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: Understanding Lambda X = 5 L = list(map(lambda x: 2**X, range(7))) print (L) ... I'm expecting this to return: [1, 2, 4, 8, 16, 32, 64] ...instead, it returns: [32, 32, 32, 32, 32, 32, 32] What am I doing wrong? A: Python is case-sensitive, so lambda x: 2**X means: take an argument, call it (lowercase) x, ignore it completely, and return 2 to the power of global variable (uppercase) X. A: Python is case-sensitive. x and X are different variables. By the way, perhaps an easier way to construct L would be L=[2**x for x in range(7)] Or, if you'd like to use map and lambda, then L=map(lambda x: 2**x, range(7)) suffices. map returns a list, so you do not have to wrap the expression in a list(...). A: Try L = list(map(lambda x: 2**x, range(7))) once. You were using X instead of x. A: You have a typo. It should be: # Upper case X refers to 5 list(map(lambda x: 2**x, range(7)))
Understanding Lambda
X = 5 L = list(map(lambda x: 2**X, range(7))) print (L) ... I'm expecting this to return: [1, 2, 4, 8, 16, 32, 64] ...instead, it returns: [32, 32, 32, 32, 32, 32, 32] What am I doing wrong?
[ "Python is case-sensitive, so lambda x: 2**X means: take an argument, call it (lowercase) x, ignore it completely, and return 2 to the power of global variable (uppercase) X.\n", "Python is case-sensitive. x and X are different variables.\nBy the way, perhaps an easier way to construct L would be \nL=[2**x for x in range(7)]\n\nOr, if you'd like to use map and lambda, then \nL=map(lambda x: 2**x, range(7))\nsuffices. map returns a list, so you do not have to wrap the expression in a list(...).\n", "Try L = list(map(lambda x: 2**x, range(7))) once. You were using X instead of x.\n", "You have a typo. It should be: \n# Upper case X refers to 5\nlist(map(lambda x: 2**x, range(7)))\n\n" ]
[ 10, 4, 2, 0 ]
[]
[]
[ "lambda", "map", "python" ]
stackoverflow_0001938189_lambda_map_python.txt
Q: Checking if A is superclass of B in Python class p1(object): pass class p2(p1): pass So p2 is the subclass of p1. Is there a way to find out programmatically that p1 is [one of] the superclass[es] of p2 ? A: using <class>.__bases__ seems to be what you're looking for... >>> class p1(object): pass >>> class p2(p1): pass >>> p2.__bases__ (<class '__main__.p1'>,) A: Yes, there is way. You can use a issubclass function. As follows: class p1(object):pass class p2(p1):pass issubclass(p2, p1) A: Depending on what you're trying to do, the "mro" method can also be useful. A: I think you meant to use "class" instead of "def".. :) Anyway, try p2.__bases__
Checking if A is superclass of B in Python
class p1(object): pass class p2(p1): pass So p2 is the subclass of p1. Is there a way to find out programmatically that p1 is [one of] the superclass[es] of p2 ?
[ "using <class>.__bases__ seems to be what you're looking for...\n>>> class p1(object): pass\n>>> class p2(p1): pass\n>>> p2.__bases__\n(<class '__main__.p1'>,)\n\n", "Yes, there is way. You can use a issubclass function.\nAs follows:\nclass p1(object):pass\nclass p2(p1):pass\n\nissubclass(p2, p1)\n\n", "Depending on what you're trying to do, the \"mro\" method can also be useful. \n", "I think you meant to use \"class\" instead of \"def\".. :) Anyway, try p2.__bases__\n" ]
[ 46, 41, 6, 5 ]
[]
[]
[ "python", "reflection", "superclass" ]
stackoverflow_0001938755_python_reflection_superclass.txt
Q: Merging multiple line segments My program uses PyOpenGL (so it's Python) with psyco. I have around 21,000 line segments which I need to render in each frame of my render (unless the user zooms in, in which case line segments are culled and not sent to the card at all). This is currently taking around 1.5 seconds each frame to complete. That's just not good enough, so I'm looking at ways to reduce the number of distinct line segments. I imagine there would be cases where multiple line segments can be merged into one big line, but I honestly do not even know where to begin with this. I do have the start point and end point of each line stored, so that might help things. Note that I am able to take as long as I need to at startup, and memory usage isn't too much of a concern. Any ideas would be much appreciated. A: It's almost certainly the overhead of all the immediate mode function calls that's killing your performance. I would do the following. Don't use GL_LINE_STRIPS, use a single list of GL_LINES instead so they can be rendered in one go. Use glDrawArrays instead of immediate mode rendering: float* coordinates = {....}; //x and y coordinate pairs for all line segments glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 2 * sizeof(float), coordinates); glDrawArrays(GL_LINES, 0, 2 * linecount); glDisableClientState(GL_VERTEX_ARRAY); (For even better performance you can store the vertex buffer in something called a vertex buffer object, but this should be fine to begin with) One final thing, if you're do culling on a per line basis it's probably faster to just skip it and send all the lines to the GPU. A: 20K segments isn't that much. Also, you'll be lucky when you can merge 10-100 lines per frame, so the speedup by this optimization will be neglectable. The rendering process is probably slow because you create the model again and again. Use glNewList() to save all the rendering commands in an GL render list on the card and then just issue glCallList() to render it with a single command. A: You can define an error metric for merging two line segments into one and then testing all pairs of segments and then merging them if the error is below a certain threshold. One example is this algorithm: Construct a new line segment X from the two points farthest away from each other in the two line segments A and B. Find the minimum distance to X for all points in A and B. Assign the error as the maximum of those minimum distances. Replace A and B with X if the error is below your threshold. This isn't the best algorithm, but it is easy to implement. Edit 1 Definitely try doing display lists or vertex buffer object rendering before implementing this.
Merging multiple line segments
My program uses PyOpenGL (so it's Python) with psyco. I have around 21,000 line segments which I need to render in each frame of my render (unless the user zooms in, in which case line segments are culled and not sent to the card at all). This is currently taking around 1.5 seconds each frame to complete. That's just not good enough, so I'm looking at ways to reduce the number of distinct line segments. I imagine there would be cases where multiple line segments can be merged into one big line, but I honestly do not even know where to begin with this. I do have the start point and end point of each line stored, so that might help things. Note that I am able to take as long as I need to at startup, and memory usage isn't too much of a concern. Any ideas would be much appreciated.
[ "It's almost certainly the overhead of all the immediate mode function calls that's killing your performance. I would do the following.\nDon't use GL_LINE_STRIPS, use a single list of GL_LINES instead so they can be rendered in one go.\nUse glDrawArrays instead of immediate mode rendering:\nfloat* coordinates = {....}; //x and y coordinate pairs for all line segments\nglEnableClientState(GL_VERTEX_ARRAY);\nglVertexPointer(2, GL_FLOAT, 2 * sizeof(float), coordinates);\nglDrawArrays(GL_LINES, 0, 2 * linecount);\nglDisableClientState(GL_VERTEX_ARRAY);\n\n(For even better performance you can store the vertex buffer in something called a vertex buffer object, but this should be fine to begin with)\nOne final thing, if you're do culling on a per line basis it's probably faster to just skip it and send all the lines to the GPU.\n", "20K segments isn't that much. Also, you'll be lucky when you can merge 10-100 lines per frame, so the speedup by this optimization will be neglectable. The rendering process is probably slow because you create the model again and again. Use glNewList() to save all the rendering commands in an GL render list on the card and then just issue glCallList() to render it with a single command.\n", "You can define an error metric for merging two line segments into one and then testing all pairs of segments and then merging them if the error is below a certain threshold.\nOne example is this algorithm:\n\nConstruct a new line segment X from the two points farthest away from each other in the two line segments A and B.\nFind the minimum distance to X for all points in A and B.\nAssign the error as the maximum of those minimum distances.\nReplace A and B with X if the error is below your threshold.\n\nThis isn't the best algorithm, but it is easy to implement.\nEdit 1\nDefinitely try doing display lists or vertex buffer object rendering before implementing this.\n" ]
[ 4, 0, 0 ]
[]
[]
[ "line_segment", "merge", "opengl", "pyopengl", "python" ]
stackoverflow_0001938831_line_segment_merge_opengl_pyopengl_python.txt
Q: Is there any libraries could import contacts from hotmail/live/aol account? I've import contacts from gmail by using gdata api, and is there any apis like that for hotmail/live/Aol ? A: There is Windows Live Contact API for Hotmail/Live mail. Yahoo Contact API for Yahoo also exists, but to this date, no AOL contact api. I would suggest you try openinviter (openinviter.com) to import contacts. Unfortunately, you will not have OAuth capabilities, but it is the best class out there and works with 90+ different email providers. Note: it is written in php, but creating a wrapper won't be too hard. A: If you are able to export from them to the standard vCard format, you can read and process vCard data using the vobject package. A: Hotmail/Live There is Windows Live Contact API for Hotmail/Live mail, which is similar to GData API. AOL As far as I remember AOL doesn't provide API to access its address book, however they working on it (for long time)...
Is there any libraries could import contacts from hotmail/live/aol account?
I've import contacts from gmail by using gdata api, and is there any apis like that for hotmail/live/Aol ?
[ "There is Windows Live Contact API for Hotmail/Live mail.\nYahoo Contact API for Yahoo also exists, but to this date, no AOL contact api. \nI would suggest you try openinviter (openinviter.com) to import contacts. Unfortunately, you will not have OAuth capabilities, but it is the best class out there and works with 90+ different email providers. \nNote: it is written in php, but creating a wrapper won't be too hard.\n", "If you are able to export from them to the standard vCard format, you can read and process vCard data using the vobject package.\n", "Hotmail/Live\nThere is Windows Live Contact API for Hotmail/Live mail, which is similar to GData API.\nAOL\nAs far as I remember AOL doesn't provide API to access its address book, however they working on it (for long time)...\n" ]
[ 2, 1, 1 ]
[]
[]
[ "api", "python" ]
stackoverflow_0001938945_api_python.txt
Q: changing image resolution in Python for a .bmp file I want to change the resolution of the .bmp image in python. ( i.e. the pixel/inch information) . Using PIL, for jpg image, for instance, the following code works fine import Image im = Image.open("myImg.jpg) im.save("output.jpg", dpi = (75, 75) ) If you view this in some image editing software like GIMP, it shows the Pixel per inch as 75, 75. But the above code doesn't work when the input image is a .bmp file. Could someone tell me how to change image resolution for any image in python? A: I suspect that there aren't many programs out there that respect bmp resolution. Windows bitmaps are all 96 dpi. Also, It looks as though PIL doesn't support a resolution parameter for bitmaps. My PIL/BmpImagePlugin.py just writes in $01000000 for the x & y resolution (i'm not sure what that translates to, but I'd guess "96 dpi"). There are docs which tell you how to write your own extension .. I'd guess it would be pretty simple to make a copy of the PIL bitmap plugin which accepted resolution as a parameter. A: I think input file can be any valid format and output need to be, jpg, pcx, png, tiff, wmf for dpi parameter I think, may be I am wrong, but when I looked at PIL source files, I don't see one for BMP files.
changing image resolution in Python for a .bmp file
I want to change the resolution of the .bmp image in python. ( i.e. the pixel/inch information) . Using PIL, for jpg image, for instance, the following code works fine import Image im = Image.open("myImg.jpg) im.save("output.jpg", dpi = (75, 75) ) If you view this in some image editing software like GIMP, it shows the Pixel per inch as 75, 75. But the above code doesn't work when the input image is a .bmp file. Could someone tell me how to change image resolution for any image in python?
[ "I suspect that there aren't many programs out there that respect bmp resolution. Windows bitmaps are all 96 dpi.\nAlso, It looks as though PIL doesn't support a resolution parameter for bitmaps. My PIL/BmpImagePlugin.py just writes in $01000000 for the x & y resolution (i'm not sure what that translates to, but I'd guess \"96 dpi\"). \nThere are docs which tell you how to write your own extension .. I'd guess it would be pretty simple to make a copy of the PIL bitmap plugin which accepted resolution as a parameter. \n", "I think input file can be any valid format and output need to be, jpg, pcx, png, tiff, wmf for dpi parameter I think, may be I am wrong, but when I looked at PIL source files, I don't see one for BMP files.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0001938959_python_python_imaging_library.txt
Q: csv to sparse matrix in python I have a big csv file which lists connections between nodes in a graph. example: 0001,95784 0001,98743 0002,00082 0002,00091 So this means that node id 0001 is connected to node 95784 and 98743 and so on. I need to read this into a sparse matrix in numpy. How can i do this? I am new to python so tutorials on this would also help. A: Example using lil_matrix (list of list matrix) of scipy. Row-based linked list matrix. This contains a list (self.rows) of rows, each of which is a sorted list of column indices of non-zero elements. It also contains a list (self.data) of lists of these elements. $ cat 1938894-simplified.csv 0,32 1,21 1,23 1,32 2,23 2,53 2,82 3,82 4,46 5,75 7,86 8,28 Code: #!/usr/bin/env python import csv from scipy import sparse rows, columns = 10, 100 matrix = sparse.lil_matrix( (rows, columns) ) csvreader = csv.reader(open('1938894-simplified.csv')) for line in csvreader: row, column = map(int, line) matrix.data[row].append(column) print matrix.data Output: [[32] [21, 23, 32] [23, 53, 82] [82] [46] [75] [] [86] [28] []] A: If you want an adjacency matrix, you can do something like: from scipy.sparse import * from scipy import * from numpy import * import csv S = dok_matrix((10000,10000), dtype=bool) f = open("your_file_name") reader = csv.reader(f) for line in reader: S[int(line[0]),int(line[1])] = True A: You might also be interested in Networkx, a pure python network/graphing package. From the website: NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. >>> import networkx as nx >>> G=nx.Graph() >>> G.add_edge(1,2) >>> G.add_node("spam") >>> print G.nodes() [1, 2, 'spam'] >>> print G.edges() [(1, 2)]
csv to sparse matrix in python
I have a big csv file which lists connections between nodes in a graph. example: 0001,95784 0001,98743 0002,00082 0002,00091 So this means that node id 0001 is connected to node 95784 and 98743 and so on. I need to read this into a sparse matrix in numpy. How can i do this? I am new to python so tutorials on this would also help.
[ "Example using lil_matrix (list of list matrix) of scipy.\n\nRow-based linked list matrix.\nThis contains a list (self.rows) of rows, each of which is a sorted list of column indices of non-zero elements. It also contains a list (self.data) of lists of these elements.\n\n$ cat 1938894-simplified.csv\n0,32\n1,21\n1,23\n1,32\n2,23\n2,53\n2,82\n3,82\n4,46\n5,75\n7,86\n8,28\n\nCode:\n#!/usr/bin/env python\n\nimport csv\nfrom scipy import sparse\n\nrows, columns = 10, 100\nmatrix = sparse.lil_matrix( (rows, columns) )\n\ncsvreader = csv.reader(open('1938894-simplified.csv'))\nfor line in csvreader:\n row, column = map(int, line)\n matrix.data[row].append(column)\n\nprint matrix.data\n\nOutput:\n[[32] [21, 23, 32] [23, 53, 82] [82] [46] [75] [] [86] [28] []]\n\n", "If you want an adjacency matrix, you can do something like:\nfrom scipy.sparse import *\nfrom scipy import *\nfrom numpy import *\nimport csv\nS = dok_matrix((10000,10000), dtype=bool)\nf = open(\"your_file_name\")\nreader = csv.reader(f)\nfor line in reader:\n S[int(line[0]),int(line[1])] = True\n\n", "You might also be interested in Networkx, a pure python network/graphing package.\nFrom the website:\n\nNetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks.\n\n>>> import networkx as nx\n>>> G=nx.Graph()\n>>> G.add_edge(1,2)\n>>> G.add_node(\"spam\")\n>>> print G.nodes()\n[1, 2, 'spam']\n>>> print G.edges()\n[(1, 2)]\n\n" ]
[ 12, 2, 2 ]
[]
[]
[ "data_structures", "python", "sparse_matrix" ]
stackoverflow_0001938894_data_structures_python_sparse_matrix.txt
Q: django + mysql + UTF-8 - Chars are not displayed I have both, django and mysql set to work with UTF-8. My base.html set utf-8 in head. row on my db : +----+--------+------------------------------------------------------------------+-----------------------------+-----------------------------+---------------------+ | id | psn_id | name | publisher | developer | release_date | +----+--------+------------------------------------------------------------------+-----------------------------+-----------------------------+---------------------+ | 1 | 10945- | まいにけいっしょ | Sony Computer Entertainment | Sony Computer Entertainment | 2006-11-11 00:00:00 | +----+--------+------------------------------------------------------------------+-----------------------------+-----------------------------+---------------------+ the source code generated looks like : &#12414;&#12356;&#12395;&#12385;&#12356;&#12387;&#12375;&#12423; and this is wat is displayed :/ why they are not showing the chars the way in this database? A: That source code, when placed into an otherwise empty HTML document, looks like this for me in Google Chrome, IE and Firefox: まいにけいっしょ Which appears to be what you want. My only thought is that that is not really the source code, and you've in fact got source code that looks like this: &amp;#12414;&amp;#12356;&amp;#12395;&amp;#12385;&amp;#12356;&amp;#12387;&amp;#12375;&amp;#12423; in which case you're HTML-encoding something that's already HTML-encoded. If that's not the case, then I've no idea. The source I used to test this is: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Foo</title> </head> <body> <p>&#12414;&#12356;&#12395;&#12385;&#12356;&#12387;&#12375;&#12423;</p> </body> </html> A: As Dominic has said, the generated HTML source code is correct (these are your Japanese characters translated into HTML entities), but we're not sure, if you see the same code rendered in the page (in this case, you have probably set content-type to "text/plain" instead of "text/html" - do you use render_to_response() or HttpResponse() in the corresponding view.py method?), or your Japanese is rendered correctly but you just don't like the entities in the source code. Since we don't know your Django settings and how do you render and return the page, it's difficult to provide you the solution. A: the problem is the auto escape django function ... my source code is like the one that Dominic pasted : &#12414;&#12356;&#12395;&#12385;&#12356;&#12387;&#12375;&#12423; i simple put the tag in places there i known that may be some diff chars: {% autoescape off %} xxxxx {% endautoescape %} and everything works like a charm... :D than you all http://docs.djangoproject.com/en/dev/ref/templates/builtins/#autoescape
django + mysql + UTF-8 - Chars are not displayed
I have both, django and mysql set to work with UTF-8. My base.html set utf-8 in head. row on my db : +----+--------+------------------------------------------------------------------+-----------------------------+-----------------------------+---------------------+ | id | psn_id | name | publisher | developer | release_date | +----+--------+------------------------------------------------------------------+-----------------------------+-----------------------------+---------------------+ | 1 | 10945- | まいにけいっしょ | Sony Computer Entertainment | Sony Computer Entertainment | 2006-11-11 00:00:00 | +----+--------+------------------------------------------------------------------+-----------------------------+-----------------------------+---------------------+ the source code generated looks like : &#12414;&#12356;&#12395;&#12385;&#12356;&#12387;&#12375;&#12423; and this is wat is displayed :/ why they are not showing the chars the way in this database?
[ "That source code, when placed into an otherwise empty HTML document, looks like this for me in Google Chrome, IE and Firefox:\n\nまいにけいっしょ\n\nWhich appears to be what you want.\nMy only thought is that that is not really the source code, and you've in fact got source code that looks like this:\n&amp;#12414;&amp;#12356;&amp;#12395;&amp;#12385;&amp;#12356;&amp;#12387;&amp;#12375;&amp;#12423;\n\nin which case you're HTML-encoding something that's already HTML-encoded.\nIf that's not the case, then I've no idea.\nThe source I used to test this is:\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> \n<html xmlns=\"http://www.w3.org/1999/xhtml\"> \n <head> \n <title>Foo</title> \n </head> \n <body> \n <p>&#12414;&#12356;&#12395;&#12385;&#12356;&#12387;&#12375;&#12423;</p>\n </body> \n</html>\n\n", "As Dominic has said, the generated HTML source code is correct (these are your Japanese characters translated into HTML entities), but we're not sure, if you see the same code rendered in the page (in this case, you have probably set content-type to \"text/plain\" instead of \"text/html\" - do you use render_to_response() or HttpResponse() in the corresponding view.py method?), or your Japanese is rendered correctly but you just don't like the entities in the source code.\nSince we don't know your Django settings and how do you render and return the page, it's difficult to provide you the solution.\n", "the problem is the auto escape django function ...\nmy source code is like the one that Dominic pasted :\n\n&#12414;&#12356;&#12395;&#12385;&#12356;&#12387;&#12375;&#12423;\n\ni simple put the tag in places there i known that may be some diff chars:\n\n{% autoescape off %}\nxxxxx\n{% endautoescape %}\n\nand everything works like a charm... :D\nthan you all\nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#autoescape\n" ]
[ 3, 0, 0 ]
[]
[]
[ "django", "python", "unicode" ]
stackoverflow_0001928087_django_python_unicode.txt
Q: Most used Python module for video processing? I need to: Open a video file Iterate over the frames of the file as images Do some analysis in this image frame of the video Draw in this image of the video Create a new video with these changes OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst? Thank you! A: Do you mean opencv can't connect to your webcam or can't read video files recorded by it? Have you tried saving the video in an other format? OpenCV is probably the best supported python image processing tool A: I'm going through this myself. It's only a couple of lines in MATLAB using mmreader, but I've already blown two work days trying to figure out how to pull frames from a video file into numpy. If you have enough disk space, and it doesn't have to be real time, you can use: mplayer -noconsolecontrols -vo png blah.mov and then pull the .png files into numpy using: pylab.imread('blah0000001.png') I know this is incomplete, but it may still help you. Good luck! A: I used this script to convert a movie to a numpy array + binary store: """ Takes a MPEG movie and produces a numpy record file with a numpy array. """ import os filename = 'walking' if not(os.path.isfile(filename + '.npy')): # do nothing if files exists N_frame = 42 # number of frames we want to store os.system('ffmpeg -i WALK.MOV.qt -f image2 foo-%03d.png') # convert them to numpy from numpy import zeros, save, mean from pylab import imread n_x, n_y, n_rgb = imread('foo-001.png').shape mov = zeros((n_y, n_x, N_frame)) for i_frame in range(N_frame): name = 'foo-%03d.png' % (i_frame +1) mov[:n_y,:n_x,i_frame] = flipud(mean(imread(name), axis=2)).T os.system('rm -f foo-*.png') save(filename + '.npy', mov) note that depending on your conventions you may not want to flip the image. you may then load it using : load('walking.npy') A: Just build a C/C++ wrapper for your webcam and then use SWIG or SIP to access these functions from Python. Then use OpenCV in Python that's the best open sourced computer vision library in the wild. If you worry for performance and you work under Linux, you could download free versions of Intel Performance Primitives (IPP) that could be loaded at runtime with zero effort from OpenCV. For certain algorithms you could get a 200% boost of performances, plus automatic multicore support for most of time consuming functions.
Most used Python module for video processing?
I need to: Open a video file Iterate over the frames of the file as images Do some analysis in this image frame of the video Draw in this image of the video Create a new video with these changes OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst? Thank you!
[ "Do you mean opencv can't connect to your webcam or can't read video files recorded by it?\nHave you tried saving the video in an other format?\nOpenCV is probably the best supported python image processing tool \n", "I'm going through this myself. It's only a couple of lines in MATLAB using mmreader, but I've already blown two work days trying to figure out how to pull frames from a video file into numpy. If you have enough disk space, and it doesn't have to be real time, you can use:\nmplayer -noconsolecontrols -vo png blah.mov\n\nand then pull the .png files into numpy using:\npylab.imread('blah0000001.png')\n\nI know this is incomplete, but it may still help you. Good luck!\n", "I used this script to convert a movie to a numpy array + binary store:\n\"\"\"\nTakes a MPEG movie and produces a numpy record file with a numpy array.\n\n\"\"\"\nimport os\n\nfilename = 'walking'\nif not(os.path.isfile(filename + '.npy')): # do nothing if files exists\n N_frame = 42 # number of frames we want to store\n os.system('ffmpeg -i WALK.MOV.qt -f image2 foo-%03d.png')\n # convert them to numpy\n from numpy import zeros, save, mean\n from pylab import imread\n\n n_x, n_y, n_rgb = imread('foo-001.png').shape\n\n mov = zeros((n_y, n_x, N_frame))\n\n for i_frame in range(N_frame):\n name = 'foo-%03d.png' % (i_frame +1)\n mov[:n_y,:n_x,i_frame] = flipud(mean(imread(name), axis=2)).T\n\n os.system('rm -f foo-*.png')\n save(filename + '.npy', mov)\n\nnote that depending on your conventions you may not want to flip the image. you may then load it using :\nload('walking.npy')\n\n", "Just build a C/C++ wrapper for your webcam and then use SWIG or SIP to access these functions from Python. Then use OpenCV in Python that's the best open sourced computer vision library in the wild.\nIf you worry for performance and you work under Linux, you could download free versions of Intel Performance Primitives (IPP) that could be loaded at runtime with zero effort from OpenCV. For certain algorithms you could get a 200% boost of performances, plus automatic multicore support for most of time consuming functions.\n" ]
[ 7, 3, 3, 0 ]
[]
[]
[ "image_processing", "python", "video_processing" ]
stackoverflow_0001480431_image_processing_python_video_processing.txt
Q: Python for Sony Ericsson Is it possible to install python on Sony Ericsson mobile phones? A: The Sony Ericsson Xperia x10 since Android phones can run python. Not sure about other Sony Ericsson phones A: Nokia Symbian S60 have Python: http://opensource.nokia.com/projects/pythonfors60/
Python for Sony Ericsson
Is it possible to install python on Sony Ericsson mobile phones?
[ "The Sony Ericsson Xperia x10 since Android phones can run python. Not sure about other Sony Ericsson phones\n", "Nokia Symbian S60 have Python: \nhttp://opensource.nokia.com/projects/pythonfors60/\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001939181_python.txt
Q: Django Sessions I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them? A: The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it. The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost. If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases. A: I'm no Django expert, so this answer is about session stores generally. Downvote if I'm wrong. Performance and Scalability Choice of session store has an effect on performance and scalability. This should only be a big problem if you have a very popular application. Both database and filesystem session stores are (usually) backed by disks so you can have a lot of sessions cheaply (because disks are cheap), but requests will often have to wait for the data to be read (because disks are slow). Memcached sessions use RAM, so will cost more to support the same number of concurrent sessions (because RAM is expensive), but may be faster (because RAM is fast). Filesystem sessions are tied to the box where your application is running, so you can't load balance between multiple application servers if your site gets huge. Database and memcached sessions let you have multiple application servers talking to a shared session store. Simplicity Choice of session store will also impact how easy it is to deploy your site. Changing away from the default will cost some complexity. Memcached and RDBMSs both have their own complexities, but your application is probably going to be using an RDBMS anyway. Unless you have a very popular application, simplicity should be the larger concern. Bonus Another approach is to store session data in cookies (all of it, not just an ID). This has the advantage that the session store automatically scales with the number of users, but it has disadvantages too. You (or your framework) need to be careful to stop users forging session data. You also need to keep each session small because the whole thing will be sent with every request. A: As of Django 1.1 you can use the cached_db session back end. This stores the session in the cache (only use with memcached), and writes it back to the DB. If it has fallen out of the cache, it will be read from the DB. Although this is slower than just using memcached for storing the session, it adds persistence to the session. For more information, see: Django Docs: Using Cached Sessions A: One thing that has to be considered when choosing session backend is "how often session data is modified"? Even sites with moderate traffic will suffer if session data is modified on each request, making many database trips to store and retrieve data. In my previous work we used memcache as session backend exclusively and it worked really well. Our administrative team put really great effort in making two special memcached instances stable as a rock, but after bit of twiddling with initial setup, we did not have any interrupts of session backends operations. A: If the database have a DBA that isn't you, you may not be allowed to use a database-backed session (it being a front-end matter only). Until django supports easily merging data from several databases, so that you can have frontend-specific stuff like sessions and user-messages (the messages in django.contrib.auth are also stored in the db) in a separate db, you need to keep this in mind.
Django Sessions
I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?
[ "The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.\nThe memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost.\nIf you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases.\n", "I'm no Django expert, so this answer is about session stores generally. Downvote if I'm wrong.\nPerformance and Scalability\nChoice of session store has an effect on performance and scalability. This should only be a big problem if you have a very popular application.\nBoth database and filesystem session stores are (usually) backed by disks so you can have a lot of sessions cheaply (because disks are cheap), but requests will often have to wait for the data to be read (because disks are slow). Memcached sessions use RAM, so will cost more to support the same number of concurrent sessions (because RAM is expensive), but may be faster (because RAM is fast).\nFilesystem sessions are tied to the box where your application is running, so you can't load balance between multiple application servers if your site gets huge. Database and memcached sessions let you have multiple application servers talking to a shared session store.\nSimplicity\nChoice of session store will also impact how easy it is to deploy your site. Changing away from the default will cost some complexity. Memcached and RDBMSs both have their own complexities, but your application is probably going to be using an RDBMS anyway.\nUnless you have a very popular application, simplicity should be the larger concern.\nBonus\nAnother approach is to store session data in cookies (all of it, not just an ID). This has the advantage that the session store automatically scales with the number of users, but it has disadvantages too. You (or your framework) need to be careful to stop users forging session data. You also need to keep each session small because the whole thing will be sent with every request.\n", "As of Django 1.1 you can use the cached_db session back end.\nThis stores the session in the cache (only use with memcached), and writes it back to the DB. If it has fallen out of the cache, it will be read from the DB.\nAlthough this is slower than just using memcached for storing the session, it adds persistence to the session.\nFor more information, see: Django Docs: Using Cached Sessions\n", "One thing that has to be considered when choosing session backend is \"how often session data is modified\"? Even sites with moderate traffic will suffer if session data is modified on each request, making many database trips to store and retrieve data.\nIn my previous work we used memcache as session backend exclusively and it worked really well. Our administrative team put really great effort in making two special memcached instances stable as a rock, but after bit of twiddling with initial setup, we did not have any interrupts of session backends operations.\n", "If the database have a DBA that isn't you, you may not be allowed to use a database-backed session (it being a front-end matter only). Until django supports easily merging data from several databases, so that you can have frontend-specific stuff like sessions and user-messages (the messages in django.contrib.auth are also stored in the db) in a separate db, you need to keep this in mind.\n" ]
[ 25, 19, 10, 3, 1 ]
[]
[]
[ "caching", "django", "mongodb", "python", "session" ]
stackoverflow_0000050568_caching_django_mongodb_python_session.txt
Q: Variables in python os.path I am new to python and I'm trying to create a program that creates a directory with todays date, create a sandbox into that directory and run the make file in the sandbox. I am having trouble getting the variables to be picked up in the os.path lines. The code is posted below: #!/usr/bin/python import mks_function from mks_function import mks_create_sandbox import sys, os, time, datetime import os.path today = datetime.date.today() # get today's date as a datetime type todaystr = today.isoformat() # get string representation: YYYY-MM-DD # from a datetime type. if not os.path.exists('/home/build/test/sandboxes/'+todaystr): os.mkdir(todaystr) else: pass if not os.path.exists('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/project.pj'): mks_create_sandbox() else: pass if os.path.exists('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/Makefile'): os.system("make >make_results.txt 2>&1") Any help would be appreciated, Thanks A: a couple of notes: #!/usr/bin/env python # import mks_function .. you won't need this ... from mks_function import mks_create_sandbox import os, datetime # import time, sys .. these aren't used in this snippet # import os.path .. just refer to os.path, since os is already imported # get today's date as a datetime type todaystr = datetime.date.today().isoformat() # .. use os.path.join() if not os.path.exists(os.path.join('/home/build/test/sandboxes/', todaystr)): os.mkdir(os.path.join('/home/build/test/sandboxes/', todaystr)) # .. 'else: pass' is unnecessary if not os.path.exists(os.path.join( '/home/build/test/sandboxes/', todaystr, '/new_sandbox/project.pj')): # i'm not seen, that the sandbox is created in the right directory here # maybe you should change the working directory via .. # os.chdir(os.path.join('/home/build/test/sandboxes/', todaystr)) mks_create_sandbox() if os.path.exists(os.path.join( '/home/build/test/sandboxes/', todaystr, '/new_sandbox/Makefile')): # .. change to the right directory os.chdir(os.path.join( '/home/build/test/sandboxes/', todaystr, '/new_sandbox/')) os.system("make > make_results.txt 2>&1") A: I think you want to change a few things: def makeSandbox(): sbdir = os.path.join('/home/build/test/sandboxes/',todaystr) if not os.path.exists(sbdir): os.mkdir(sbdir) # <- fully qualified path else: pass And I don't really see what variables need to be picked up, seems fine to me. A: Please try adding chdir code before you call make if os.path.exists('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/Makefile'): os.chdir('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/') os.system("make >make_results.txt 2>&1") A: Not sure what the module mks_function does. But I see one issue with your code. For example, if not os.path.exists('/home/build/test/sandboxes/'+todaystr): os.mkdir(todaystr) In the above chunk you check if the directory "/home/build/test/sandboxes/+'todaystr'" exists and a create a directory by name "value contained in todaystr" (say 2009-12-21). This creates directory by name '2009-12-21' in the current working directory, rather than under : /home/build/test/sandboxes which is what you intended I guess. So change to the above directory before the call to mkdir. Also it is good to check the return status of mkdir to verify if the directory creation succeeded. A: path module might help in this case: #!/usr/bin/env python from mks_function import mks_create_sandbox import os, datetime from path import path sandboxes = path('/home/build/test/sandboxes/') today = sandboxes / datetime.date.today().isoformat() today.mkdir() # create directory if it doesn't exist project = today / "new_sandbox/project.pj" project.parent.mkdir() # create sandbox directory if it doesn't exist if not project.isfile(): mks_create_sandbox() makefile = project.parent / "Makefile" if makefile.isfile(): os.chdir(makefile.parent) os.system("make >make_results.txt 2>&1")
Variables in python os.path
I am new to python and I'm trying to create a program that creates a directory with todays date, create a sandbox into that directory and run the make file in the sandbox. I am having trouble getting the variables to be picked up in the os.path lines. The code is posted below: #!/usr/bin/python import mks_function from mks_function import mks_create_sandbox import sys, os, time, datetime import os.path today = datetime.date.today() # get today's date as a datetime type todaystr = today.isoformat() # get string representation: YYYY-MM-DD # from a datetime type. if not os.path.exists('/home/build/test/sandboxes/'+todaystr): os.mkdir(todaystr) else: pass if not os.path.exists('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/project.pj'): mks_create_sandbox() else: pass if os.path.exists('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/Makefile'): os.system("make >make_results.txt 2>&1") Any help would be appreciated, Thanks
[ "a couple of notes: \n#!/usr/bin/env python \n# import mks_function .. you won't need this ...\n\nfrom mks_function import mks_create_sandbox \nimport os, datetime \n\n# import time, sys .. these aren't used in this snippet \n# import os.path .. just refer to os.path, since os is already imported\n\n# get today's date as a datetime type \ntodaystr = datetime.date.today().isoformat() \n\n# .. use os.path.join()\nif not os.path.exists(os.path.join('/home/build/test/sandboxes/', todaystr)): \n os.mkdir(os.path.join('/home/build/test/sandboxes/', todaystr)) \n# .. 'else: pass' is unnecessary\n\nif not os.path.exists(os.path.join(\n '/home/build/test/sandboxes/', todaystr, '/new_sandbox/project.pj')): \n\n # i'm not seen, that the sandbox is created in the right directory here\n # maybe you should change the working directory via ..\n # os.chdir(os.path.join('/home/build/test/sandboxes/', todaystr))\n mks_create_sandbox() \n\nif os.path.exists(os.path.join(\n '/home/build/test/sandboxes/', todaystr, '/new_sandbox/Makefile')): \n\n # .. change to the right directory\n os.chdir(os.path.join(\n '/home/build/test/sandboxes/', todaystr, '/new_sandbox/'))\n\n os.system(\"make > make_results.txt 2>&1\") \n\n", "I think you want to change a few things:\ndef makeSandbox():\n sbdir = os.path.join('/home/build/test/sandboxes/',todaystr)\n if not os.path.exists(sbdir): \n os.mkdir(sbdir) # <- fully qualified path\n else: \n pass\n\nAnd I don't really see what variables need to be picked up, seems fine to me.\n", "Please try adding chdir code before you call make\nif os.path.exists('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/Makefile'):\n os.chdir('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/')\n os.system(\"make >make_results.txt 2>&1\")\n\n", "Not sure what the module mks_function does. But I see one issue with your code. \nFor example,\n\nif not os.path.exists('/home/build/test/sandboxes/'+todaystr): \n os.mkdir(todaystr) \n\n\nIn the above chunk you check if the directory \"/home/build/test/sandboxes/+'todaystr'\"\nexists and a create a directory by name \"value contained in todaystr\" (say 2009-12-21). This creates directory by name '2009-12-21' in the current working directory, rather than under : /home/build/test/sandboxes\nwhich is what you intended I guess. So change to the above directory before the call to mkdir. Also it is good to check the return status of mkdir to verify if the directory creation succeeded.\n", "path module might help in this case:\n#!/usr/bin/env python \nfrom mks_function import mks_create_sandbox \nimport os, datetime \n\nfrom path import path\n\nsandboxes = path('/home/build/test/sandboxes/')\ntoday = sandboxes / datetime.date.today().isoformat()\ntoday.mkdir() # create directory if it doesn't exist\n\nproject = today / \"new_sandbox/project.pj\"\nproject.parent.mkdir() # create sandbox directory if it doesn't exist\nif not project.isfile(): \n mks_create_sandbox() \n\nmakefile = project.parent / \"Makefile\"\nif makefile.isfile():\n os.chdir(makefile.parent) \n os.system(\"make >make_results.txt 2>&1\")\n\n" ]
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001939496_python.txt
Q: Dynamically import class by name for static access I am generating class names dynamically and then want to import that class by its name to access a static method. This is the class to import in "the_module.py": class ToImport(object): @classmethod def initialize(cls, parameter): print parameter According to a Blog post this is as far as I came: theModule = __import__("the_module") toImport = getattr(theModule, "ToImport") toImport.initialize("parameter") But the blog example seems to be incomplete as it gives me a module object without my desired class ToImport. Looking at the __import__() documentation shows me that there are more optional attributes to the function. I succeeded with theModule = __import__("the_module", globals(), locals(), ["ToImport"]) Why do I have to give the fromlist attribute? Can't I import all the modules attributes? A: I have done exactly what you did and I retrieved the class. In [1]: theModule = __import__("the_module") In [2]: toImport = getattr(theModule, "ToImport") In [3]: toImport.initialize("parameter") parameter I am using Python 2.6.4. Could you explain further, what exactly doesn't work for you?
Dynamically import class by name for static access
I am generating class names dynamically and then want to import that class by its name to access a static method. This is the class to import in "the_module.py": class ToImport(object): @classmethod def initialize(cls, parameter): print parameter According to a Blog post this is as far as I came: theModule = __import__("the_module") toImport = getattr(theModule, "ToImport") toImport.initialize("parameter") But the blog example seems to be incomplete as it gives me a module object without my desired class ToImport. Looking at the __import__() documentation shows me that there are more optional attributes to the function. I succeeded with theModule = __import__("the_module", globals(), locals(), ["ToImport"]) Why do I have to give the fromlist attribute? Can't I import all the modules attributes?
[ "I have done exactly what you did and I retrieved the class.\nIn [1]: theModule = __import__(\"the_module\")\n\nIn [2]: toImport = getattr(theModule, \"ToImport\")\n\nIn [3]: toImport.initialize(\"parameter\")\nparameter\n\nI am using Python 2.6.4. Could you explain further, what exactly doesn't work for you?\n" ]
[ 2 ]
[]
[]
[ "class", "import", "python" ]
stackoverflow_0001939622_class_import_python.txt
Q: Python sorts "u11-Phrase 1000.wav" before "u11-Phrase 101.wav"; how can I overcome this? I'm running Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 When I'm asking Python >>> "u11-Phrase 099.wav" < "u11-Phrase 1000.wav" True That's fine. When I ask >>> "u11-Phrase 100.wav" < "u11-Phrase 1000.wav" True That's fine, too. But when I ask >>> "u11-Phrase 101.wav" < "u11-Phrase 1000.wav" False So according Python "u11-Phrase 100.wav" comes before "u11-Phrase 1000.wav" but "u11-Phrase 101.wav" comes after "u11-Phrase 1000.wav"! And this is problematic for me because I'm trying to write a file renaming program and this kind of sorting breaks the functionality. What can I do to overcome this? Should I write my own cmp function and test for edge cases or is there a much simpler shortcut to give me the ordering I want? On the other hand if I modify the strings such as >>> "u11-Phrase 0101.wav" < "u11-Phrase 1000.wav" True However those strings come from the file listing of directory such as: files = glob.glob('*.wav') files.sort() for file in files: ... So I'd rather not do surgical operations on the strings after they have been created by glob. And no, I don't want to change the original filenames in that folder, too. Any hints? A: You are looking for human sorting. The reason 101.wav is not less than 1000.wav is that computers (not just Python) sort strings character by character, and the first difference between these two strings is where the first string has a '1' and the second string has a '0'. '1' is not less than '0', so the strings compare as you have seen. People naturally parse those strings into their components, and interpret the numbers numerically, not lexically. The code I linked to above will do that same sort of parsing. A: You need to construct a proper sort key for each filename. Something like this should do what you want: import re def k(s): return [w.isdigit() and int(w) or w for w in re.split(r'(\d+)', s)] files = ["u11-Phrase 099.wav", "u11-Phrase 1000.wav", "u11-Phrase 100.wav"] print files print sorted(files, key=k) It gives this output: ['u11-Phrase 099.wav', 'u11-Phrase 1000.wav', 'u11-Phrase 100.wav'] ['u11-Phrase 099.wav', 'u11-Phrase 100.wav', 'u11-Phrase 1000.wav'] The k function will split apart the filenames on sequences of digits and (more importantly) turn those sequences into integers: >>> k('u11-Phrase 099.wav') ['u', 11, '-Phrase ', 99, '.wav'] We then use the fact that Python knows how to sort lists --- it sorts the lists by comparing each element one by one. The end result is that >>> k('u11-Phrase 99.wav') < k('u11-Phrase 100.wav') True whereas >>> 'u11-Phrase 99.wav' < 'u11-Phrase 100.wav' False as you've already found out.
Python sorts "u11-Phrase 1000.wav" before "u11-Phrase 101.wav"; how can I overcome this?
I'm running Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 When I'm asking Python >>> "u11-Phrase 099.wav" < "u11-Phrase 1000.wav" True That's fine. When I ask >>> "u11-Phrase 100.wav" < "u11-Phrase 1000.wav" True That's fine, too. But when I ask >>> "u11-Phrase 101.wav" < "u11-Phrase 1000.wav" False So according Python "u11-Phrase 100.wav" comes before "u11-Phrase 1000.wav" but "u11-Phrase 101.wav" comes after "u11-Phrase 1000.wav"! And this is problematic for me because I'm trying to write a file renaming program and this kind of sorting breaks the functionality. What can I do to overcome this? Should I write my own cmp function and test for edge cases or is there a much simpler shortcut to give me the ordering I want? On the other hand if I modify the strings such as >>> "u11-Phrase 0101.wav" < "u11-Phrase 1000.wav" True However those strings come from the file listing of directory such as: files = glob.glob('*.wav') files.sort() for file in files: ... So I'd rather not do surgical operations on the strings after they have been created by glob. And no, I don't want to change the original filenames in that folder, too. Any hints?
[ "You are looking for human sorting.\nThe reason 101.wav is not less than 1000.wav is that computers (not just Python) sort strings character by character, and the first difference between these two strings is where the first string has a '1' and the second string has a '0'. '1' is not less than '0', so the strings compare as you have seen.\nPeople naturally parse those strings into their components, and interpret the numbers numerically, not lexically. The code I linked to above will do that same sort of parsing.\n", "You need to construct a proper sort key for each filename. Something like this should do what you want:\nimport re\n\ndef k(s):\n return [w.isdigit() and int(w) or w for w in re.split(r'(\\d+)', s)]\n\nfiles = [\"u11-Phrase 099.wav\", \"u11-Phrase 1000.wav\", \"u11-Phrase 100.wav\"]\n\nprint files\nprint sorted(files, key=k)\n\nIt gives this output:\n['u11-Phrase 099.wav', 'u11-Phrase 1000.wav', 'u11-Phrase 100.wav']\n['u11-Phrase 099.wav', 'u11-Phrase 100.wav', 'u11-Phrase 1000.wav']\n\nThe k function will split apart the filenames on sequences of digits and (more importantly) turn those sequences into integers:\n>>> k('u11-Phrase 099.wav')\n['u', 11, '-Phrase ', 99, '.wav']\n\nWe then use the fact that Python knows how to sort lists --- it sorts the lists by comparing each element one by one. The end result is that\n>>> k('u11-Phrase 99.wav') < k('u11-Phrase 100.wav')\nTrue\n\nwhereas\n>>> 'u11-Phrase 99.wav' < 'u11-Phrase 100.wav'\nFalse\n\nas you've already found out.\n" ]
[ 16, 9 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0001940056_python_sorting.txt
Q: Run XBMC plugins in a .net application Is there any way to use xbmc plugins in .net? im thinking about those plugins that provide access to media content like GameTrailers and stuff like that.. A: I believe the plugin system is based on Python. You may be able to use IronPython to run some of the plugins in XBMC, although it may not be 100% compatible. You could also take the Python code and create a COM server object in which you could use .NET interop to interface with it.
Run XBMC plugins in a .net application
Is there any way to use xbmc plugins in .net? im thinking about those plugins that provide access to media content like GameTrailers and stuff like that..
[ "I believe the plugin system is based on Python. You may be able to use IronPython to run some of the plugins in XBMC, although it may not be 100% compatible. You could also take the Python code and create a COM server object in which you could use .NET interop to interface with it.\n" ]
[ 1 ]
[]
[]
[ ".net", "python", "xbmc" ]
stackoverflow_0001940150_.net_python_xbmc.txt
Q: Python tell when an ftp transfer sits on completion I have to download some files from an FTP server. Seems prosaic enough. However, the way this server behaves is if the file is very large, the connection will just hang when the download ostensibly completes. How can I handle this gracefully using ftplib in python? Sample python code: from ftplib import FTP ... ftp = FTP(host) ftp.login(login, passwd) files=ftp.nlst() ftp.set_debuglevel(2) for fname in files: ret_status = ftp.retrbinary('RETR ' + fname, open(fname, 'wb').write) debug output from the above: *cmd* 'TYPE I' *put* 'TYPE I\r\n' *get* '200 Type set to I.\r\n' *resp* '200 Type set to I.' *cmd* 'PASV' *put* 'PASV\r\n' *get* '227 Entering Passive Mode (0,0,0,0,10,52).\r\n' *resp* '227 Entering Passive Mode (0,0,0,0,10,52).' *cmd* 'RETR some_file' *put* 'RETR some_file\r\n' *get* '125 Data connection already open; Transfer starting.\r\n' *resp* '125 Data connection already open; Transfer starting.' [just sits there indefinitely] This is what it looks like when I attempt the same download using curl -v: * About to connect() to some_server port 21 (#0) * Trying some_ip... connected * Connected to some_server (some_ip) port 21 (#0) < 220 Microsoft FTP Service > USER some_user < 331 Password required for some_user. > PASS some_password < 230 User some_user logged in. > PWD < 257 "/some_dir" is current directory. * Entry path is '/some_dir' > EPSV * Connect data stream passively < 500 'EPSV': command not understood * disabling EPSV usage > PASV < 227 Entering Passive Mode (0,0,0,0,11,116). * Trying some_ip... connected * Connecting to some_ip (some_ip) port 2932 > TYPE I < 200 Type set to I. > SIZE some_file < 213 229376897 > RETR some_file < 125 Data connection already open; Transfer starting. * Maxdownload = -1 * Getting file with size: 229376897 { [data not shown] % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 218M 100 218M 0 0 182k 0 0:20:28 0:20:28 --:--:-- 0* FTP response timeout * control connection looks dead 100 218M 100 218M 0 0 182k 0 0:20:29 0:20:29 --:--:-- 0* Connection #0 to host some_server left intact curl: (28) FTP response timeout * Closing connection #0 wget output is kind of interesting as well, it notices the connection is dead, then attempts to re-download the file which only confirms that it is already finished: --2009-07-09 11:32:23-- ftp://some_server/some_file => `some_file' Resolving some_server... 0.0.0.0 Connecting to some_server|0.0.0.0|:21... connected. Logging in as some_user ... Logged in! ==> SYST ... done. ==> PWD ... done. ==> TYPE I ... done. ==> CWD not needed. ==> SIZE some_file ... 229376897 ==> PASV ... done. ==> RETR some_file ... done. Length: 229376897 (219M) 100%[==========================================================>] 229,376,897 387K/s in 18m 54s 2009-07-09 11:51:17 (198 KB/s) - Control connection closed. Retrying. --2009-07-09 12:06:18-- ftp://some_server/some_file (try: 2) => `some_file' Connecting to some_server|0.0.0.0|:21... connected. Logging in as some_user ... Logged in! ==> SYST ... done. ==> PWD ... done. ==> TYPE I ... done. ==> CWD not needed. ==> SIZE some_file ... 229376897 ==> PASV ... done. ==> REST 229376897 ... done. ==> RETR some_file ... done. Length: 229376897 (219M), 0 (0) remaining 100%[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++] 229,376,897 --.-K/s in 0s 2009-07-09 12:06:18 (0.00 B/s) - `some_file' saved [229376897] A: I've never used ftplib, but perhaps you could do: Get the name and size of the file you want. Start a new daemonic thread to download the file. In the main thread, check every few seconds whether the file size on disk equals the target size. When it does, wait a few seconds to give the connection a chance to close nicely, and then exit the program. A: I think some debugging could be useful. Could you fold the class below into your code? (I didn't do it myself because I know this version works, and didn't want to risk making an error. You should be able to just put the class at the top of your file and replace the body of the loop with what I've written after #LOOP BODY) class CounterFile(): def __init__(self, file, maxsize): self.file = file self.count = 0 self.maxsize = maxsize def write(self, bytes): self.count += len(bytes) print "total %d bytes / %d"%(self.count, self.maxsize) if self.count == self.maxsize: print " Should be complete" self.file.write(bytes) from ftplib import FTP ftp = FTP('ftp.gimp.org') ftp.login('ftp', 'thouis@gmail.com') ftp.set_debuglevel(2) ftp.cwd('/pub/gimp/v2.6/') fname = 'gimp-2.6.2.tar.bz2' # LOOP BODY sz = ftp.size(fname) if sz is None: print "Could not get size!" sz = 0 ret_status = ftp.retrbinary('RETR ' + fname, CounterFile(open(fname, 'wb'), sz).write)
Python tell when an ftp transfer sits on completion
I have to download some files from an FTP server. Seems prosaic enough. However, the way this server behaves is if the file is very large, the connection will just hang when the download ostensibly completes. How can I handle this gracefully using ftplib in python? Sample python code: from ftplib import FTP ... ftp = FTP(host) ftp.login(login, passwd) files=ftp.nlst() ftp.set_debuglevel(2) for fname in files: ret_status = ftp.retrbinary('RETR ' + fname, open(fname, 'wb').write) debug output from the above: *cmd* 'TYPE I' *put* 'TYPE I\r\n' *get* '200 Type set to I.\r\n' *resp* '200 Type set to I.' *cmd* 'PASV' *put* 'PASV\r\n' *get* '227 Entering Passive Mode (0,0,0,0,10,52).\r\n' *resp* '227 Entering Passive Mode (0,0,0,0,10,52).' *cmd* 'RETR some_file' *put* 'RETR some_file\r\n' *get* '125 Data connection already open; Transfer starting.\r\n' *resp* '125 Data connection already open; Transfer starting.' [just sits there indefinitely] This is what it looks like when I attempt the same download using curl -v: * About to connect() to some_server port 21 (#0) * Trying some_ip... connected * Connected to some_server (some_ip) port 21 (#0) < 220 Microsoft FTP Service > USER some_user < 331 Password required for some_user. > PASS some_password < 230 User some_user logged in. > PWD < 257 "/some_dir" is current directory. * Entry path is '/some_dir' > EPSV * Connect data stream passively < 500 'EPSV': command not understood * disabling EPSV usage > PASV < 227 Entering Passive Mode (0,0,0,0,11,116). * Trying some_ip... connected * Connecting to some_ip (some_ip) port 2932 > TYPE I < 200 Type set to I. > SIZE some_file < 213 229376897 > RETR some_file < 125 Data connection already open; Transfer starting. * Maxdownload = -1 * Getting file with size: 229376897 { [data not shown] % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 218M 100 218M 0 0 182k 0 0:20:28 0:20:28 --:--:-- 0* FTP response timeout * control connection looks dead 100 218M 100 218M 0 0 182k 0 0:20:29 0:20:29 --:--:-- 0* Connection #0 to host some_server left intact curl: (28) FTP response timeout * Closing connection #0 wget output is kind of interesting as well, it notices the connection is dead, then attempts to re-download the file which only confirms that it is already finished: --2009-07-09 11:32:23-- ftp://some_server/some_file => `some_file' Resolving some_server... 0.0.0.0 Connecting to some_server|0.0.0.0|:21... connected. Logging in as some_user ... Logged in! ==> SYST ... done. ==> PWD ... done. ==> TYPE I ... done. ==> CWD not needed. ==> SIZE some_file ... 229376897 ==> PASV ... done. ==> RETR some_file ... done. Length: 229376897 (219M) 100%[==========================================================>] 229,376,897 387K/s in 18m 54s 2009-07-09 11:51:17 (198 KB/s) - Control connection closed. Retrying. --2009-07-09 12:06:18-- ftp://some_server/some_file (try: 2) => `some_file' Connecting to some_server|0.0.0.0|:21... connected. Logging in as some_user ... Logged in! ==> SYST ... done. ==> PWD ... done. ==> TYPE I ... done. ==> CWD not needed. ==> SIZE some_file ... 229376897 ==> PASV ... done. ==> REST 229376897 ... done. ==> RETR some_file ... done. Length: 229376897 (219M), 0 (0) remaining 100%[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++] 229,376,897 --.-K/s in 0s 2009-07-09 12:06:18 (0.00 B/s) - `some_file' saved [229376897]
[ "I've never used ftplib, but perhaps you could do:\n\nGet the name and size of the file you want.\nStart a new daemonic thread to download the file.\nIn the main thread, check every few seconds whether the file size on disk equals the target size.\nWhen it does, wait a few seconds to give the connection a chance to close nicely, and then exit the program.\n\n", "I think some debugging could be useful. Could you fold the class below into your code? (I didn't do it myself because I know this version works, and didn't want to risk making an error. You should be able to just put the class at the top of your file and replace the body of the loop with what I've written after #LOOP BODY)\nclass CounterFile():\n def __init__(self, file, maxsize):\n self.file = file\n self.count = 0\n self.maxsize = maxsize\n\n def write(self, bytes):\n self.count += len(bytes)\n print \"total %d bytes / %d\"%(self.count, self.maxsize)\n if self.count == self.maxsize:\n print \" Should be complete\"\n self.file.write(bytes)\n\n\nfrom ftplib import FTP\nftp = FTP('ftp.gimp.org')\nftp.login('ftp', 'thouis@gmail.com')\nftp.set_debuglevel(2)\n\nftp.cwd('/pub/gimp/v2.6/')\nfname = 'gimp-2.6.2.tar.bz2'\n\n# LOOP BODY\nsz = ftp.size(fname)\nif sz is None:\n print \"Could not get size!\"\n sz = 0\nret_status = ftp.retrbinary('RETR ' + fname, CounterFile(open(fname, 'wb'), sz).write)\n\n" ]
[ 0, 0 ]
[]
[]
[ "ftp", "network_programming", "python" ]
stackoverflow_0001105014_ftp_network_programming_python.txt
Q: Python: Synchronize Input and Output Between Threads Currently, I am trying to do a small project with sockets in Python, a two-user chatting system. import socket import threading #Callback. Print doesn't work across threads def data_recieved(data): print data #Thread class to gather input class socket_read(threading.Thread): sock = object def __init__(self, sock): threading.Thread.__init__(self) self.sock = sock def run(self): while True: data = self.sock.recv(1000) if (data == "\quitting\\"): return data_recieved(self.sock.recv(1000)) #################################################################################### server = False uname = input("What's your username: ") print "Now for the technical info..." port = input("What port do I connect to ['any' if first]: ") #This is the first client. Let it get an available port if (port == "any"): server = True port = 9999 err = True while err == True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', port)) err = False except: err = True sock.close() print "Bound to port #" + str(port) print "Waiting for client..." sock.listen(1) (channel, info) = sock.accept() else: #This is the client. Just bind it tho a predisposed port host = input("What's the IP of the other client: ") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, int(port))) msg = "" if (server == True): #Use the connection from accept reader = socket_read(channel) else: #Use the actual socket reader = socket_read(sock) reader.start() while msg != 'quit': #Get the message... msg = uname + ": " + input("Message: ") try: #And send it if (server == True): #Use the connection from accept channel.send(msg) else: #Use direct socket sock.send(msg) except: break reader.join() channel.send("\quitting\\") sock.close() (I hope the comments help) Anyhow, by calling for input at the same time, and getting the other socket's message, I've got a small syncronization issue. I can connect, but when I recieve a message, it doesn't cancel the input statement. In other words, when I recieve a message, it says this Message: user: I got a message #Flashing cursor here So that it doesn't cancel the input statement. Also, I only get every other message. Any suggestions? A: What you have here is not so much a synchronization issue as it is a presentation/UI issue. I would suggest making your life easier and picking some UI toolkit (curses, wxPython, pyqt) to handle interaction with the user. Using input() is very handy for quick-and-dirty one-off code, but it is not very sophisticated. If you do this you will see you do not need to use threads at all (as is often the case), and your problems will go away as if by magic! A: Alright, sorry for such a quick answer to my own question, but callbacks are MAGICAL when using threading (at least on Linux's model). Anyhow, did this: import socket import threading def msg_loop(socket): msg = "" if (server == True): reader = socket_read(channel) else: reader = socket_read(sock) reader.start() while msg != 'quit': msg = uname + " said : " + input("Message: ") print "" try: if (server == True): channel.send('null') channel.send(msg) else: sock.send('null') sock.send(msg) except: break def data_recieved(data, socket): print "Hold on...\n\n" + data + "\n" msg_loop(socket) class socket_read(threading.Thread): sock = object def __init__(self, sock): threading.Thread.__init__(self) self.sock = sock def run(self): while True: data = self.sock.recv(1000) if (data == "\quitting\\" or data == ''): return data_recieved(self.sock.recv(1000), self.sock) #################################################################################### server = False uname = str(input("What's your username: ")) print "Now for the technical stuff..." port = input("What port do I connect to ['any' if first]: ") if (port == "any"): server = True port = 9999 err = True while err == True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', port)) err = False except: print "Socket #" + str(port) + " failed" err = True sock.close() port -= 1 print "Bound to port #" + str(port) print "Waiting for client..." sock.listen(1) (channel, info) = sock.accept() else: host = input("What's the IP of the other client: ") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, int(port))) if (server == True): msg_loop(channel) else: msg_loop(sock) reader.join() channel.send("\quitting\\") sock.close() As you can see, I added the message loop as a callback. Also note, I send a null value, to circumvent the "every other" problem. That, and I use a newline at the end of printing in data_recieved to disable the newline. (If you like the code, it doesn't run as well on Windows. This is because, apparently, Python's threading model on there doesn't execute as instentaniously. Try it on your local Linux box)
Python: Synchronize Input and Output Between Threads
Currently, I am trying to do a small project with sockets in Python, a two-user chatting system. import socket import threading #Callback. Print doesn't work across threads def data_recieved(data): print data #Thread class to gather input class socket_read(threading.Thread): sock = object def __init__(self, sock): threading.Thread.__init__(self) self.sock = sock def run(self): while True: data = self.sock.recv(1000) if (data == "\quitting\\"): return data_recieved(self.sock.recv(1000)) #################################################################################### server = False uname = input("What's your username: ") print "Now for the technical info..." port = input("What port do I connect to ['any' if first]: ") #This is the first client. Let it get an available port if (port == "any"): server = True port = 9999 err = True while err == True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', port)) err = False except: err = True sock.close() print "Bound to port #" + str(port) print "Waiting for client..." sock.listen(1) (channel, info) = sock.accept() else: #This is the client. Just bind it tho a predisposed port host = input("What's the IP of the other client: ") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, int(port))) msg = "" if (server == True): #Use the connection from accept reader = socket_read(channel) else: #Use the actual socket reader = socket_read(sock) reader.start() while msg != 'quit': #Get the message... msg = uname + ": " + input("Message: ") try: #And send it if (server == True): #Use the connection from accept channel.send(msg) else: #Use direct socket sock.send(msg) except: break reader.join() channel.send("\quitting\\") sock.close() (I hope the comments help) Anyhow, by calling for input at the same time, and getting the other socket's message, I've got a small syncronization issue. I can connect, but when I recieve a message, it doesn't cancel the input statement. In other words, when I recieve a message, it says this Message: user: I got a message #Flashing cursor here So that it doesn't cancel the input statement. Also, I only get every other message. Any suggestions?
[ "What you have here is not so much a synchronization issue as it is a presentation/UI issue. I would suggest making your life easier and picking some UI toolkit (curses, wxPython, pyqt) to handle interaction with the user. Using input() is very handy for quick-and-dirty one-off code, but it is not very sophisticated.\nIf you do this you will see you do not need to use threads at all (as is often the case), and your problems will go away as if by magic!\n", "Alright, sorry for such a quick answer to my own question, but callbacks are MAGICAL when using threading (at least on Linux's model).\nAnyhow, did this:\nimport socket\nimport threading\n\ndef msg_loop(socket):\n msg = \"\"\n if (server == True):\n reader = socket_read(channel)\n else:\n reader = socket_read(sock)\n reader.start()\n while msg != 'quit':\n msg = uname + \" said : \" + input(\"Message: \")\n print \"\"\n try:\n if (server == True):\n channel.send('null')\n channel.send(msg)\n else:\n sock.send('null')\n sock.send(msg)\n except:\n break\n\ndef data_recieved(data, socket):\n print \"Hold on...\\n\\n\" + data + \"\\n\"\n msg_loop(socket)\n\nclass socket_read(threading.Thread):\n sock = object\n def __init__(self, sock):\n threading.Thread.__init__(self)\n self.sock = sock\n def run(self):\n while True:\n data = self.sock.recv(1000)\n if (data == \"\\quitting\\\\\" or data == ''):\n return\n data_recieved(self.sock.recv(1000), self.sock)\n\n####################################################################################\nserver = False\nuname = str(input(\"What's your username: \"))\nprint \"Now for the technical stuff...\"\nport = input(\"What port do I connect to ['any' if first]: \")\nif (port == \"any\"):\n server = True\n port = 9999\n err = True\n while err == True:\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.bind(('', port))\n err = False\n except:\n print \"Socket #\" + str(port) + \" failed\"\n err = True\n sock.close()\n port -= 1\n\n print \"Bound to port #\" + str(port)\n print \"Waiting for client...\"\n\n sock.listen(1)\n (channel, info) = sock.accept()\nelse:\n host = input(\"What's the IP of the other client: \")\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((host, int(port)))\n\nif (server == True):\n msg_loop(channel)\nelse:\n msg_loop(sock)\n\nreader.join()\nchannel.send(\"\\quitting\\\\\")\nsock.close()\n\nAs you can see, I added the message loop as a callback.\nAlso note, I send a null value, to circumvent the \"every other\" problem.\nThat, and I use a newline at the end of printing in data_recieved to disable the newline.\n(If you like the code, it doesn't run as well on Windows. This is because, apparently, Python's threading model on there doesn't execute as instentaniously. Try it on your local Linux box)\n" ]
[ 1, 1 ]
[]
[]
[ "input", "multithreading", "python" ]
stackoverflow_0001940423_input_multithreading_python.txt
Q: Django index page best/most common practice I am working on a site currently (first one solo) and went to go make an index page. I have been attempting to follow django best practices as I go, so naturally I go search for this but couldn't a real standard in regards to this. I have seen folks creating apps to serve this purpose named various things (main, home, misc) and have seen a views.py in the root of the project. I am really just looking for what the majority out there do for this. The index page is not static, since I want to detect if the user is logged in and such. Thanks. A: If all of your dynamic content is handled in the template (for example, if it's just simple checking if a user is present on the request), then I recommend using a generic view, specificially the direct to template view: urlpatterns = patterns('django.views.generic.simple', (r'^$', 'direct_to_template', {'template': 'index.html'}), ) If you want to add a few more bits of information to the template context, there is another argument, extra_context, that you can pass to the generic view to include it: extra_context = { 'foo': 'bar', # etc } urlpatterns = patterns('django.views.generic.simple', (r'^$', 'direct_to_template', {'template': 'index.html', 'extra_context': extra_context }), ) A: I tend to create a views.py in the root of the project where I keep the index view.
Django index page best/most common practice
I am working on a site currently (first one solo) and went to go make an index page. I have been attempting to follow django best practices as I go, so naturally I go search for this but couldn't a real standard in regards to this. I have seen folks creating apps to serve this purpose named various things (main, home, misc) and have seen a views.py in the root of the project. I am really just looking for what the majority out there do for this. The index page is not static, since I want to detect if the user is logged in and such. Thanks.
[ "If all of your dynamic content is handled in the template (for example, if it's just simple checking if a user is present on the request), then I recommend using a generic view, specificially the direct to template view:\nurlpatterns = patterns('django.views.generic.simple',\n (r'^$', 'direct_to_template', {'template': 'index.html'}),\n)\n\nIf you want to add a few more bits of information to the template context, there is another argument, extra_context, that you can pass to the generic view to include it:\nextra_context = { \n 'foo': 'bar',\n # etc\n}\nurlpatterns = patterns('django.views.generic.simple',\n (r'^$', 'direct_to_template', {'template': 'index.html', 'extra_context': extra_context }),\n)\n\n", "I tend to create a views.py in the root of the project where I keep the index view.\n" ]
[ 19, 3 ]
[]
[]
[ "django", "indexing", "python" ]
stackoverflow_0001940528_django_indexing_python.txt
Q: Send a file with webpy and urllib2 I need to send a file to another server using oauth and webpy. For now I'll ignore the oauth part as sending the file itself is already a challenge. Here's my partial code: class create_video: def POST(self): x = web.input(video_original={}) At this point I want to send the file over the network using urllib2. Note that I also have other parameters to send. UPDATE considering that I want to send these parameters: params = { 'title': x['title'], 'video_original': x['video_original'].file } How do I use urllib2 (or anything else) to send them to a given url? P.S. I've tried to use the poster module but I don't know how to send generic parameters along with the file. A: You're coming from here, I guess. The POST method defines how to receive data via POST requests, rather than send any data. In your code, the data from an incoming POST request is saved in x. How do you want to proceed now? If you want to send the data to another url, use urllib(2) as described here.
Send a file with webpy and urllib2
I need to send a file to another server using oauth and webpy. For now I'll ignore the oauth part as sending the file itself is already a challenge. Here's my partial code: class create_video: def POST(self): x = web.input(video_original={}) At this point I want to send the file over the network using urllib2. Note that I also have other parameters to send. UPDATE considering that I want to send these parameters: params = { 'title': x['title'], 'video_original': x['video_original'].file } How do I use urllib2 (or anything else) to send them to a given url? P.S. I've tried to use the poster module but I don't know how to send generic parameters along with the file.
[ "You're coming from here, I guess.\nThe POST method defines how to receive data via POST requests, rather than send any data. In your code, the data from an incoming POST request is saved in x. How do you want to proceed now? If you want to send the data to another url, use urllib(2) as described here.\n" ]
[ 1 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0001939048_python_web.py.txt
Q: Interactive mode in matplotlib I want to dynamically update the scatter plot based on the y-axis data received from a socket connection. I used python matplot lib in interactive mode to do this, but during dynamic updation if i move the window to a different location or minimize the window then the plot updation stops abruptly. How to do this? I have attached a sample dynamic updation code used here and the same problem appears here also. import matplotlib.pyplot as plt import random import time items = [25.5,26.7,23.4,22.5,20,13.4,15.6,-12,-16,20] x = [1,2,3,4,5,6,7,8,9,10] plt.ion() # Interactive on for i in range(1,100): plt.title('graph plotting') plt.ylabel('temperature') plt.xlabel('time') random.shuffle(items) plt.plot(x,items,'ob-') plt.axis([0, 10, -40, 40]) plt.draw() #time.sleep(2) plt.clf() plt.close() A: This page contains a couple of examples of dynamic plots with matplotlib and wxPython. And here is a version with PyQt. A: For this to work, you need to have a main loop for event handling, and your own event handler to redraw the plot when the window is resized or refreshed. You'll find many examples for this on the web, or in the tutorials. I think this is best handled by using a UI toolkit (e.g. wxPython), not using matplotlib interactive mode. I had a similar question in the past and got some good answers.
Interactive mode in matplotlib
I want to dynamically update the scatter plot based on the y-axis data received from a socket connection. I used python matplot lib in interactive mode to do this, but during dynamic updation if i move the window to a different location or minimize the window then the plot updation stops abruptly. How to do this? I have attached a sample dynamic updation code used here and the same problem appears here also. import matplotlib.pyplot as plt import random import time items = [25.5,26.7,23.4,22.5,20,13.4,15.6,-12,-16,20] x = [1,2,3,4,5,6,7,8,9,10] plt.ion() # Interactive on for i in range(1,100): plt.title('graph plotting') plt.ylabel('temperature') plt.xlabel('time') random.shuffle(items) plt.plot(x,items,'ob-') plt.axis([0, 10, -40, 40]) plt.draw() #time.sleep(2) plt.clf() plt.close()
[ "This page contains a couple of examples of dynamic plots with matplotlib and wxPython. And here is a version with PyQt.\n", "For this to work, you need to have a main loop for event handling, and your own event handler to redraw the plot when the window is resized or refreshed.\nYou'll find many examples for this on the web, or in the tutorials.\nI think this is best handled by using a UI toolkit (e.g. wxPython), not using matplotlib interactive mode. I had a similar question in the past and got some good answers.\n" ]
[ 4, 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0001940387_matplotlib_python.txt
Q: Syntax quirks or why is that valid python In python 2.6, why is the following line valid? my_line = 'foo' 'bar' and if that is valid, why isn't the following: my_list = 1 2 The first example is string concatenation, however, the following isn't valid either (thanks god): foo = 'foo' bar = 'bar' foo_bar = foo bar A: This is doing string literal concatenation. As noted in the documentation, advantages include the following: This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings... It goes on to note that this concatenation is done at compilation time rather than run time. The history and rationale behind this, and a rejected suggestion to remove the feature, is described in PEP 3126. A: my_line = 'foo' 'bar' is string concatenation. A: Perhaps this is of C's ancestry. In C, the following is perfectly valid: char* ptr = "hello " "world"; It is implemented by the C pre-processor (cpp), and the rationale given in that link is: this allows long strings to be split over multiple lines, and also allows string literals resulting from C preprocessor defines and macros to be appended to strings at compile time A: It isn't inconsistent. Strings and integers have different methods. Integer concatenation is meaningless. String concatenation is a meaningful default behavior.
Syntax quirks or why is that valid python
In python 2.6, why is the following line valid? my_line = 'foo' 'bar' and if that is valid, why isn't the following: my_list = 1 2 The first example is string concatenation, however, the following isn't valid either (thanks god): foo = 'foo' bar = 'bar' foo_bar = foo bar
[ "This is doing string literal concatenation. As noted in the documentation, advantages include the following:\n\nThis feature can be used to reduce the\n number of backslashes needed, to split\n long strings conveniently across long\n lines, or even to add comments to\n parts of strings...\n\nIt goes on to note that this concatenation is done at compilation time rather than run time.\nThe history and rationale behind this, and a rejected suggestion to remove the feature, is described in PEP 3126.\n", "my_line = 'foo' 'bar' is string concatenation.\n", "Perhaps this is of C's ancestry. In C, the following is perfectly valid:\nchar* ptr = \"hello \" \"world\";\n\nIt is implemented by the C pre-processor (cpp), and the rationale given in that link is:\n\nthis allows long strings to be split\n over multiple lines, and also allows\n string literals resulting from C\n preprocessor defines and macros to be\n appended to strings at compile time\n\n", "It isn't inconsistent. Strings and integers have different methods. \nInteger concatenation is meaningless. \nString concatenation is a meaningful default behavior. \n" ]
[ 20, 8, 6, 5 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0001940710_python_syntax.txt
Q: Redirect with additional variables I have view which in some cases redirects user to another addres. How can I redirect user, with additional variables (not GET, beacause that variable can be long text)? Currently I'm using HttpResponseRedirect. Cheers. A: You can't force a POST on redirect. Perhaps your best option is to store the variables in request.session, and then check for the presence of these variables in the view handler for the redirected URL. Here's some more info on sessions.
Redirect with additional variables
I have view which in some cases redirects user to another addres. How can I redirect user, with additional variables (not GET, beacause that variable can be long text)? Currently I'm using HttpResponseRedirect. Cheers.
[ "You can't force a POST on redirect. Perhaps your best option is to store the variables in request.session, and then check for the presence of these variables in the view handler for the redirected URL.\nHere's some more info on sessions.\n" ]
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001941362_django_python.txt
Q: How does/should global data in modules across packages be managed in Python/other languages? I am trying to design the package and module system for a programming language (Heron) which can be both compiled and interpreted, and from what I have seen I really like the Python approach. Python has a rich choice of modules, which seems to contribute largely to its success. What I don`t know is what happens in Python if a module is included in two different compiled packages: are there separate copies made of the data or is it shared? Related to this are a bunch of side-questions: Am I right in assuming that packages can be compiled in Python? What are there pros and cons to the two approaches (copying or sharing of module data)? Are there widely known problems with the Python module system, from the point of view of the Python community? For example is there a PEP under consideration for enhancing modules/packages? Are there certain aspects of the Python module/package system which wouldn`t work well for a compiled language? A: Well, you asked a lot of questions. Here are some hints to get a bit further: a. Python code is lexed and compiled into Python specific instructions, but not compiled to machine executable code. The ".pyc" file is automatically created whenever you run python code that does not match the existing .pyc timestamp. This feature can be turned off. You might play with the dis module to see these instructions. b. When a module is imported, it is executed (top to bottom) in its own namespace and that namespace cached globally. When you import from another module, the module is not executed again. Remember that def is just a statement. You may want to put a print('compiling this module') statement in your code to trace it. It depends. There were recent enhancements, mostly around specifying which module needed to be loaded. Modules can have relative paths so that a huge project might have multiple modules with the a same name. Python itself won't work for a compiled language. Google for "unladen swallow blog" to see the tribulations of trying to speed up a language where "a = sum(b)" can change meanings between executions. Outside of corner cases, the module system forms a nice bridge between source code and a compiled library system. The approach works well, and Python's easy wrapping of C code (swig, etc.) helps. A: Modules are the only truly global objects in Python, with all other global data based around the module system (which uses sys.modules as a registry). Packages are simply modules with special semantics for importing submodules. "Compiling" a .py file into a .pyc or .pyo isn't compilation as understood for most languages: it only checks the syntax and creates a code object which, when executed in the interpreter, creates the module object. example.py: print "Creating %s module." % __name__ def show_def(f): print "Creating function %s.%s." % (__name__, f.__name__) return f @show_def def a(): print "called: %s.a" % __name__ Interactive session: >>> import example # first sys.modules['example'] is checked # since it doesn't exist, example.py is found and "compiled" to example.pyc # (since example.pyc doesn't exist, same would happen if it was outdated, etc.) Creating example module. # module code is executed Creating function example.a. # def statement executed >>> example.a() called: example.a >>> import example # sys.modules['example'] found, local variable example assigned to that object # no 'Creating ..' output >>> d = {"__name__": "fake"} >>> exec open("example.py") in d # the first import in this session is very similar to this # in that it creates a module object (which has a __dict__), initializes a few # variables in it (__builtins__, __name__, and others---packages' __init__ # modules have their own as well---look at some_module.__dict__.keys() or # dir(some_module)) # and executes the code from example.py in this dict (or the code object stored # in example.pyc, etc.) Creating fake module. # module code is executed Creating function fake.a. # def statement executed >>> d.keys() ['__builtins__', '__name__', 'a', 'show_def'] >>> d['a']() called: fake.a Your questions: They are compiled, in a sense, but not as you would expect if you're familiar with how C compilers work. If the data is immutable, copying is feasible, and should be indistinguishable from sharing except for object identity (is operator and id() in Python). Imports may or may not execute code (they always assign a local variable to an object, but that poses no problems) and may or may not modify sys.modules. You must be careful to not import in threads, and generally it is best to do all imports at the top of every module: this leads to a cascading graph so all the imports are done at once and then __main__ continues and does the Real Workβ„’. I don't know of any current PEP, but there's already a lot of complex machinery in place, too. For example packages can have a __path__ attribute (really a list of paths) so submodules don't have to be in the same directory, and these paths can even be computed at runtime! (Example mungepath package below.) You can have your own import hooks, use import statements inside functions, directly call __import__, and I wouldn't be surprised to find 2-3 other unique ways to work with packages and modules. A subset of the import system would work in a traditionally-compiled language, as long as it was similar to something like C's #include. You could run the "first level" of execution (creating the module objects) in the compiler, and compile those results. There are significant drawbacks to this, however, and amounts to separate execution contexts for module-level code and functions executed at runtime (and some functions would have to run in both contexts!). (Remember in Python that every statement is executed at runtime, even def and class statements.) I believe this is the main reason traditionally-compiled languages restrict "top-level" code to class, function, and object declarations, eliminating this second context. Even then, you have initialization problems for global objects in C/C++ (and others), unless managed carefully. mungepath/__init__.py: print __path__ __path__.append(".") # CWD, would be different in non-example code print __path__ from . import example # this is example.py from above, and is NOT in mungepath/ # note that this is a degenerate case, in that we now have two names for the # 'same' module: example and mungepath.example, but they're really different # modules with different functions (use 'is' or 'id()' to verify) Interactive session: >>> import example Creating example module. Creating function example.a. >>> example.__dict__.keys() ['a', '__builtins__', '__file__', 'show_def', '__package__', '__name__', '__doc__'] >>> import mungepath ['mungepath'] ['mungepath', '.'] Creating mungepath.example module. Creating function mungepath.example.a. >>> mungepath.example.a() called: mungepath.example.a >>> example is mungepath.example False >>> example.a is mungepath.example.a False A: Global data is scoped at the interpreter level. "packages" can be compiled as a package is just a collection of modules which themselves can be compiled. I am not sure I understand given the established scoping of data.
How does/should global data in modules across packages be managed in Python/other languages?
I am trying to design the package and module system for a programming language (Heron) which can be both compiled and interpreted, and from what I have seen I really like the Python approach. Python has a rich choice of modules, which seems to contribute largely to its success. What I don`t know is what happens in Python if a module is included in two different compiled packages: are there separate copies made of the data or is it shared? Related to this are a bunch of side-questions: Am I right in assuming that packages can be compiled in Python? What are there pros and cons to the two approaches (copying or sharing of module data)? Are there widely known problems with the Python module system, from the point of view of the Python community? For example is there a PEP under consideration for enhancing modules/packages? Are there certain aspects of the Python module/package system which wouldn`t work well for a compiled language?
[ "Well, you asked a lot of questions. Here are some hints to get a bit further:\n\na. Python code is lexed and compiled into Python specific instructions, but not compiled to machine executable code. The \".pyc\" file is automatically created whenever you run python code that does not match the existing .pyc timestamp. This feature can be turned off. You might play with the dis module to see these instructions.\n b. When a module is imported, it is executed (top to bottom) in its own namespace and that namespace cached globally. When you import from another module, the module is not executed again. Remember that def is just a statement. You may want to put a print('compiling this module') statement in your code to trace it.\nIt depends.\nThere were recent enhancements, mostly around specifying which module needed to be loaded. Modules can have relative paths so that a huge project might have multiple modules with the a same name.\nPython itself won't work for a compiled language. Google for \"unladen swallow blog\" to see the tribulations of trying to speed up a language where \"a = sum(b)\" can change meanings between executions. Outside of corner cases, the module system forms a nice bridge between source code and a compiled library system. The approach works well, and Python's easy wrapping of C code (swig, etc.) helps.\n\n", "Modules are the only truly global objects in Python, with all other global data based around the module system (which uses sys.modules as a registry). Packages are simply modules with special semantics for importing submodules. \"Compiling\" a .py file into a .pyc or .pyo isn't compilation as understood for most languages: it only checks the syntax and creates a code object which, when executed in the interpreter, creates the module object.\nexample.py:\nprint \"Creating %s module.\" % __name__\n\ndef show_def(f):\n print \"Creating function %s.%s.\" % (__name__, f.__name__)\n return f\n\n@show_def\ndef a():\n print \"called: %s.a\" % __name__\n\nInteractive session:\n>>> import example\n# first sys.modules['example'] is checked\n# since it doesn't exist, example.py is found and \"compiled\" to example.pyc\n# (since example.pyc doesn't exist, same would happen if it was outdated, etc.)\nCreating example module. # module code is executed\nCreating function example.a. # def statement executed\n>>> example.a()\ncalled: example.a\n>>> import example\n# sys.modules['example'] found, local variable example assigned to that object\n# no 'Creating ..' output\n>>> d = {\"__name__\": \"fake\"}\n>>> exec open(\"example.py\") in d\n# the first import in this session is very similar to this\n# in that it creates a module object (which has a __dict__), initializes a few\n# variables in it (__builtins__, __name__, and others---packages' __init__\n# modules have their own as well---look at some_module.__dict__.keys() or\n# dir(some_module))\n# and executes the code from example.py in this dict (or the code object stored\n# in example.pyc, etc.)\nCreating fake module. # module code is executed\nCreating function fake.a. # def statement executed\n>>> d.keys()\n['__builtins__', '__name__', 'a', 'show_def']\n>>> d['a']()\ncalled: fake.a\n\nYour questions:\n\nThey are compiled, in a sense, but not as you would expect if you're familiar with how C compilers work.\nIf the data is immutable, copying is feasible, and should be indistinguishable from sharing except for object identity (is operator and id() in Python).\nImports may or may not execute code (they always assign a local variable to an object, but that poses no problems) and may or may not modify sys.modules. You must be careful to not import in threads, and generally it is best to do all imports at the top of every module: this leads to a cascading graph so all the imports are done at once and then __main__ continues and does the Real Workβ„’.\n\n\nI don't know of any current PEP, but there's already a lot of complex machinery in place, too. For example packages can have a __path__ attribute (really a list of paths) so submodules don't have to be in the same directory, and these paths can even be computed at runtime! (Example mungepath package below.) You can have your own import hooks, use import statements inside functions, directly call __import__, and I wouldn't be surprised to find 2-3 other unique ways to work with packages and modules.\n\nA subset of the import system would work in a traditionally-compiled language, as long as it was similar to something like C's #include. You could run the \"first level\" of execution (creating the module objects) in the compiler, and compile those results. There are significant drawbacks to this, however, and amounts to separate execution contexts for module-level code and functions executed at runtime (and some functions would have to run in both contexts!). (Remember in Python that every statement is executed at runtime, even def and class statements.)\n\n\nI believe this is the main reason traditionally-compiled languages restrict \"top-level\" code to class, function, and object declarations, eliminating this second context. Even then, you have initialization problems for global objects in C/C++ (and others), unless managed carefully.\n\n\nmungepath/__init__.py:\nprint __path__\n__path__.append(\".\") # CWD, would be different in non-example code\nprint __path__\nfrom . import example # this is example.py from above, and is NOT in mungepath/\n# note that this is a degenerate case, in that we now have two names for the\n# 'same' module: example and mungepath.example, but they're really different\n# modules with different functions (use 'is' or 'id()' to verify)\n\nInteractive session:\n>>> import example\nCreating example module.\nCreating function example.a.\n>>> example.__dict__.keys()\n['a', '__builtins__', '__file__', 'show_def', '__package__',\n '__name__', '__doc__']\n>>> import mungepath\n['mungepath']\n['mungepath', '.']\nCreating mungepath.example module.\nCreating function mungepath.example.a.\n>>> mungepath.example.a()\ncalled: mungepath.example.a\n>>> example is mungepath.example\nFalse\n>>> example.a is mungepath.example.a\nFalse\n\n", "Global data is scoped at the interpreter level.\n\n\"packages\" can be compiled as a package is just a collection of modules which themselves can be compiled.\nI am not sure I understand given the established scoping of data.\n\n" ]
[ 3, 3, 1 ]
[]
[]
[ "language_design", "module", "namespaces", "package", "python" ]
stackoverflow_0001940934_language_design_module_namespaces_package_python.txt
Q: Using multiprocessing pool of workers I have the following code written to make my lazy second CPU core working. What the code does basically is first find the desired "sea" files in the directory hierarchy and later execute set of external scripts to process these binary "sea" files to produce 50 to 100 text and binary files in number. As the title of the question suggest in a paralleled fashion to increase the processing speed. This question originates from the long discussion that we have been having on IPython users list titled as "Cannot start ipcluster". Starting with my experimentation on IPython's parallel processing functionalities. The issue is I can't get this code running correctly. If the folders that contain "sea" files only houses "sea" files the script finishes its execution without fully performing external script runs. (Say I have 30-50 external scripts to run, but my multiprocessing enabled script exhaust only after executing the first script in these external script chain.) Interestingly, if I run this script on an already processed folder (which is "sea" files processed beforehand and output files are already in that folder) then it runs, but this time I get speed-ups at about 2.4 to 2.7X with respect to linear processing timings. It is not very expected since I only have a Core 2 Duo 2.5 Ghz CPU in my laptop. Although I have a CUDA powered GPU it has nothing to do with my current parallel computing struggle :) What do you think might be source of this issue? Thank you for all comments and suggestions. #!/usr/bin/env python from multiprocessing import Pool from subprocess import call import os def find_sea_files(): file_list, path_list = [], [] init = os.getcwd() for root, dirs, files in os.walk('.'): dirs.sort() for file in files: if file.endswith('.sea'): file_list.append(file) os.chdir(root) path_list.append(os.getcwd()) os.chdir(init) return file_list, path_list def process_all(pf): os.chdir(pf[0]) call(['postprocessing_saudi', pf[1]]) if __name__ == '__main__': pool = Pool(processes=2) # start 2 worker processes files, paths = find_sea_files() pathfile = [[paths[i],files[i]] for i in range(len(files))] pool.map(process_all, pathfile) A: I would start with getting a better feeling for what is going on with the worker process. The multiprocessing module comes with logging for its subprocesses if you need. Since you have simplified the code to narrow down the problem, I would just debug with a few print statements, like so (or you can PrettyPrint the pf array): def process_all(pf): print "PID: ", os.getpid() print "Script Dir: ", pf[0] print "Script: ", pf[1] os.chdir(pf[0]) call(['postprocessing_saudi', pf[1]]) if __name__ == '__main__': pool = Pool(processes=2) files, paths = find_sea_files() pathfile = [[paths[i],files[i]] for i in range(len(files))] pool.map(process_all, pathfile, 1) # Ensure the chunk size is 1 pool.close() pool.join() The version of Python that I have accomplished this with 2.6.4. A: There are several things I can think of: 1) Have you printed out the pathfiles? Are you sure that they are all properly generated? a) I ask as your os.walk is a bit interesting; the dirs.sort() should be ok, but seems quite unncessarily. os.chdir() in general shouldn't be used; the restoration should be alright, but in general you should just be appending root to init. 2) I've seen multiprocessing on python2.6 have problems spawning subporcesses from pools. (I specifically had a script use multiprocessing to spawn subprocesses. Those subprocesses then could not correctly use multiprocessing (the pool locked up)). Try python2.5 w/ the mulitprocessing backport. 3) Try picloud's cloud.mp module (which wraps multiprocessing, but handles pools a tad differently) and see if that works. You would do cloud.mp.join(cloud.mp.map(process_all, pathfile)) (Disclaimer: I am one of the developers of PiCloud)
Using multiprocessing pool of workers
I have the following code written to make my lazy second CPU core working. What the code does basically is first find the desired "sea" files in the directory hierarchy and later execute set of external scripts to process these binary "sea" files to produce 50 to 100 text and binary files in number. As the title of the question suggest in a paralleled fashion to increase the processing speed. This question originates from the long discussion that we have been having on IPython users list titled as "Cannot start ipcluster". Starting with my experimentation on IPython's parallel processing functionalities. The issue is I can't get this code running correctly. If the folders that contain "sea" files only houses "sea" files the script finishes its execution without fully performing external script runs. (Say I have 30-50 external scripts to run, but my multiprocessing enabled script exhaust only after executing the first script in these external script chain.) Interestingly, if I run this script on an already processed folder (which is "sea" files processed beforehand and output files are already in that folder) then it runs, but this time I get speed-ups at about 2.4 to 2.7X with respect to linear processing timings. It is not very expected since I only have a Core 2 Duo 2.5 Ghz CPU in my laptop. Although I have a CUDA powered GPU it has nothing to do with my current parallel computing struggle :) What do you think might be source of this issue? Thank you for all comments and suggestions. #!/usr/bin/env python from multiprocessing import Pool from subprocess import call import os def find_sea_files(): file_list, path_list = [], [] init = os.getcwd() for root, dirs, files in os.walk('.'): dirs.sort() for file in files: if file.endswith('.sea'): file_list.append(file) os.chdir(root) path_list.append(os.getcwd()) os.chdir(init) return file_list, path_list def process_all(pf): os.chdir(pf[0]) call(['postprocessing_saudi', pf[1]]) if __name__ == '__main__': pool = Pool(processes=2) # start 2 worker processes files, paths = find_sea_files() pathfile = [[paths[i],files[i]] for i in range(len(files))] pool.map(process_all, pathfile)
[ "I would start with getting a better feeling for what is going on with the worker process. The multiprocessing module comes with logging for its subprocesses if you need. Since you have simplified the code to narrow down the problem, I would just debug with a few print statements, like so (or you can PrettyPrint the pf array):\n\ndef process_all(pf):\n print \"PID: \", os.getpid()\n print \"Script Dir: \", pf[0]\n print \"Script: \", pf[1]\n os.chdir(pf[0])\n call(['postprocessing_saudi', pf[1]])\n\n\nif __name__ == '__main__':\n pool = Pool(processes=2)\n files, paths = find_sea_files()\n pathfile = [[paths[i],files[i]] for i in range(len(files))]\n pool.map(process_all, pathfile, 1) # Ensure the chunk size is 1\n pool.close()\n pool.join()\n\nThe version of Python that I have accomplished this with 2.6.4.\n", "There are several things I can think of:\n1) Have you printed out the pathfiles? Are you sure that they are all properly generated?\na) I ask as your os.walk is a bit interesting; the dirs.sort() should be ok, but seems quite unncessarily. os.chdir() in general shouldn't be used; the restoration should be alright, but in general you should just be appending root to init.\n2) I've seen multiprocessing on python2.6 have problems spawning subporcesses from pools. (I specifically had a script use multiprocessing to spawn subprocesses. Those subprocesses then could not correctly use multiprocessing (the pool locked up)). Try python2.5 w/ the mulitprocessing backport.\n3) Try picloud's cloud.mp module (which wraps multiprocessing, but handles pools a tad differently) and see if that works. \nYou would do\ncloud.mp.join(cloud.mp.map(process_all, pathfile))\n\n(Disclaimer: I am one of the developers of PiCloud)\n" ]
[ 6, 3 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0001586754_multiprocessing_python.txt
Q: calling an outside function in python I am trying to return (execute) a function from another file in an if statement. I have read that the return statement will not work, I was hoping someone would know what statement would allow me to call an outside function. The function creates a sandbox but if one exists I want to pass the if statement. This is a small snippet of code I used. import mks_function from mksfunction import mks_create_sandbox import sys, os, time import os.path if not os.path.exists('home/build/test/new_sandbox/project.pj'): return mks_create_sandbox() else: print pass A: Say your function bar is in a file called foo.py on your Python path. If foo.py contains this: def bar(): return True Then you can do this: from foo import bar if bar(): print "bar() is True!" A: let's see what docs say: return may only occur syntactically nested in a function definition, not within a nested class definition. what you're trying to do, I guess is: from mksfunction import mks_create_sandbox import os.path if not os.path.exists('home/build/test/new_sandbox/project.pj'): mks_create_sandbox() A: I have a big touch on this recently as I was working on my final project in python. I would be engaged to look at your outside function file too. If you are calling a module (well actually, any function outside the same file can be treated as a module, I hate to specify things too precise), you need to make sure something. Here is an example of a module, let's called it my_module.py # Example python module import sys # Any other imports... imports should always be first # Some classes, functions, whatever... # This is your meat and potatos # Now we'll define a main function def main(): # This is the code that runs when you are running this module alone print sys.platform # This checks whether this file is being run as the main script # or if its being run from another script if __name__ == '__main__': main() # Another script running this script (ie, in an import) would use it's own # filename as the value of __name__ Now I want to call this entire function in another file, called work.py import my_module x = my_module x.main() A: You probably need to import the module which contains the function, no? Of course, a little more precision as to what you are trying to achieve would help. A: What exactly do you mean by "the return statement will not work"? You can import the function from the other file and call it like a local function. A: It depends what you mean. If you want to create a static method then you would do something like class fubar(object): @classmethod def foo(): return bar fubar.foo() # returns bar If you want to run an external process then you would use subprocess library and do import subprocess subprocess.popen("cmd echo 'test'",shell=true) really depends what you want to do A: Do you mean import? Say, your external function lives in mymodule.py in the same directory, you have to import it first: import mymodule # or from mymodule import myfunction Then it is straight forward to use the function: if mymodule.myfunction() == "abc": # do something or with the second import: if myfunction() == "abc": # do something See this tutorial.
calling an outside function in python
I am trying to return (execute) a function from another file in an if statement. I have read that the return statement will not work, I was hoping someone would know what statement would allow me to call an outside function. The function creates a sandbox but if one exists I want to pass the if statement. This is a small snippet of code I used. import mks_function from mksfunction import mks_create_sandbox import sys, os, time import os.path if not os.path.exists('home/build/test/new_sandbox/project.pj'): return mks_create_sandbox() else: print pass
[ "Say your function bar is in a file called foo.py on your Python path.\nIf foo.py contains this:\ndef bar():\n return True\n\nThen you can do this:\nfrom foo import bar\n\nif bar():\n print \"bar() is True!\"\n\n", "let's see what docs say:\n\nreturn may only occur syntactically nested in a function definition, not within a nested class definition.\n\nwhat you're trying to do, I guess is:\nfrom mksfunction import mks_create_sandbox \nimport os.path\n\nif not os.path.exists('home/build/test/new_sandbox/project.pj'):\n mks_create_sandbox()\n\n", "I have a big touch on this recently as I was working on my final project in python. I would be engaged to look at your outside function file too.\nIf you are calling a module (well actually, any function outside the same file can be treated as a module, I hate to specify things too precise), you need to make sure something. Here is an example of a module, let's called it my_module.py\n# Example python module\n\nimport sys\n# Any other imports... imports should always be first\n\n# Some classes, functions, whatever...\n# This is your meat and potatos\n\n# Now we'll define a main function\ndef main():\n # This is the code that runs when you are running this module alone\n print sys.platform\n\n# This checks whether this file is being run as the main script\n# or if its being run from another script\nif __name__ == '__main__':\n main()\n# Another script running this script (ie, in an import) would use it's own\n# filename as the value of __name__\n\nNow I want to call this entire function in another file, called work.py\nimport my_module\n\nx = my_module\nx.main()\n\n", "You probably need to import the module which contains the function, no?\nOf course, a little more precision as to what you are trying to achieve would help.\n", "What exactly do you mean by \"the return statement will not work\"?\nYou can import the function from the other file and call it like a local function.\n", "It depends what you mean. If you want to create a static method then you would do something like\nclass fubar(object):\n\n @classmethod\n def foo():\n return bar\n\nfubar.foo() # returns bar\n\nIf you want to run an external process then you would use subprocess library and do\nimport subprocess\nsubprocess.popen(\"cmd echo 'test'\",shell=true)\n\nreally depends what you want to do\n", "Do you mean import? Say, your external function lives in mymodule.py in the same directory, you have to import it first:\nimport mymodule\n# or\nfrom mymodule import myfunction\n\nThen it is straight forward to use the function:\nif mymodule.myfunction() == \"abc\":\n # do something\n\nor with the second import:\nif myfunction() == \"abc\":\n # do something\n\nSee this tutorial.\n" ]
[ 5, 2, 2, 1, 1, 0, 0 ]
[ "file1.py (comment out 2 of the versions)\n#version 1\nfrom file2 import outsidefunction\nprint (outsidefunction(3))\n\n#version 2\nimport file2\nprint (file2.outsidefunction(3))\n\n#version 3\nfrom file2 import *\nprint (outsidefunction(3))\n\nfile2.py\ndef outsidefunction(num):\n return num * 2\n\nCommand-Line: python file1.py\n" ]
[ -1 ]
[ "python", "return" ]
stackoverflow_0001928718_python_return.txt
Q: Python: Defining a class with only Integers Defined I am defining a class where only a set of integers is used. I cannot use the following datatypes in defining my class: set, frozenset and dictionaries. i need help defining: remove(self,i): Integer i is removed from the set. An exception is raised if i is not in self. discard(self, i): integer i is removed from the set. No exception is raised if i is not in self A: Assuming you are using an internal list based on what you've said, you could do it like so: class Example(object): def __init__(self): self._list = list() # all your other methods here... def remove(self, i): try: self._list.remove(i) except ValueError: raise ValueError("i is not in the set.") def discard(self, i): try: self._list.remove(i) except ValueError: pass remove() tries to remove the element and catches the list's ValueError so it can throw its own. discard() does the same but instead does nothing if a ValueError occurs. A: I cannot use the following datatypes in defining my class: set, frozenset and dictionaries. It looks like you are going to use list. You can use list's remove method and handle exceptions in appropriate way. A: Here's highly inefficient but complete implementation using MutableSet ABC: import collections class MySet(collections.MutableSet): def __init__(self, iterable=tuple()): self._items = [] for value in iterable: self.add(value) def discard(self, value): try: self._items.remove(value) except ValueError: pass def add(self, value): if value not in self: self._items.append(value) def __iter__(self): return iter(self._items) def __len__(self): return len(self._items) def __contains__(self, value): return value in self._items From collections.MutableSet source: def remove(self, value): if value not in self: raise KeyError(value) self.discard(value) A: Here is something I did with duplication, take some ideas from it combList = list1 + list2 combList.sort() last = combList[-1] for i in range(len(combList)-2, -1, -1): if last == combList[i]: del combList[i] else: last = combList[i] combList.sort() for i in range(len(combList)): print i+1, combList[i] I totally agreed with LiOliQ, the only way is to do it as a list.
Python: Defining a class with only Integers Defined
I am defining a class where only a set of integers is used. I cannot use the following datatypes in defining my class: set, frozenset and dictionaries. i need help defining: remove(self,i): Integer i is removed from the set. An exception is raised if i is not in self. discard(self, i): integer i is removed from the set. No exception is raised if i is not in self
[ "Assuming you are using an internal list based on what you've said, you could do it like so:\nclass Example(object):\n def __init__(self):\n self._list = list()\n\n # all your other methods here...\n\n def remove(self, i):\n try:\n self._list.remove(i)\n except ValueError:\n raise ValueError(\"i is not in the set.\")\n\n def discard(self, i):\n try:\n self._list.remove(i)\n except ValueError:\n pass\n\nremove() tries to remove the element and catches the list's ValueError so it can throw its own. discard() does the same but instead does nothing if a ValueError occurs.\n", "\nI cannot use the following datatypes in defining my class: set, frozenset and dictionaries.\n\nIt looks like you are going to use list.\nYou can use list's remove method and handle exceptions in appropriate way.\n", "Here's highly inefficient but complete implementation using MutableSet ABC:\nimport collections\n\n\nclass MySet(collections.MutableSet):\n\n def __init__(self, iterable=tuple()):\n self._items = []\n for value in iterable:\n self.add(value)\n\n def discard(self, value):\n try: self._items.remove(value)\n except ValueError:\n pass\n\n def add(self, value):\n if value not in self:\n self._items.append(value)\n\n def __iter__(self):\n return iter(self._items)\n\n def __len__(self):\n return len(self._items)\n\n def __contains__(self, value):\n return value in self._items\n\nFrom collections.MutableSet source:\ndef remove(self, value):\n if value not in self:\n raise KeyError(value)\n self.discard(value)\n\n", "Here is something I did with duplication, take some ideas from it\ncombList = list1 + list2\n\ncombList.sort()\nlast = combList[-1]\nfor i in range(len(combList)-2, -1, -1):\n if last == combList[i]:\n del combList[i]\n else:\n last = combList[i]\n\ncombList.sort()\n\nfor i in range(len(combList)):\n print i+1, combList[i] \n\nI totally agreed with LiOliQ, the only way is to do it as a list.\n" ]
[ 2, 1, 1, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0001930896_class_python.txt
Q: Creating a new virtualenv results in an error I'm trying to get virtualenv to work on my machine. I'm using python2.6, and after installing pip, and using pip to install virtualenv, running "virtualenv --no-site-packages cyclesg" results in the following: New python executable in cyclesg/bin/python Installing setuptools.... Complete output from command /home/nubela/Workspace/cyclesg...ython -c "#!python \"\"\"Bootstrap setuptoo... " /usr/lib/python2.6/site-packag...6.egg: error: invalid Python installation: unable to open /home/nubela/Workspace/cyclesg_dep/cyclesg/include/multiarch-i386-linux/python2.6/pyconfig.h (No such file or directory) ---------------------------------------- ...Installing setuptools...done. New python executable in cyclesg/bin/python Installing setuptools.... Complete output from command /home/nubela/Workspace/cyclesg...ython -c "#!python \"\"\"Bootstrap setuptoo... " /usr/lib/python2.6/site-packag...6.egg: error: invalid Python installation: unable to open /home/nubela/Workspace/cyclesg_dep/cyclesg/include/multiarch-i386-linux/python2.6/pyconfig.h (No such file or directory) ---------------------------------------- ...Installing setuptools...done. Any idea how I can remedy this? Thanks! A: Are you on mandriva? In order to support multilib (mixing x86/x86_64) Mandriva messes up your python installation. They patched python, which breaks virtualenv; instead of fixing python, they then proceeded to patch virtualenv. This is useless if you are using your own virtualenv installed from pip. Here is the bug: https://qa.mandriva.com/show_bug.cgi?id=42808 A: Are you on a linux based system? It looks like virtualenv is trying to build a new python exectable but can't find the files to do that. Try installing the python-dev package.
Creating a new virtualenv results in an error
I'm trying to get virtualenv to work on my machine. I'm using python2.6, and after installing pip, and using pip to install virtualenv, running "virtualenv --no-site-packages cyclesg" results in the following: New python executable in cyclesg/bin/python Installing setuptools.... Complete output from command /home/nubela/Workspace/cyclesg...ython -c "#!python \"\"\"Bootstrap setuptoo... " /usr/lib/python2.6/site-packag...6.egg: error: invalid Python installation: unable to open /home/nubela/Workspace/cyclesg_dep/cyclesg/include/multiarch-i386-linux/python2.6/pyconfig.h (No such file or directory) ---------------------------------------- ...Installing setuptools...done. New python executable in cyclesg/bin/python Installing setuptools.... Complete output from command /home/nubela/Workspace/cyclesg...ython -c "#!python \"\"\"Bootstrap setuptoo... " /usr/lib/python2.6/site-packag...6.egg: error: invalid Python installation: unable to open /home/nubela/Workspace/cyclesg_dep/cyclesg/include/multiarch-i386-linux/python2.6/pyconfig.h (No such file or directory) ---------------------------------------- ...Installing setuptools...done. Any idea how I can remedy this? Thanks!
[ "Are you on mandriva?\nIn order to support multilib (mixing x86/x86_64) Mandriva messes up your python installation. They patched python, which breaks virtualenv; instead of fixing python, they then proceeded to patch virtualenv. This is useless if you are using your own virtualenv installed from pip.\nHere is the bug: https://qa.mandriva.com/show_bug.cgi?id=42808\n", "Are you on a linux based system? It looks like virtualenv is trying to build a new python exectable but can't find the files to do that. Try installing the python-dev package.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0001941894_python_virtualenv.txt
Q: Add a member variable / method to a Python generator? Can I add a member variable / method to a Python generator? I want something along the following lines, so that I can "peek" at member variable j: def foo(): for i in range(10): self.j = 10 - i yield i gen = foo() for k in gen: print gen.j print k Yes, I know that I can return i AND j every time. But I don't want to do that. I want to peek at a local within the generator. A: You could create an object and manipulate the __iter__ interface: class Foo(object): def __init__(self): self.j = None def __iter__(self): for i in range(10): self.j = 10 - i yield i my_generator = Foo() for k in my_generator: print 'j is',my_generator.j print 'k is',k Prints: j is 10 k is 0 j is 9 k is 1 j is 8 k is 2 j is 7 k is 3 j is 6 k is 4 j is 5 k is 5 j is 4 k is 6 j is 3 k is 7 j is 2 k is 8 j is 1 k is 9 A: I think it's ugly, but it should do what you want. I'd rather return i AND j every time, though :-) class Foo(object): def foo(self): for i in range(10): self.j = 10 - i yield i genKlass = Foo() gen = genKlass.foo() for k in gen: print genKlass.j print k
Add a member variable / method to a Python generator?
Can I add a member variable / method to a Python generator? I want something along the following lines, so that I can "peek" at member variable j: def foo(): for i in range(10): self.j = 10 - i yield i gen = foo() for k in gen: print gen.j print k Yes, I know that I can return i AND j every time. But I don't want to do that. I want to peek at a local within the generator.
[ "You could create an object and manipulate the __iter__ interface:\nclass Foo(object):\n def __init__(self):\n self.j = None\n def __iter__(self):\n for i in range(10):\n self.j = 10 - i\n yield i\n\nmy_generator = Foo()\n\nfor k in my_generator:\n print 'j is',my_generator.j\n print 'k is',k\n\nPrints:\nj is 10\nk is 0\nj is 9\nk is 1\nj is 8\nk is 2\nj is 7\nk is 3\nj is 6\nk is 4\nj is 5\nk is 5\nj is 4\nk is 6\nj is 3\nk is 7\nj is 2\nk is 8\nj is 1\nk is 9\n\n", "I think it's ugly, but it should do what you want. I'd rather return i AND j every time, though :-)\nclass Foo(object):\n def foo(self):\n for i in range(10):\n self.j = 10 - i\n yield i\n\ngenKlass = Foo()\ngen = genKlass.foo()\nfor k in gen:\n print genKlass.j\n print k\n\n" ]
[ 9, 2 ]
[]
[]
[ "generator", "local", "python" ]
stackoverflow_0001942328_generator_local_python.txt
Q: Why does ctypes WriteProcessMemory() fail? I have been trying to get this function working for some time now with no luck. def write_memory(self, address, data): PROCESS_ALL_ACCESS = 0x001F0FFF count = c_ulong(0) length = len(data) c_data = c_char_p(data[count.value:]) null = c_int(0) windll.kernel32.SetLastError(10000) if not windll.kernel32.WriteProcessMemory(self.h_process, address, c_data, length, byref(count)): print "Failed to write memory." print "Error Code: ", windll.kernel32.GetLastError() else: return True GetLastError() returns 87 (0x57), which is ERROR_INVALID_PARAMETER. For this function I copied it straight from Gray Hat Python by Justin Seitz. Not sure what I'm doing wrong, ReadProcessMemory() works great and returns the appropriate value. For address I'm picking a random location at the moment, 0x00050000, and passing data like "\x61" reading the location before and after with no change. I have the feeling It's a simple error, Thanks in advance for the help. Nav. While you were right It's a privilege thing. I still can't seem to figure out what I'm looking for. Here's my launch process code: class SECURITY_ATTRIBUTES(Structure): _fields_ = [("Length", DWORD), ("SecDescriptor", LPVOID), ("InheritHandle", BOOL)] def launch(self, path_to_exe): CREATE_NEW_CONSOLE = 0x0000010 startupinfo = STARTUPINFO() process_information = PROCESS_INFORMATION() security_attributes = SECURITY_ATTRIBUTES() startupinfo.dwFlags = 0x1 startupinfo.wShowWindow = 0x0 startupinfo.cb = sizeof(startupinfo) security_attributes.Length = sizeof(security_attributes) security_attributes.SecDescriptior = None security_attributes.InheritHandle = True if windll.kernel32.CreateProcessA(path_to_exe, None, byref(security_attributes), byref(security_attributes), True, CREATE_NEW_CONSOLE, None, None, byref(startupinfo), byref(process_information)): self.pid = process_information.dwProcessId else: print "Couldnt launch: %d" %path_to_exe print windll.kernel32.GetLastError() Do I need to create the process a different way? What should I be putting in the SecDescriptor struct? MSDN isn't very helpful going on about DACL's and ACE's? Thanks for all the help so far. PS - Just an idea, how does a debugger or some other program not spawn a process and is able to alter memory? A: There's nothing obviously wrong with the call. Most likely there just aren't any pages at 0x00050000 or the pages there aren't writable. Why don't you try doing a VirtualQuery on the bytes you are trying to write to and see if it's actually writable? Most random addresses aren't.
Why does ctypes WriteProcessMemory() fail?
I have been trying to get this function working for some time now with no luck. def write_memory(self, address, data): PROCESS_ALL_ACCESS = 0x001F0FFF count = c_ulong(0) length = len(data) c_data = c_char_p(data[count.value:]) null = c_int(0) windll.kernel32.SetLastError(10000) if not windll.kernel32.WriteProcessMemory(self.h_process, address, c_data, length, byref(count)): print "Failed to write memory." print "Error Code: ", windll.kernel32.GetLastError() else: return True GetLastError() returns 87 (0x57), which is ERROR_INVALID_PARAMETER. For this function I copied it straight from Gray Hat Python by Justin Seitz. Not sure what I'm doing wrong, ReadProcessMemory() works great and returns the appropriate value. For address I'm picking a random location at the moment, 0x00050000, and passing data like "\x61" reading the location before and after with no change. I have the feeling It's a simple error, Thanks in advance for the help. Nav. While you were right It's a privilege thing. I still can't seem to figure out what I'm looking for. Here's my launch process code: class SECURITY_ATTRIBUTES(Structure): _fields_ = [("Length", DWORD), ("SecDescriptor", LPVOID), ("InheritHandle", BOOL)] def launch(self, path_to_exe): CREATE_NEW_CONSOLE = 0x0000010 startupinfo = STARTUPINFO() process_information = PROCESS_INFORMATION() security_attributes = SECURITY_ATTRIBUTES() startupinfo.dwFlags = 0x1 startupinfo.wShowWindow = 0x0 startupinfo.cb = sizeof(startupinfo) security_attributes.Length = sizeof(security_attributes) security_attributes.SecDescriptior = None security_attributes.InheritHandle = True if windll.kernel32.CreateProcessA(path_to_exe, None, byref(security_attributes), byref(security_attributes), True, CREATE_NEW_CONSOLE, None, None, byref(startupinfo), byref(process_information)): self.pid = process_information.dwProcessId else: print "Couldnt launch: %d" %path_to_exe print windll.kernel32.GetLastError() Do I need to create the process a different way? What should I be putting in the SecDescriptor struct? MSDN isn't very helpful going on about DACL's and ACE's? Thanks for all the help so far. PS - Just an idea, how does a debugger or some other program not spawn a process and is able to alter memory?
[ "There's nothing obviously wrong with the call. Most likely there just aren't any pages at 0x00050000 or the pages there aren't writable. \nWhy don't you try doing a VirtualQuery on the bytes you are trying to write to and see if it's actually writable? Most random addresses aren't.\n" ]
[ 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0001942322_ctypes_python.txt
Q: How properly bundle&install python to windows users I need to redistribute Python 2.6 for my users. Currently, I execute the silent instalation for the msi installer from http://www.python.org/download/, but I have some problems, like if other version of python is installed this not get the default. In the other hand, despite this could be rare, if a user have already python and I install my own, then could cause a conflict. So, which could the best curse of action? How automate this install?. I already have http://installbuilder.bitrock.com but the available django stack is too large for my app, and I need to pre-install several python modules. I wonder if in this case virtualenv will be the best option, but still have the issue of properly install it... A: I haven't used it, beyond some initial research, but ActiveState's ActivePython generally does what you want, if you're looking for a commercial pre-built solution. I have worked on software that included its own bundled Python, and there were never any problems with conflicts. In our case, it was installed alongside the rest of the software, rather than C:\Python26, and it was intended for the software's use only, not as a replacement for any existing Python on the system. A full Python with the stdlib pre-compiled to .pyo takes only ~10-20MB of space, depending on which modules you include. So I wouldn't worry about the possible redundancy. It also makes your life easier to have your own copy, since you know exactly which versions of all the third-party libraries you have; you don't have to worry about the user upgrading something that breaks your app. The counter-argument is that some users may want the latest versions of libraries, for security reasons. But in my experience, those users are in a very slim minority, and for them it just boils down to a little more work. Finally, I presume you have reasons for wanting a full Python installation. Just in case you're only interested in a way to distribute a single app, take a look at py2exe.
How properly bundle&install python to windows users
I need to redistribute Python 2.6 for my users. Currently, I execute the silent instalation for the msi installer from http://www.python.org/download/, but I have some problems, like if other version of python is installed this not get the default. In the other hand, despite this could be rare, if a user have already python and I install my own, then could cause a conflict. So, which could the best curse of action? How automate this install?. I already have http://installbuilder.bitrock.com but the available django stack is too large for my app, and I need to pre-install several python modules. I wonder if in this case virtualenv will be the best option, but still have the issue of properly install it...
[ "I haven't used it, beyond some initial research, but ActiveState's ActivePython generally does what you want, if you're looking for a commercial pre-built solution.\nI have worked on software that included its own bundled Python, and there were never any problems with conflicts. In our case, it was installed alongside the rest of the software, rather than C:\\Python26, and it was intended for the software's use only, not as a replacement for any existing Python on the system. A full Python with the stdlib pre-compiled to .pyo takes only ~10-20MB of space, depending on which modules you include. So I wouldn't worry about the possible redundancy.\nIt also makes your life easier to have your own copy, since you know exactly which versions of all the third-party libraries you have; you don't have to worry about the user upgrading something that breaks your app. The counter-argument is that some users may want the latest versions of libraries, for security reasons. But in my experience, those users are in a very slim minority, and for them it just boils down to a little more work.\nFinally, I presume you have reasons for wanting a full Python installation. Just in case you're only interested in a way to distribute a single app, take a look at py2exe.\n" ]
[ 2 ]
[]
[]
[ "deployment", "installation", "python", "windows" ]
stackoverflow_0001942399_deployment_installation_python_windows.txt
Q: DOM to use with SpiderMonkey? I'm trying to use the GoogleMaps JavaScript library from inside of SpiderMonkey using the python wrapper, but I can't because of the lack of a DOM. Is there some way I can integrate a DOM into this so that I can get this to work? A: env.js implements the DOM. I know it at least works in SpiderMonkey and Rhino but SpiderMonkey may have issues with things like XMLHttpRequest.
DOM to use with SpiderMonkey?
I'm trying to use the GoogleMaps JavaScript library from inside of SpiderMonkey using the python wrapper, but I can't because of the lack of a DOM. Is there some way I can integrate a DOM into this so that I can get this to work?
[ "env.js implements the DOM. I know it at least works in SpiderMonkey and Rhino but SpiderMonkey may have issues with things like XMLHttpRequest.\n" ]
[ 4 ]
[]
[]
[ "dom", "javascript", "python", "spidermonkey" ]
stackoverflow_0001942344_dom_javascript_python_spidermonkey.txt
Q: Python GUI (glade) to display output of shell process I'm writing a python application that runs several subprocesses using subprocess.Popen objects. I have a glade GUI and want to display the output of these commands (running in subprocess.Popen) in the gui in real time. Can anyone suggest a way to do this? What glade object do I need to use and how to redirect the output? A: After lots of reading and not getting the results I wanted, I found another method that works. It goes like this #!/usr/bine/env python import subprocess import gtk ### Of course, you should have the gui built and know which widgets to use for this. viewer = self.builder.get_object('txtview') proc = subprocess.Popen('ls -al /home'.split(), stdout=subprocess.PIPE, stderr = subprocess.STDOUT) while True: line = proc.stdout.readline() viewer.get_buffer().insert_at_cursor(line) if not line: break A: Here is a link that also displays another way of doing this. I found this to be very insightful, maybe someone else can use these tips. http://pygabriel.wordpress.com/2009/07/27/redirecting-the-stdout-on-a-gtk-textview/ A: glade is only a program to build gui with gtk so when you ask for a glade object maybe you should ask for gtk widget and in this case textbuffer and textview chould be a solution or maybe treeview and liststore. subprocess.Popen has stdout and stderr arguments that can accept a file-like object. you can create an adapter that writes to the textbuffer or add items in the liststore
Python GUI (glade) to display output of shell process
I'm writing a python application that runs several subprocesses using subprocess.Popen objects. I have a glade GUI and want to display the output of these commands (running in subprocess.Popen) in the gui in real time. Can anyone suggest a way to do this? What glade object do I need to use and how to redirect the output?
[ "After lots of reading and not getting the results I wanted, I found another method that works.\nIt goes like this\n#!/usr/bine/env python\nimport subprocess\nimport gtk\n\n### Of course, you should have the gui built and know which widgets to use for this.\nviewer = self.builder.get_object('txtview')\nproc = subprocess.Popen('ls -al /home'.split(), stdout=subprocess.PIPE, stderr = subprocess.STDOUT)\nwhile True:\n line = proc.stdout.readline()\n viewer.get_buffer().insert_at_cursor(line)\n if not line:\n break\n\n", "Here is a link that also displays another way of doing this.\nI found this to be very insightful, maybe someone else can use these tips.\nhttp://pygabriel.wordpress.com/2009/07/27/redirecting-the-stdout-on-a-gtk-textview/\n", "glade is only a program to build gui with gtk so when you ask for a glade object maybe you should ask for gtk widget and in this case textbuffer and textview chould be a solution or maybe treeview and liststore.\nsubprocess.Popen has stdout and stderr arguments that can accept a file-like object. you can create an adapter that writes to the textbuffer or add items in the liststore\n" ]
[ 2, 2, 1 ]
[]
[]
[ "glade", "python", "user_interface" ]
stackoverflow_0001929018_glade_python_user_interface.txt
Q: anyone have example python code that sends mail using sendmail and subprocess? I'm kind of confused about how subprocess.Popen works. If anyone has example code that sends email using the subprocess module and sendmail that'd be great. A: This doesn't directly answer the question, but given your response to a comment by "DNS", it might solve your problem. When sending SMTP mail, you need to understand that the "from" and "to" addresses that you pass to the smtplib.sendmail() routine as arguments are not the same thing as what you see in the From: and To: headers in the message when it's received. Those arguments become parameters given to the receiving SMTP mailer, with the "MAIL FROM" and "RCPT TO" commands. This is commonly referred to as the "envelope" of the mail, and the values usually show up in the Received: header lines. To specify the headers you want, you have to supply them yourself before the body of the message. The smtplib example shows how that's done, in that case with a tuple called "msg" that they prepend to the message body. A: One of the first gotchas I encountered with subprocess was the fact that it doesn't take full shell string commands by default. If you want to do the equivalent of a shell command like: os.system("echo hello world") you need to use the shell=True option: subprocess.Popen("echo hello world", shell=True)
anyone have example python code that sends mail using sendmail and subprocess?
I'm kind of confused about how subprocess.Popen works. If anyone has example code that sends email using the subprocess module and sendmail that'd be great.
[ "This doesn't directly answer the question, but given your response to a comment by \"DNS\", it might solve your problem.\nWhen sending SMTP mail, you need to understand that the \"from\" and \"to\" addresses that you pass to the smtplib.sendmail() routine as arguments are not the same thing as what you see in the From: and To: headers in the message when it's received. Those arguments become parameters given to the receiving SMTP mailer, with the \"MAIL FROM\" and \"RCPT TO\" commands. This is commonly referred to as the \"envelope\" of the mail, and the values usually show up in the Received: header lines.\nTo specify the headers you want, you have to supply them yourself before the body of the message. The smtplib example shows how that's done, in that case with a tuple called \"msg\" that they prepend to the message body.\n", "One of the first gotchas I encountered with subprocess was the fact that it doesn't take full shell string commands by default. \nIf you want to do the equivalent of a shell command like:\nos.system(\"echo hello world\")\n\nyou need to use the shell=True option:\nsubprocess.Popen(\"echo hello world\", shell=True)\n\n" ]
[ 2, 0 ]
[]
[]
[ "python", "sendmail", "subprocess" ]
stackoverflow_0001942305_python_sendmail_subprocess.txt
Q: how to properly destroy gtk.Dialog objects/widgets Noob @ programming with python and pygtk. I'm creating an application which includes a couple of dialogs for user interaction. #!usr/bin/env python import gtk info = gtk.MessageDialog(type=gtk.DIALOG_INFO, buttons=gtk.BUTTONS_OK) info.set_property('title', 'Test info message') info.set_property('text', 'Message to be displayed in the messagebox goes here') if info.run() == gtk.RESPONSE_OK: info.destroy() This displays my message dialog, however, when you click on the 'OK' button presented in the dialog, nothing happens, the box just freezes. What am I doing wrong here? A: @mg My bad. Your code is correct (and I guess my initial code was too) The reason my dialog was remaining on the screen is because my gtk.main loop is running on a separate thread. So all I had to was enclose your code (corrected version of mine) in between a gtk.gdk.threads_enter() and a gtk.gdk.threads_leave() and there it was. Thanks for your response. A: can you give me a last chance? ;) there are some errors in your code: you did not close a bracket your syntax in .set_property is wrong: use: .set_property('property', 'value') but i think they are copy/paste errors. try this code, it works for me. maybe did you forget the gtk.main()? import gtk info = gtk.MessageDialog(buttons=gtk.BUTTONS_OK) info.set_property('title', 'Test info message') info.set_property('text', 'Message to be displayed in the messagebox goes here') response = info.run() if response == gtk.RESPONSE_OK: print 'ok' else: print response info.destroy() gtk.main()
how to properly destroy gtk.Dialog objects/widgets
Noob @ programming with python and pygtk. I'm creating an application which includes a couple of dialogs for user interaction. #!usr/bin/env python import gtk info = gtk.MessageDialog(type=gtk.DIALOG_INFO, buttons=gtk.BUTTONS_OK) info.set_property('title', 'Test info message') info.set_property('text', 'Message to be displayed in the messagebox goes here') if info.run() == gtk.RESPONSE_OK: info.destroy() This displays my message dialog, however, when you click on the 'OK' button presented in the dialog, nothing happens, the box just freezes. What am I doing wrong here?
[ "@mg\nMy bad. Your code is correct (and I guess my initial code was too)\nThe reason my dialog was remaining on the screen is because my gtk.main loop is running on a separate thread.\nSo all I had to was enclose your code (corrected version of mine) in between a\ngtk.gdk.threads_enter()\n\nand a \ngtk.gdk.threads_leave()\n\nand there it was. \nThanks for your response.\n", "can you give me a last chance? ;)\nthere are some errors in your code:\n\nyou did not close a bracket\nyour syntax in .set_property is wrong: use: .set_property('property', 'value')\n\nbut i think they are copy/paste errors.\ntry this code, it works for me. maybe did you forget the gtk.main()?\nimport gtk\n\ninfo = gtk.MessageDialog(buttons=gtk.BUTTONS_OK)\ninfo.set_property('title', 'Test info message')\ninfo.set_property('text', 'Message to be displayed in the messagebox goes here')\nresponse = info.run()\nif response == gtk.RESPONSE_OK:\n print 'ok'\nelse:\n print response\ninfo.destroy()\n\ngtk.main()\n\n" ]
[ 3, 2 ]
[]
[]
[ "dialog", "pygtk", "python" ]
stackoverflow_0001942295_dialog_pygtk_python.txt
Q: Simple code but can't find the error (PyS60 but not specific) I'm a Python beginner and now it's freakin me out: L = [] file = urllib.urlopen("http://someurl.com/someText.txt") line = file.readline() while line != "" : L.append(line) line = file.readline() appuifw.selection_list(choices=L) and I get this error: line = file.readline() ^ SyntaxError: invalid syntax Does anyone know what the issue is? A: Rewriting to file = urllib.urlopen("http://blabla.com/bla.txt") lines1 = file.readlines() for li in lines1: L.append(li) index = appuifw.selection_list(choices=L) it seems to work now. (Still problems left but I think it's the URL) A: Show the invisibles. I bet there is an illegal character (null is a favorite) hiding in one of those lines and it's not showing up on your screen. Or maybe the file has the wrong type of line ends. My usual tricks here: 1) You might have typed it in right in StackOverflow; try copying this code back into the source and see if it fixes things. Sometimes it's hard to see if you put a ] where a ) or } should be. 2) Comment out all the lines, then uncomment them one at a time until the syntax error reappears. If the syntax error is there when you comment out all the other lines, then ther real problem is upstream. 3) Delete the line in question and a couple lines below and above it. Delete these lines in a single operation; you don't want the bad character to stay around because it was in between two lines that you deleted one at a time. Then retype those lines. Don't paste them back in; that might just paste the problem right back in. A: Seems to work fine in my Python interpreter (2.6.1). I take it you did do import urllib first? (Not doing that would cause a NameError, not a SyntaxError.) EDIT: a quick Google found this: http://discussion.forum.nokia.com/forum/showthread.php?t=150563 It’s 18 months old, but it claims that PyS60 is Python 2.2.2. I don’t have that on my machine, but it might be worth seeing if that’s the issue. A: I actually don't see a problem, unless you're mixing tabs and spaces in that indentation, in which case the error should complaining about indentation levels. But I thought I'd point out that there's a much cleaner way to read all the lines in a file-like object: f = urllib.urlopen("http://someurl.com/someText.txt") lines = f.readlines() appuifw.selection_list(choices=lines) A: You are overwriting the built-in function file with you variable of the same name. Maybe that causes the Py60 some grief?
Simple code but can't find the error (PyS60 but not specific)
I'm a Python beginner and now it's freakin me out: L = [] file = urllib.urlopen("http://someurl.com/someText.txt") line = file.readline() while line != "" : L.append(line) line = file.readline() appuifw.selection_list(choices=L) and I get this error: line = file.readline() ^ SyntaxError: invalid syntax Does anyone know what the issue is?
[ "Rewriting to\nfile = urllib.urlopen(\"http://blabla.com/bla.txt\")\nlines1 = file.readlines()\nfor li in lines1:\n L.append(li)\nindex = appuifw.selection_list(choices=L)\n\nit seems to work now.\n(Still problems left but I think it's the URL)\n", "Show the invisibles. I bet there is an illegal character (null is a favorite) hiding in one of those lines and it's not showing up on your screen. Or maybe the file has the wrong type of line ends.\nMy usual tricks here:\n1) You might have typed it in right in StackOverflow; try copying this code back into the source and see if it fixes things. Sometimes it's hard to see if you put a ] where a ) or } should be.\n2) Comment out all the lines, then uncomment them one at a time until the syntax error reappears. If the syntax error is there when you comment out all the other lines, then ther real problem is upstream.\n3) Delete the line in question and a couple lines below and above it. Delete these lines in a single operation; you don't want the bad character to stay around because it was in between two lines that you deleted one at a time. Then retype those lines. Don't paste them back in; that might just paste the problem right back in.\n", "Seems to work fine in my Python interpreter (2.6.1).\nI take it you did do import urllib first? (Not doing that would cause a NameError, not a SyntaxError.)\nEDIT: a quick Google found this: http://discussion.forum.nokia.com/forum/showthread.php?t=150563\nIt’s 18 months old, but it claims that PyS60 is Python 2.2.2. I don’t have that on my machine, but it might be worth seeing if that’s the issue.\n", "I actually don't see a problem, unless you're mixing tabs and spaces in that indentation, in which case the error should complaining about indentation levels. But I thought I'd point out that there's a much cleaner way to read all the lines in a file-like object:\nf = urllib.urlopen(\"http://someurl.com/someText.txt\")\nlines = f.readlines()\nappuifw.selection_list(choices=lines)\n\n", "You are overwriting the built-in function file with you variable of the same name. Maybe that causes the Py60 some grief?\n" ]
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "pys60", "python" ]
stackoverflow_0001942559_pys60_python.txt
Q: String class internals - caching character offset to byte relationship if using UTF-8 When writing a custom string class that stores UTF-8 internally (to save memory) rather than UTF-16 from scratch is it feasible to some extent cache the relationship between byte offset and character offset to increase performance when applications use the class with random access? Does Perl do this kind of caching of character offset to byte offset relationship? How do Python strings work internally? What about Objective-C and Java? Do they use UTF-8 internally? EDIT Found this reference to Perl 5 using UTF-8 internally: "$flag = utf8::is_utf8(STRING) (Since Perl 5.8.1) Test whether STRING is in UTF-8 internally. Functionally the same as Encode::is_utf8()." On page http://perldoc.perl.org/utf8.html EDIT In the applications I have in mind, the strings have 1-2K XML stanzas in an XMPP stream. About 1% of the messages are going to have I expect up to 50% (by character count) of Unicode values > 127 (this is XML). In servers, the messages are rule-checked and routed conditionally on a small (character volume wise) subset of fields. The servers are Wintel boxes operating in a farm. In clients, the data comes from and is fed into UI toolkits. EDIT But the app wil inevitably evolve and want to do some random access too. Can the performance hit when this happens be minimised: I was also interested if a more general class design exists that eg manages b-trees of character offset <-> byte offset relationships for big UTF8 strings (or some other algorithm found to be efficient in the general case.) A: Perl distinguishes between Unicode and non-Unicode strings. Unicode strings are implemented using UTF-8 internally. Non-Unicode does not necessarily mean 7-bit ASCII, though, it could be any character that can be represented in the current locale as a single byte. A: I think the answer is: in general, it's not really worth trying to do this. In your specific case, maybe. If most of your characters are plain ASCII, and you rarely have UTF sequences, then it might be worth building some kind of sparse data structure with the offsets. In the general case, every single character might be non-ASCII and you might have many many offsets to store. Really, the most general case would be to make a string of bytes that is exactly as long as your string of Unicode characters, and have each byte value be the offset of the next character. But this means one whole byte per character, and thus a net savings of only one byte per Unicode character; probably not worth the effort. And that implies that indexing into your string is now an O(n) operation, as you run through these offsets and sum them to find the actual index. If you do want to try the sparse data structure, I suggest an array of pairs of values, the first value being the index within the Unicode string of a character, and the second one being the index within the byte sequence where this character actually appears. Then after each UTF8 escape sequence, you would add the two values to find the next character in the string. Finally, when given an index to a Unicode character, your code could do a binary search of this array, to find the highest index within the sparse array that is lower than the requested index, and then use that to find the actual byte that represents the start of the desired character. If you need to save memory, you might want to consider using a data compression library. Slurp in the Unicode strings as full Unicode, then compress them; then to index into a string, first you uncompress that string. This will really save memory, and it will be easy and fast to get the code correct to make it work; but it may add too much CPU overhead to be reasonable. A: Java's strings are UTF-16 internally: A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String. java.lang.String
String class internals - caching character offset to byte relationship if using UTF-8
When writing a custom string class that stores UTF-8 internally (to save memory) rather than UTF-16 from scratch is it feasible to some extent cache the relationship between byte offset and character offset to increase performance when applications use the class with random access? Does Perl do this kind of caching of character offset to byte offset relationship? How do Python strings work internally? What about Objective-C and Java? Do they use UTF-8 internally? EDIT Found this reference to Perl 5 using UTF-8 internally: "$flag = utf8::is_utf8(STRING) (Since Perl 5.8.1) Test whether STRING is in UTF-8 internally. Functionally the same as Encode::is_utf8()." On page http://perldoc.perl.org/utf8.html EDIT In the applications I have in mind, the strings have 1-2K XML stanzas in an XMPP stream. About 1% of the messages are going to have I expect up to 50% (by character count) of Unicode values > 127 (this is XML). In servers, the messages are rule-checked and routed conditionally on a small (character volume wise) subset of fields. The servers are Wintel boxes operating in a farm. In clients, the data comes from and is fed into UI toolkits. EDIT But the app wil inevitably evolve and want to do some random access too. Can the performance hit when this happens be minimised: I was also interested if a more general class design exists that eg manages b-trees of character offset <-> byte offset relationships for big UTF8 strings (or some other algorithm found to be efficient in the general case.)
[ "Perl distinguishes between Unicode and non-Unicode strings. Unicode strings are implemented using UTF-8 internally. Non-Unicode does not necessarily mean 7-bit ASCII, though, it could be any character that can be represented in the current locale as a single byte. \n", "I think the answer is: in general, it's not really worth trying to do this. In your specific case, maybe.\nIf most of your characters are plain ASCII, and you rarely have UTF sequences, then it might be worth building some kind of sparse data structure with the offsets.\nIn the general case, every single character might be non-ASCII and you might have many many offsets to store. Really, the most general case would be to make a string of bytes that is exactly as long as your string of Unicode characters, and have each byte value be the offset of the next character. But this means one whole byte per character, and thus a net savings of only one byte per Unicode character; probably not worth the effort. And that implies that indexing into your string is now an O(n) operation, as you run through these offsets and sum them to find the actual index.\nIf you do want to try the sparse data structure, I suggest an array of pairs of values, the first value being the index within the Unicode string of a character, and the second one being the index within the byte sequence where this character actually appears. Then after each UTF8 escape sequence, you would add the two values to find the next character in the string. Finally, when given an index to a Unicode character, your code could do a binary search of this array, to find the highest index within the sparse array that is lower than the requested index, and then use that to find the actual byte that represents the start of the desired character.\nIf you need to save memory, you might want to consider using a data compression library. Slurp in the Unicode strings as full Unicode, then compress them; then to index into a string, first you uncompress that string. This will really save memory, and it will be easy and fast to get the code correct to make it work; but it may add too much CPU overhead to be reasonable.\n", "Java's strings are UTF-16 internally:\n\nA String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.\n\njava.lang.String\n" ]
[ 2, 1, 1 ]
[]
[]
[ "java", "objective_c", "perl", "python", "utf_8" ]
stackoverflow_0001942282_java_objective_c_perl_python_utf_8.txt
Q: How to generate an audio stream using gst-python? I'm looking to generate a stream in gstreamer, and I'd prefer to do it from python if possible. This points towards using gst-python, but I don't see a clear way to do it. It looks like creating a new stream would require making a gstreamer plugin, which gst-python doesn't seem to be able to do. To clarify, I'd like to be able to generate the actual values getting handed to the sound card, allowing me to, for example, make a sine-curve tone. I don't want to use the built-in python OSS support, as it's a bit outdated, and locks /dev/dsp. Does anyone have a suggestion of something to try? Or even another (modern) sound system that can do this? A: Take a look at appsrc (gst-inspect appsrc). I used its counterpart appsink to get data out of a gstreamer pipeline. And here's an (almost)-working example. http://gstreamer-devel.966125.n4.nabble.com/appsrc-random-crash-td973529.html
How to generate an audio stream using gst-python?
I'm looking to generate a stream in gstreamer, and I'd prefer to do it from python if possible. This points towards using gst-python, but I don't see a clear way to do it. It looks like creating a new stream would require making a gstreamer plugin, which gst-python doesn't seem to be able to do. To clarify, I'd like to be able to generate the actual values getting handed to the sound card, allowing me to, for example, make a sine-curve tone. I don't want to use the built-in python OSS support, as it's a bit outdated, and locks /dev/dsp. Does anyone have a suggestion of something to try? Or even another (modern) sound system that can do this?
[ "Take a look at appsrc (gst-inspect appsrc). I used its counterpart appsink to get data out of a gstreamer pipeline.\nAnd here's an (almost)-working example. http://gstreamer-devel.966125.n4.nabble.com/appsrc-random-crash-td973529.html\n" ]
[ 3 ]
[]
[]
[ "audio", "gstreamer", "python" ]
stackoverflow_0001932120_audio_gstreamer_python.txt
Q: Using paver and nose together with an atypical directory structure I'm trying to write a task for Paver that will run nosetests on my files. My directory structure looks like this: project/ file1.py file2.py file3.py build/ pavement.py subproject/ file4.py test/ file5.py file6.py Doctests (using the --with_doctest option) should be run on all the *.py files, while only the files under project/test (in this example, file5.py and file6.py) should be searched for test routines. I can't seem to figure out how to do this--I can write a custom plugin for nose which includes the correct files, but I can't seem to get paver to build and install it before calling the nosetests task. I also can't find a way to get paver to pass a list of files to test to nosetests on the command line. What's the best way of getting this to work? A: Is this at all close to what you're trying to get at? from paver.easy import sh, path __path__ = path(__file__).abspath().dirname() @task def setup_nose_plugin(): # ... do your plugin setup here. @task @needs('setup_nose_plugin') def nosetests(): nose_options = '--with-doctest' # Put your command-line options in there sh('nosetests %s' % nose_options, # Your pavement.py is in a weird place, so you need to specify the working dir: cwd=__path__.parent) I'm not actually sure how to tell nose to look in specific files, but that's a matter of command-line options. --where lets you specify a directory, but I don't see a way to say "run only doctests here, and other tests here". You may need two invocations of sh('nosetests') to do all that.
Using paver and nose together with an atypical directory structure
I'm trying to write a task for Paver that will run nosetests on my files. My directory structure looks like this: project/ file1.py file2.py file3.py build/ pavement.py subproject/ file4.py test/ file5.py file6.py Doctests (using the --with_doctest option) should be run on all the *.py files, while only the files under project/test (in this example, file5.py and file6.py) should be searched for test routines. I can't seem to figure out how to do this--I can write a custom plugin for nose which includes the correct files, but I can't seem to get paver to build and install it before calling the nosetests task. I also can't find a way to get paver to pass a list of files to test to nosetests on the command line. What's the best way of getting this to work?
[ "Is this at all close to what you're trying to get at?\nfrom paver.easy import sh, path\n__path__ = path(__file__).abspath().dirname()\n\n@task\ndef setup_nose_plugin():\n # ... do your plugin setup here.\n\n@task\n@needs('setup_nose_plugin')\ndef nosetests():\n nose_options = '--with-doctest' # Put your command-line options in there\n sh('nosetests %s' % nose_options, \n # Your pavement.py is in a weird place, so you need to specify the working dir:\n cwd=__path__.parent)\n\nI'm not actually sure how to tell nose to look in specific files, but that's a matter of command-line options. \n--where lets you specify a directory, but I don't see a way to say \"run only doctests here, and other tests here\". You may need two invocations of sh('nosetests') to do all that.\n" ]
[ 2 ]
[]
[]
[ "nose", "paver", "python" ]
stackoverflow_0000722992_nose_paver_python.txt
Q: A little misunderstanding timers in python can somebody tell me how to use this class timers from python in my code more than one time. import MOD class timer: def __init__(self, seconds): self.start(seconds) def start(self, seconds): self.startTime = MOD.secCounter() self.expirationTime = self.startTime + seconds if seconds != 0: self.running = 1 self.expired = 0 else: self.running = 0 self.expired = 0 def stop(self): self.running = 0 self.expired = 0 def isexpired(self): if self.running == 1: timeNow = MOD.secCounter() if timeNow > self.expirationTime: self.running = 0 self.expired = 1 else: self.expired = 0 return self.expired def isrunning(self): if self.running == 1: timeNow = MOD.secCounter() if timeNow > self.expirationTime: self.running = 0 self.expired = 1 else: self.expired = 0 return self.running def change(self, seconds): self.expirationTime = self.startTime + seconds def count(self): if self.running == 1: timeNow = MOD.secCounter() return (timeNow - self.startTime) else: return -1 they write this comment: The following is a simple example about how to use this class: import timers timerA = timers.timer(0) timerA.start(15) while 1: if timerA.isexpired(): print 'timerA expired' break but I don't know how to use it more than one time in my code, because I need to use more than one timer in my code, should I write timerB = timers.timer(1) timerB.start(1800) while 1: if timerB.isexpired(): print 'timerA expired' break any help, please A: Close - the argument to timers.timer is the number of seconds that the timer should time for at first. But every time you call timers.timer(), you'll get a new timer instance. So your code could look more like: timerB = timers.timer(1800) while 1: if timerB.isexpired(): print 'timerA expired' break Except that this is misleading - timerA and timerB are separate timers, so timerB.isexpired() won't tell you anything about timerA. Maybe you meant it to read "timerB expired"? And I would also advise against polling timerB.isexpired() so rapidly. Maybe sleep for a second after each check?
A little misunderstanding timers in python
can somebody tell me how to use this class timers from python in my code more than one time. import MOD class timer: def __init__(self, seconds): self.start(seconds) def start(self, seconds): self.startTime = MOD.secCounter() self.expirationTime = self.startTime + seconds if seconds != 0: self.running = 1 self.expired = 0 else: self.running = 0 self.expired = 0 def stop(self): self.running = 0 self.expired = 0 def isexpired(self): if self.running == 1: timeNow = MOD.secCounter() if timeNow > self.expirationTime: self.running = 0 self.expired = 1 else: self.expired = 0 return self.expired def isrunning(self): if self.running == 1: timeNow = MOD.secCounter() if timeNow > self.expirationTime: self.running = 0 self.expired = 1 else: self.expired = 0 return self.running def change(self, seconds): self.expirationTime = self.startTime + seconds def count(self): if self.running == 1: timeNow = MOD.secCounter() return (timeNow - self.startTime) else: return -1 they write this comment: The following is a simple example about how to use this class: import timers timerA = timers.timer(0) timerA.start(15) while 1: if timerA.isexpired(): print 'timerA expired' break but I don't know how to use it more than one time in my code, because I need to use more than one timer in my code, should I write timerB = timers.timer(1) timerB.start(1800) while 1: if timerB.isexpired(): print 'timerA expired' break any help, please
[ "Close - the argument to timers.timer is the number of seconds that the timer should time for at first. But every time you call timers.timer(), you'll get a new timer instance.\nSo your code could look more like:\n timerB = timers.timer(1800)\n while 1: \n if timerB.isexpired(): \n print 'timerA expired' \n break\n\nExcept that this is misleading - timerA and timerB are separate timers, so timerB.isexpired() won't tell you anything about timerA. Maybe you meant it to read \"timerB expired\"?\nAnd I would also advise against polling timerB.isexpired() so rapidly. Maybe sleep for a second after each check?\n" ]
[ 2 ]
[]
[]
[ "python", "timer" ]
stackoverflow_0001943182_python_timer.txt
Q: wxPython progress bar I can't use wx.ProgressDialog because I need to add extra contents to the dialog box (a pause button and information about what is currently being processed). Is there a control for just the progress bar that I can use in my own dialog box? I could of course draw something simple myself, but since the program needs to run on Mac OS X, Windows, and Linux it would be better if the progress bars had a native look. A: What about wxGauge which displays a horizontal or vertical bar? http://www.wxpython.org/docs/api/wx.Gauge-class.html More complete C++ doc: http://docs.wxwidgets.org/2.6/wx_wxgauge.html#wxgauge A: You could always create your own derivative of wx.Dialog and using a sizer, add in the widgets you require. Here's one from my program, for example: class ProgressDialog(wx.Dialog): """ Shows a Progres Gauge while an operation is taking place. May be cancellable which is possible when converting pdf/ps """ def __init__(self, gui, title, to_add=1, cancellable=False): """Defines a gauge and a timer which updates the gauge.""" wx.Dialog.__init__(self, gui, title=title, style=wx.CAPTION) self.gui = gui self.count = 0 self.to_add = to_add self.timer = wx.Timer(self) self.gauge = wx.Gauge(self, range=100, size=(180, 30)) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.gauge, 0, wx.ALL, 10) if cancellable: cancel = wx.Button(self, wx.ID_CANCEL, _("&Cancel")) cancel.SetDefault() cancel.Bind(wx.EVT_BUTTON, self.on_cancel) btnSizer = wx.StdDialogButtonSizer() btnSizer.AddButton(cancel) btnSizer.Realize() sizer.Add(btnSizer, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10) self.SetSizer(sizer) sizer.Fit(self) self.SetFocus() self.Bind(wx.EVT_TIMER, self.on_timer, self.timer) self.timer.Start(30) def on_timer(self, event): """Increases the gauge's progress.""" self.count += self.to_add self.gauge.SetValue(self.count) if self.count > 100: self.count = 0 def on_cancel(self, event): """Cancels the conversion process""" # do whatever
wxPython progress bar
I can't use wx.ProgressDialog because I need to add extra contents to the dialog box (a pause button and information about what is currently being processed). Is there a control for just the progress bar that I can use in my own dialog box? I could of course draw something simple myself, but since the program needs to run on Mac OS X, Windows, and Linux it would be better if the progress bars had a native look.
[ "What about wxGauge which displays a horizontal or vertical bar?\nhttp://www.wxpython.org/docs/api/wx.Gauge-class.html\nMore complete C++ doc:\nhttp://docs.wxwidgets.org/2.6/wx_wxgauge.html#wxgauge \n", "You could always create your own derivative of wx.Dialog and using a sizer, add in the widgets you require.\nHere's one from my program, for example:\nclass ProgressDialog(wx.Dialog):\n \"\"\"\n Shows a Progres Gauge while an operation is taking place. May be cancellable\n which is possible when converting pdf/ps\n \"\"\"\n def __init__(self, gui, title, to_add=1, cancellable=False):\n \"\"\"Defines a gauge and a timer which updates the gauge.\"\"\"\n wx.Dialog.__init__(self, gui, title=title,\n style=wx.CAPTION)\n self.gui = gui\n self.count = 0\n self.to_add = to_add\n self.timer = wx.Timer(self)\n self.gauge = wx.Gauge(self, range=100, size=(180, 30))\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(self.gauge, 0, wx.ALL, 10)\n\n if cancellable:\n cancel = wx.Button(self, wx.ID_CANCEL, _(\"&Cancel\"))\n cancel.SetDefault()\n cancel.Bind(wx.EVT_BUTTON, self.on_cancel)\n btnSizer = wx.StdDialogButtonSizer()\n btnSizer.AddButton(cancel)\n btnSizer.Realize()\n sizer.Add(btnSizer, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10)\n\n self.SetSizer(sizer)\n sizer.Fit(self)\n self.SetFocus()\n\n self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)\n self.timer.Start(30)\n\n\n def on_timer(self, event):\n \"\"\"Increases the gauge's progress.\"\"\"\n self.count += self.to_add\n self.gauge.SetValue(self.count)\n if self.count > 100:\n self.count = 0\n\n\n def on_cancel(self, event):\n \"\"\"Cancels the conversion process\"\"\"\n # do whatever\n\n" ]
[ 6, 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001883528_python_wxpython.txt
Q: Python regular expression inconsistency I am getting different results based on whether I precompile a regular expression: >>> re.compile('mr', re.IGNORECASE).sub('', 'Mr Bean') ' Bean' >>> re.sub('mr', '', 'Mr Bean', re.IGNORECASE) 'Mr Bean' The Python documentation says Some of the functions are simplified versions of the full featured methods for compiled regular expressions. However it also claims RegexObject.sub() is Identical to the sub() function. So what is going on here? A: re.sub() can't accept the re.IGNORECASE, it appears. The documentation states: sub(pattern, repl, string, count=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used. Using this works in its place, however: re.sub("(?i)mr", "", "Mr Bean") A: the module level sub() call doesn't accept modifiers at the end. thats the "count" argument - the maximum number of pattern occurrences to be replaced. A: >>> help(re.sub) 1 Help on function sub in module re: 2 3 sub(pattern, repl, string, count=0) 4 Return the string obtained by replacing the leftmost 5 non-overlapping occurrences of the pattern in string by the 6 replacement repl. repl can be either a string or a callable; 7 if a callable, it's passed the match object and must return 8 a replacement string to be used. There is no function parameter in re.sub for regex flags (IGNORECASE, MULTILINE, DOTALL) as in re.compile. Alternatives: >>> re.sub("[M|m]r", "", "Mr Bean") ' Bean' >>> re.sub("(?i)mr", "", "Mr Bean") ' Bean' Edit Python 3.1 added support for regex flags, http://docs.python.org/3.1/whatsnew/3.1.html. As of 3.1 the signature of e.g. re.sub looks like: re.sub(pattern, repl, string[, count, flags]) A: From the Python 2.6.4 documentation: re.sub(pattern, repl, string[, count]) re.sub() doesn't take a flag to set the regex mode. If you want re.IGNORECASE, you must use re.compile().sub()
Python regular expression inconsistency
I am getting different results based on whether I precompile a regular expression: >>> re.compile('mr', re.IGNORECASE).sub('', 'Mr Bean') ' Bean' >>> re.sub('mr', '', 'Mr Bean', re.IGNORECASE) 'Mr Bean' The Python documentation says Some of the functions are simplified versions of the full featured methods for compiled regular expressions. However it also claims RegexObject.sub() is Identical to the sub() function. So what is going on here?
[ "re.sub() can't accept the re.IGNORECASE, it appears.\nThe documentation states:\n\nsub(pattern, repl, string, count=0) \nReturn the string obtained by replacing the leftmost\nnon-overlapping occurrences of the pattern in string by the\nreplacement repl. repl can be either a string or a callable;\nif a string, backslash escapes in it are processed. If it is\na callable, it's passed the match object and must return\na replacement string to be used.\n\nUsing this works in its place, however:\nre.sub(\"(?i)mr\", \"\", \"Mr Bean\")\n\n", "the module level sub() call doesn't accept modifiers at the end. thats the \"count\" argument - the maximum number of pattern occurrences to be replaced.\n", ">>> help(re.sub)\n 1 Help on function sub in module re:\n 2 \n 3 sub(pattern, repl, string, count=0)\n 4 Return the string obtained by replacing the leftmost\n 5 non-overlapping occurrences of the pattern in string by the\n 6 replacement repl. repl can be either a string or a callable;\n 7 if a callable, it's passed the match object and must return\n 8 a replacement string to be used.\n\nThere is no function parameter in re.sub for regex flags (IGNORECASE, MULTILINE, DOTALL) as in re.compile.\nAlternatives:\n>>> re.sub(\"[M|m]r\", \"\", \"Mr Bean\")\n' Bean'\n\n>>> re.sub(\"(?i)mr\", \"\", \"Mr Bean\")\n' Bean'\n\n\nEdit Python 3.1 added support for regex flags, http://docs.python.org/3.1/whatsnew/3.1.html. As of 3.1 the signature of e.g. re.sub looks like:\nre.sub(pattern, repl, string[, count, flags])\n\n", "From the Python 2.6.4 documentation:\nre.sub(pattern, repl, string[, count])\n\nre.sub() doesn't take a flag to set the regex mode. If you want re.IGNORECASE, you must use re.compile().sub()\n" ]
[ 12, 5, 4, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001943400_python_regex.txt
Q: python fetching multiple pages using post and cookies Got a test site that I'm fetching. The site uses the POST method, as well as cookies. (Not sure that the cookies are critical, but i'm inclined to think they are..) The app presents a page, with a "next button" to generate the subsequent pages. I've used LiveHttpHeaders/Firefof to determine what the post data should be in the query, as well as the fact that the cookies are being set. I've also verified that the page doesn't work if cookies are dosabled by the browser. I'm trying to figure out what I've missed/screwed up in my test. The sample code presents the query/post data for both the 1st and 2nd page that I'm trying to fetch. I've searched the net, as well as triedn numerous different possible attempts, so I'm pretty sure that I missing something simple.. Any thoughts/comments are appreciated.. #!/usr/bin/python #test python script import re import urllib import urllib2 import sys, string, os from mechanize import Browser import mechanize import cookielib ######################## # # Parsing App Information ######################## # datafile cj = "p" COOKIEFILE = 'cookies.lwp' #cookielib = 1 urlopen = urllib2.urlopen #cj = urllib2.cookielib.LWPCookieJar() cj = cookielib.LWPCookieJar() #cj = ClientCookie.LWPCookieJar() Request = urllib2.Request br = Browser() if cj != None: print "sss" #install the CookieJar for the default CookieProcessor if os.path.isfile(COOKIEFILE): cj.load(COOKIEFILE) print "foo\n" if cookielib: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) print "foo2\n" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } if __name__ == "__main__": # main app baseurl="https://pisa.ucsc.edu/class_search/index.php" print "b = ",baseurl print "b = ",headers query="action=results&binds%5B%3Aterm%5D=2100&binds%5B%3Areg_status%5D=O&binds%5B%3Asubject%5D=&binds%5B%3Acatalog_nbr_op%5D=%3D&binds%5B%3Acatalog_nbr%5D=&binds%5B%3Atitle%5D=&binds%5B%3Ainstr_name_op%5D=%3D&binds%5B%3Ainstructor%5D=&binds%5B%3Age%5D=&binds%5B%3Acrse_units_op%5D=%3D&binds%5B%3Acrse_units_from%5D=&binds%5B%3Acrse_units_to%5D=&binds%5B%3Acrse_units_exact%5D=&binds%5B%3Adays%5D=&binds%5B%3Atimes%5D=&binds%5B%3Aacad_career%5D=" request = urllib2.Request(baseurl, query, headers) response = urllib2.urlopen(request) print "gggg \n" #print req print "\n gggg 555555\n" print "res = ",response x1 = response.read() #x1 = res.read() print x1 #sys.exit() cj.save(COOKIEFILE) # resave cookies if cj is None: print "We don't have a cookie library available - sorry." print "I can't show you any cookies." else: print 'These are the cookies we have received so far :' for index, cookie in enumerate (cj): print index, ' : ', cookie cj.save(COOKIEFILE) print "ffgg \n" for index, cookie in enumerate (cj): print index, ' : ', cookie #baseurl ="http://students.yale.edu/oci/resultList.jsp" baseurl="https://pisa.ucsc.edu/class_search/index.php" query="action=next&Rec_Dur=100&sel_col%5Bclass_nbr%5D=1&sel_col%5Bclass_id%5D=1&sel_col%5Bclass_title%5D=1&sel_col%5Btype%5D=1&sel_col%5Bdays%5D=1&sel_col%5Btimes%5D=1&sel_col%5Binstr_name%5D=1&sel_col%5Bstatus%5D=1&sel_col%5Benrl_cap%5D=1&sel_col%5Benrl_tot%5D=1&sel_col%5Bseats_avail%5D=1&sel_col%5Blocation%5D=1" request = urllib2.Request(baseurl, query, headers) response = urllib2.urlopen(request) print "gggg \n" #print req print "\n gggg 555555\n" print "res = ",response x1 = response.read() #x1 = res.read() print x1 sys.exit() req = Request(baseurl, query, headers) print "gggg \n" #print req print "\n gggg 555555\n" #br.open(req) res = urlopen(req) print "gggg 000000000000\n" x1 = res.read() print x1 sys.exit() thanks for any thoughts/pointers... and yeah.. i know.. the script/test is really bad! -tom A: I'm really not sure what's going wrong. It may not be helpful, but a different way to do it: Open a table-row for each 1st page submit then keep only the rowId in the cookie and add to the row with subsequent accesses. tf.
python fetching multiple pages using post and cookies
Got a test site that I'm fetching. The site uses the POST method, as well as cookies. (Not sure that the cookies are critical, but i'm inclined to think they are..) The app presents a page, with a "next button" to generate the subsequent pages. I've used LiveHttpHeaders/Firefof to determine what the post data should be in the query, as well as the fact that the cookies are being set. I've also verified that the page doesn't work if cookies are dosabled by the browser. I'm trying to figure out what I've missed/screwed up in my test. The sample code presents the query/post data for both the 1st and 2nd page that I'm trying to fetch. I've searched the net, as well as triedn numerous different possible attempts, so I'm pretty sure that I missing something simple.. Any thoughts/comments are appreciated.. #!/usr/bin/python #test python script import re import urllib import urllib2 import sys, string, os from mechanize import Browser import mechanize import cookielib ######################## # # Parsing App Information ######################## # datafile cj = "p" COOKIEFILE = 'cookies.lwp' #cookielib = 1 urlopen = urllib2.urlopen #cj = urllib2.cookielib.LWPCookieJar() cj = cookielib.LWPCookieJar() #cj = ClientCookie.LWPCookieJar() Request = urllib2.Request br = Browser() if cj != None: print "sss" #install the CookieJar for the default CookieProcessor if os.path.isfile(COOKIEFILE): cj.load(COOKIEFILE) print "foo\n" if cookielib: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) print "foo2\n" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } if __name__ == "__main__": # main app baseurl="https://pisa.ucsc.edu/class_search/index.php" print "b = ",baseurl print "b = ",headers query="action=results&binds%5B%3Aterm%5D=2100&binds%5B%3Areg_status%5D=O&binds%5B%3Asubject%5D=&binds%5B%3Acatalog_nbr_op%5D=%3D&binds%5B%3Acatalog_nbr%5D=&binds%5B%3Atitle%5D=&binds%5B%3Ainstr_name_op%5D=%3D&binds%5B%3Ainstructor%5D=&binds%5B%3Age%5D=&binds%5B%3Acrse_units_op%5D=%3D&binds%5B%3Acrse_units_from%5D=&binds%5B%3Acrse_units_to%5D=&binds%5B%3Acrse_units_exact%5D=&binds%5B%3Adays%5D=&binds%5B%3Atimes%5D=&binds%5B%3Aacad_career%5D=" request = urllib2.Request(baseurl, query, headers) response = urllib2.urlopen(request) print "gggg \n" #print req print "\n gggg 555555\n" print "res = ",response x1 = response.read() #x1 = res.read() print x1 #sys.exit() cj.save(COOKIEFILE) # resave cookies if cj is None: print "We don't have a cookie library available - sorry." print "I can't show you any cookies." else: print 'These are the cookies we have received so far :' for index, cookie in enumerate (cj): print index, ' : ', cookie cj.save(COOKIEFILE) print "ffgg \n" for index, cookie in enumerate (cj): print index, ' : ', cookie #baseurl ="http://students.yale.edu/oci/resultList.jsp" baseurl="https://pisa.ucsc.edu/class_search/index.php" query="action=next&Rec_Dur=100&sel_col%5Bclass_nbr%5D=1&sel_col%5Bclass_id%5D=1&sel_col%5Bclass_title%5D=1&sel_col%5Btype%5D=1&sel_col%5Bdays%5D=1&sel_col%5Btimes%5D=1&sel_col%5Binstr_name%5D=1&sel_col%5Bstatus%5D=1&sel_col%5Benrl_cap%5D=1&sel_col%5Benrl_tot%5D=1&sel_col%5Bseats_avail%5D=1&sel_col%5Blocation%5D=1" request = urllib2.Request(baseurl, query, headers) response = urllib2.urlopen(request) print "gggg \n" #print req print "\n gggg 555555\n" print "res = ",response x1 = response.read() #x1 = res.read() print x1 sys.exit() req = Request(baseurl, query, headers) print "gggg \n" #print req print "\n gggg 555555\n" #br.open(req) res = urlopen(req) print "gggg 000000000000\n" x1 = res.read() print x1 sys.exit() thanks for any thoughts/pointers... and yeah.. i know.. the script/test is really bad! -tom
[ "I'm really not sure what's going wrong. It may not be helpful, but a different way to do it:\nOpen a table-row for each 1st page submit then keep only the rowId in the cookie and add to the row with subsequent accesses.\ntf.\n" ]
[ 0 ]
[]
[]
[ "cookies", "post", "python", "urllib2" ]
stackoverflow_0001943546_cookies_post_python_urllib2.txt
Q: redirecting standard output to the calling process Im no bash expert so bear with me I have a python script thats starting other processes, which then emit log messages on stdout. what bash command would I use to redirect stdout of those child processes back to the stdout of the parent process (the python script thats starting the processes)? thank you in advance A: If you just want to capture the output of the child processes in your python script, the best way to do it would be to use the subprocess module: import subprocess p = subprocess.Popen(['/bin/ls', '-l'], stdout=subprocess.PIPE) (out, _) = p.communicate() print "Output:", out A: I'm assuming you're using os.system("command") to execute your scripts. This method only executes the command and gives you the program's return value and NOT it's stdout. What you need is the subprocess module. For example: import subprocess proc = subprocess.Popen(['command', 'option 1', 'option 2'], stdout=subprocess.PIPE) output = proc.communicate()[0] #for stdout. Use proc.communicate[1] for stderr On looking at your comment, your solution is simple: subprocess.Popen('command option 1 option 2', shell=True) Note: command needs to be passed as a string. A sequence doesn't work.
redirecting standard output to the calling process
Im no bash expert so bear with me I have a python script thats starting other processes, which then emit log messages on stdout. what bash command would I use to redirect stdout of those child processes back to the stdout of the parent process (the python script thats starting the processes)? thank you in advance
[ "If you just want to capture the output of the child processes in your python script, the best way to do it would be to use the subprocess module:\nimport subprocess\n\np = subprocess.Popen(['/bin/ls', '-l'], stdout=subprocess.PIPE)\n(out, _) = p.communicate()\nprint \"Output:\", out\n\n", "I'm assuming you're using os.system(\"command\") to execute your scripts. This method only executes the command and gives you the program's return value and NOT it's stdout. What you need is the subprocess module. For example:\nimport subprocess\n\nproc = subprocess.Popen(['command', 'option 1', 'option 2'], stdout=subprocess.PIPE)\noutput = proc.communicate()[0] #for stdout. Use proc.communicate[1] for stderr\n\nOn looking at your comment, your solution is simple:\nsubprocess.Popen('command option 1 option 2', shell=True)\n\nNote: command needs to be passed as a string. A sequence doesn't work.\n" ]
[ 3, 1 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0001943712_bash_python.txt
Q: Grab Focus for Frame after Shortcut Pressed in wxPython on GNOME I'm building an app that uses global shortcut keys (using python-keybinder), but there's a problem. The frame pops up and raises properly but doesn't have focus. I have to click on frame. After I press my keyboard shortcut my frame appears, but it is not focused. I can see that the frame I was focused on previously (e.g. my Firefox frame) still has focus (i.e., the title bar is still white & bold). Only after I click on my app's frame does Firefox's title bar become grey and dim. I try to SetFocus and CaptureMouse but neither do anything. FindFocus and GetCapture return None. This only happens on Ubuntu (GNOME). On Windows, the frame gets focus immediately. Is there a way to force GNOME to give focus to my app/frame? A: How are you showing the frmae initially, with frame.Show()? I'm not sure if you're saying the frame itself doesn't have focus (but/or a child of the frame does), or your application doesn't have focus? Are you calling SetFocus in the Frame that initialises all your widgets? It could be an issue of the focus being given to a child of the frame. Try using wx.CallAfter(self.SetFocus) at the end of your Frame.init method - it should ensure the focus is set after all widget creation is done
Grab Focus for Frame after Shortcut Pressed in wxPython on GNOME
I'm building an app that uses global shortcut keys (using python-keybinder), but there's a problem. The frame pops up and raises properly but doesn't have focus. I have to click on frame. After I press my keyboard shortcut my frame appears, but it is not focused. I can see that the frame I was focused on previously (e.g. my Firefox frame) still has focus (i.e., the title bar is still white & bold). Only after I click on my app's frame does Firefox's title bar become grey and dim. I try to SetFocus and CaptureMouse but neither do anything. FindFocus and GetCapture return None. This only happens on Ubuntu (GNOME). On Windows, the frame gets focus immediately. Is there a way to force GNOME to give focus to my app/frame?
[ "How are you showing the frmae initially, with frame.Show()? I'm not sure if you're saying the frame itself doesn't have focus (but/or a child of the frame does), or your application doesn't have focus?\nAre you calling SetFocus in the Frame that initialises all your widgets? It could be an issue of the focus being given to a child of the frame. Try using wx.CallAfter(self.SetFocus) at the end of your Frame.init method - it should ensure the focus is set after all widget creation is done\n" ]
[ 0 ]
[]
[]
[ "gnome", "python", "wxpython" ]
stackoverflow_0001943682_gnome_python_wxpython.txt
Q: Open 3rd party Application with Python I am on Windows XP and have a 3rd party application that I want to be able to open using a Python script. How do I go about doing it? from win32com.client import Dispatch mySuite = Dispatch("TestSuite.Application") throws an error File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\Script1.py", line 2, in <module> mySuite = Dispatch("TestSuite.Application") File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 98, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 78, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221005, 'Invalid class string', None, None) Any pointers? Thanks. A: Looks like the TestSuite.Application COM class has not been registered -- try opening it in, say, VBScript, to verify, and it should also fail. In which case maybe you can fix it with regsvr32.exe or similar tools.
Open 3rd party Application with Python
I am on Windows XP and have a 3rd party application that I want to be able to open using a Python script. How do I go about doing it? from win32com.client import Dispatch mySuite = Dispatch("TestSuite.Application") throws an error File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\Script1.py", line 2, in <module> mySuite = Dispatch("TestSuite.Application") File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 98, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 78, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221005, 'Invalid class string', None, None) Any pointers? Thanks.
[ "Looks like the TestSuite.Application COM class has not been registered -- try opening it in, say, VBScript, to verify, and it should also fail. In which case maybe you can fix it with regsvr32.exe or similar tools.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001943367_python.txt
Q: How to get value on a certain index, in a python list? I have a list which looks something like this List = [q1,a1,q2,a2,q3,a3] I need the final code to be something like this dictionary = {q1:a1,q2:a2,q3:a3} if only I can get values at a certain index e.g List[0] I can accomplish this, is there any way I can get it? A: Python dictionaries can be constructed using the dict class, given an iterable containing tuples. We can use this in conjunction with the range builtin to produce a collection of tuples as in (every-odd-item, every-even-item), and pass it to dict, such that the values organize themselves into key/value pairs in the final result: dictionary = dict([(List[i], List[i+1]) for i in range(0, len(List), 2)]) A: Using extended slice notation: dictionary = dict(zip(List[0::2], List[1::2])) A: The range-based answer is simpler, but there's another approach possible using the itertools package: from itertools import izip dictionary = dict(izip(*[iter(List)] * 2)) Breaking this down (edit: tested this time): # Create instance of iterator wrapped around List # which will consume items one at a time when called. iter(List) # Put reference to iterator into list and duplicate it so # there are two references to the *same* iterator. [iter(List)] * 2 # Pass each item in the list as a separate argument to the # izip() function. This uses the special * syntax that takes # a sequence and spreads it across a number of positional arguments. izip(* [iter(List)] * 2) # Use regular dict() constructor, same as in the answer by zzzeeek dict(izip(* [iter(List)] * 2)) Edit: much thanks to Chris Lutz' sharp eyes for the double correction. A: d = {} for i in range(0, len(List), 2): d[List[i]] = List[i+1] A: You've mentioned in the comments that you have duplicate entries. We can work with this. Take your favorite method of generating the list of tuples, and expand it into a for loop: from itertools import izip dictionary = {} for k, v in izip(List[::2], List[1::2]): if k not in dictionary: dictionary[k] = set() dictionary[k].add(v) Or we could use collections.defaultdict so we don't have to check if a key is already initialized: from itertools import izip from collections import defaultdict dictionary = defaultdict(set) for k, v in izip(List[::2], List[1::2]): dictionary[k].add(v) We'll end with a dictionary where all the keys are sets, and the sets contain the values. This still may not be appropriate, because sets, like dictionaries, cannot hold duplicates, so if you need a single key to hold two of the same value, you'll need to change it to a tuple or a list. But this should get you started.
How to get value on a certain index, in a python list?
I have a list which looks something like this List = [q1,a1,q2,a2,q3,a3] I need the final code to be something like this dictionary = {q1:a1,q2:a2,q3:a3} if only I can get values at a certain index e.g List[0] I can accomplish this, is there any way I can get it?
[ "Python dictionaries can be constructed using the dict class, given an iterable containing tuples. We can use this in conjunction with the range builtin to produce a collection of tuples as in (every-odd-item, every-even-item), and pass it to dict, such that the values organize themselves into key/value pairs in the final result:\ndictionary = dict([(List[i], List[i+1]) for i in range(0, len(List), 2)])\n\n", "Using extended slice notation:\ndictionary = dict(zip(List[0::2], List[1::2]))\n\n", "The range-based answer is simpler, but there's another approach possible using the itertools package:\nfrom itertools import izip\ndictionary = dict(izip(*[iter(List)] * 2))\n\nBreaking this down (edit: tested this time):\n# Create instance of iterator wrapped around List\n# which will consume items one at a time when called.\niter(List)\n\n# Put reference to iterator into list and duplicate it so\n# there are two references to the *same* iterator.\n[iter(List)] * 2 \n\n# Pass each item in the list as a separate argument to the\n# izip() function. This uses the special * syntax that takes\n# a sequence and spreads it across a number of positional arguments.\nizip(* [iter(List)] * 2)\n\n# Use regular dict() constructor, same as in the answer by zzzeeek\ndict(izip(* [iter(List)] * 2))\n\nEdit: much thanks to Chris Lutz' sharp eyes for the double correction.\n", "d = {}\nfor i in range(0, len(List), 2):\n d[List[i]] = List[i+1]\n\n", "You've mentioned in the comments that you have duplicate entries. We can work with this. Take your favorite method of generating the list of tuples, and expand it into a for loop:\nfrom itertools import izip\n\ndictionary = {}\nfor k, v in izip(List[::2], List[1::2]):\n if k not in dictionary:\n dictionary[k] = set()\n dictionary[k].add(v)\n\nOr we could use collections.defaultdict so we don't have to check if a key is already initialized:\nfrom itertools import izip\nfrom collections import defaultdict\n\ndictionary = defaultdict(set)\nfor k, v in izip(List[::2], List[1::2]):\n dictionary[k].add(v)\n\nWe'll end with a dictionary where all the keys are sets, and the sets contain the values. This still may not be appropriate, because sets, like dictionaries, cannot hold duplicates, so if you need a single key to hold two of the same value, you'll need to change it to a tuple or a list. But this should get you started.\n" ]
[ 11, 11, 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001943824_python.txt
Q: Why isn't count() working the way I expect in my code? class FriendshipManager(models.Manager): def are_friends(self, user1, user2): if self.filter(from_user=user1, to_user=user2).count() > 0: return True if self.filter(from_user=user2, to_user=user1).count() > 0: return True return False and i found count() so i try it, but it runs wrong a=[1,2,3,4] print a.count() or a='ssada' print a.count() why my code run wrong,but the FriendshipManager can run ,thanks Please try to use the code, rather than text, because my English is not very good, thank you A: The issue here is that you've mixed up two methods with the same name. On a sequence in Python, count() works exactly has Dustin describes to "count the number of occurrences of the parameter in the sequence." The code you're referencing however, is from a Django model. There, calling count() on the filter object is an alias for the SQL grouping function COUNT, which sums up the number of matching rows. In essence, the count in your initial example and the count in the two examples after that aren't the same method at all. A: I think you want to use len(a) rather than a.count() if you want to determine the length/size of the list. a.count() actually requires an argument anyway. It counts the number of occurrences of a value. For example: a = [2, 6, 2, 1, 5, 3, 9, 5] print a.count(5) #should display 2 because there are two elements with a value of 5 print a.count(3) #should display 1 because there is only one element with a value of 3 A: len is the correct one for that case. >>> a=[1,2,3,4] >>> print len(a) 4 A: I am not sure if this is a right answer, but, try this instead of the Model Manager code which you have. No big changes as such ofcourse. class FriendshipManager(models.Manager): def are_friends(self, user1, user2): if self.filter(from_user=user1, to_user=user2).count() or self.filter(from_user=user2, to_user=user1).count(): return True return False If count() returns a value other than zero, it will always return True.
Why isn't count() working the way I expect in my code?
class FriendshipManager(models.Manager): def are_friends(self, user1, user2): if self.filter(from_user=user1, to_user=user2).count() > 0: return True if self.filter(from_user=user2, to_user=user1).count() > 0: return True return False and i found count() so i try it, but it runs wrong a=[1,2,3,4] print a.count() or a='ssada' print a.count() why my code run wrong,but the FriendshipManager can run ,thanks Please try to use the code, rather than text, because my English is not very good, thank you
[ "The issue here is that you've mixed up two methods with the same name.\nOn a sequence in Python, count() works exactly has Dustin describes to \"count the number of occurrences of the parameter in the sequence.\"\nThe code you're referencing however, is from a Django model. There, calling count() on the filter object is an alias for the SQL grouping function COUNT, which sums up the number of matching rows.\nIn essence, the count in your initial example and the count in the two examples after that aren't the same method at all.\n", "I think you want to use len(a) rather than a.count() if you want to determine the length/size of the list. a.count() actually requires an argument anyway. It counts the number of occurrences of a value. For example:\na = [2, 6, 2, 1, 5, 3, 9, 5]\nprint a.count(5) #should display 2 because there are two elements with a value of 5\nprint a.count(3) #should display 1 because there is only one element with a value of 3\n\n", "len is the correct one for that case.\n>>> a=[1,2,3,4]\n>>> print len(a)\n4\n\n", "I am not sure if this is a right answer, but, try this instead of the Model Manager code which you have. No big changes as such ofcourse.\nclass FriendshipManager(models.Manager): \n def are_friends(self, user1, user2):\n if self.filter(from_user=user1, to_user=user2).count() or self.filter(from_user=user2, to_user=user1).count():\n return True\n return False\n\nIf count() returns a value other than zero, it will always return True. \n" ]
[ 8, 4, 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001944064_django_python.txt
Q: What is the relationship between __getattr__ and getattr? I know this code is right: class A: def __init__(self): self.a = 'a' def method(self): print "method print" a = A() print getattr(a, 'a', 'default') print getattr(a, 'b', 'default') print getattr(a, 'method', 'default') getattr(a, 'method', 'default')() And this is wrong: # will __getattr__ affect the getattr? class a(object): def __getattr__(self,name): return 'xxx' print getattr(a) This is also wrong: a={'aa':'aaaa'} print getattr(a,'aa') Where should we use __getattr__ and getattr? A: Alex's answer was good, but providing you with a sample code since you asked for it :) class foo: def __init__(self): self.a = "a" def __getattr__(self, attribute): return "You asked for %s, but I'm giving you default" % attribute >>> bar = foo() >>> bar.a 'a' >>> bar.b "You asked for b, but I'm giving you default" >>> getattr(bar, "a") 'a' >>> getattr(bar, "b") "You asked for b, but I'm giving you default" So in short answer is You use __getattr__ to define how to handle attributes that are not found and getattr to get the attributes A: getattr is a built-in function taking (at least) two arguments: the object from which you're getting the attribute, and the string name of the attribute. If the string name is a constant, say 'foo', getattr(obj, 'foo') is exactly the same thing as obj.foo. So, the main use case for the built-in function getattr is when you don't have the attribute name as a constant, but rather as a variable. A second important use case is when you pass it three arguments, rather than just two: in that case, if the attribute is absent from the object, getattr returns the third, "default", argument, rather than raising an exception. __getattr__ is a special method, defined in a class, that gets invoked when some attribute of an instance of that class is requested, and other normal ways to supply that attribute (via the instance's __dict__, slots, properties, and so on) all failed. You can define it, for example, when you want to delegate otherwise-undefined attribute lookups to other objects. So your second example is wrong because the builtin getattr can never be called with a single argument. The third one fails because the dictionary you're trying to "get an attribute" from does not have that attribute -- it has items, which are totally disjoint from attributes of course. A: __getattr__() is a special method function that you can define. When a member lookup fails, this function will be called. getattr() is a function you can call to attempt a member lookup. If the lookup succeeds, you get the member (perhaps a method function object, or perhaps a data attribute object). getattr() can also return a default in the case the lookup fails. If you declare a __getattr__() member function, you can make it succeed sometimes, or you can make it succeed every time. class A(object): def __getattr__(self, name): return "I pretend I have an attribute called '%s'" % name a = A() print a.foo # prints "I pretend I have an attribute called 'foo'" Python also has __getattribute__() which is always called on every lookup. It is very dangerous because it can make it impossible to access members normally. class A(object): def __init__(self, value): self.v = value def __getattribute__(self, name): return "I pretend I have an attribute called '%s'" % name a = A(42) print a.v # prints "I pretend I have an attribute called 'v'" print a.__dict__["v"] # prints "I pretend I have an attribute called '__dict__'" Oops, it is now impossible to access a.v!
What is the relationship between __getattr__ and getattr?
I know this code is right: class A: def __init__(self): self.a = 'a' def method(self): print "method print" a = A() print getattr(a, 'a', 'default') print getattr(a, 'b', 'default') print getattr(a, 'method', 'default') getattr(a, 'method', 'default')() And this is wrong: # will __getattr__ affect the getattr? class a(object): def __getattr__(self,name): return 'xxx' print getattr(a) This is also wrong: a={'aa':'aaaa'} print getattr(a,'aa') Where should we use __getattr__ and getattr?
[ "Alex's answer was good, but providing you with a sample code since you asked for it :)\nclass foo:\n def __init__(self):\n self.a = \"a\"\n def __getattr__(self, attribute):\n return \"You asked for %s, but I'm giving you default\" % attribute\n\n\n>>> bar = foo()\n>>> bar.a\n'a'\n>>> bar.b\n\"You asked for b, but I'm giving you default\"\n>>> getattr(bar, \"a\")\n'a'\n>>> getattr(bar, \"b\")\n\"You asked for b, but I'm giving you default\"\n\nSo in short answer is\nYou use \n__getattr__ to define how to handle attributes that are not found\nand\ngetattr to get the attributes\n", "getattr is a built-in function taking (at least) two arguments: the object from which you're getting the attribute, and the string name of the attribute.\nIf the string name is a constant, say 'foo', getattr(obj, 'foo') is exactly the same thing as obj.foo.\nSo, the main use case for the built-in function getattr is when you don't have the attribute name as a constant, but rather as a variable. A second important use case is when you pass it three arguments, rather than just two: in that case, if the attribute is absent from the object, getattr returns the third, \"default\", argument, rather than raising an exception.\n__getattr__ is a special method, defined in a class, that gets invoked when some attribute of an instance of that class is requested, and other normal ways to supply that attribute (via the instance's __dict__, slots, properties, and so on) all failed. You can define it, for example, when you want to delegate otherwise-undefined attribute lookups to other objects.\nSo your second example is wrong because the builtin getattr can never be called with a single argument.\nThe third one fails because the dictionary you're trying to \"get an attribute\" from does not have that attribute -- it has items, which are totally disjoint from attributes of course.\n", "__getattr__() is a special method function that you can define. When a member lookup fails, this function will be called.\ngetattr() is a function you can call to attempt a member lookup. If the lookup succeeds, you get the member (perhaps a method function object, or perhaps a data attribute object). getattr() can also return a default in the case the lookup fails.\nIf you declare a __getattr__() member function, you can make it succeed sometimes, or you can make it succeed every time.\nclass A(object):\n def __getattr__(self, name):\n return \"I pretend I have an attribute called '%s'\" % name\n\na = A()\n\nprint a.foo # prints \"I pretend I have an attribute called 'foo'\"\n\nPython also has __getattribute__() which is always called on every lookup. It is very dangerous because it can make it impossible to access members normally.\nclass A(object):\n def __init__(self, value):\n self.v = value\n def __getattribute__(self, name):\n return \"I pretend I have an attribute called '%s'\" % name\n\na = A(42)\n\nprint a.v # prints \"I pretend I have an attribute called 'v'\"\nprint a.__dict__[\"v\"] # prints \"I pretend I have an attribute called '__dict__'\"\n\nOops, it is now impossible to access a.v!\n" ]
[ 63, 39, 19 ]
[]
[]
[ "getattr", "python" ]
stackoverflow_0001944625_getattr_python.txt
Q: What's the difference between _b and b in this place class a: def __init__(self): self._b()#why here use _b,not b,What's the difference self._c='cccc'#why here use _c,not c,What's the difference def _b(): print 'bbbb' a.py class a: def __init__(self): self._b()#why here use _b,not b,What's the difference self._c='cccc'#why here use _c,not c,What's the difference def _b(self): print 'bbbb' b.py from a import * b=a() b._b() print b._c it print bbbb bbbb bbbb bbbb cccc Why can print out these, aren't _b and _c private variables. A: Prefixing a variable or function name with an underscore is a convention in Python to indicate that the variable is private. From the docs: Private” instance variables that cannot be accessed except from inside an object, don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice. A: Per pep8 (http://www.python.org/dev/peps/pep-0008/), a single underscore is intended to denote a "generally private" method or attribute. The interpreter itself has no interaction with the single underscore, its more of a convention. The double underscore OTOH has significance within the interpreter. A: Basically, the idea is that in Python convention, there are three levels of encapsulation/hiding. Public attributes and methods: These are meant to be accessed by other classes without restriction. Private attributes and methods (prefixed with an underscore): These are meant to be hidden from the outside world. The underscore serves as something like a warning to say: you shouldn't be touching this method unless you really know what you're doing. Primarily, this is used to differentiate between end users (the lesser mortals) and other developers. There is a third level called mangled. Any attributes/methods that are mangled are basically not to be touched by anyone who is not the author of that code. It is important to the core functioning of the program and should not be touched, because if it is misused, then it may lead to unwanted/unplanned behavior. In your case, the '_b' method is a private method. The author of this code wants to let you know that this is not meant for public use, rather if you are writing a wrapper around this class or something of that nature (basically if you are developer using this class), then you may use that method. Otherwise, it is better that you don't. Also, a single underscore in front of a variable(or method) ties it to that class. So when a._b is called, the interpreter looks for it in the definition of the class a. A: Difference between single and double underscore: class Foo(object): def regular_method(self): print 'ok' def _soft_private(self): print 'ok' def __mangled_private(self): print 'ok' f = Foo() f.regular_method() # prints ok f._soft_private() # print ok f.__mangled_private() # error! no such attribute. BUT: f._Foo__mangled_private() # prints ok So in essence there is no real "privacy" in python, but convention of using single underscore to warn developer using your API that he's doing so at his own risk. A: You'll notice that b isn't defined anywhere. While _b is. Unless you're asking why that naming convention is being used, in which case, you should ask the author of that code. A: The underscore is simply used to denote that the variable is private.
What's the difference between _b and b in this place
class a: def __init__(self): self._b()#why here use _b,not b,What's the difference self._c='cccc'#why here use _c,not c,What's the difference def _b(): print 'bbbb' a.py class a: def __init__(self): self._b()#why here use _b,not b,What's the difference self._c='cccc'#why here use _c,not c,What's the difference def _b(self): print 'bbbb' b.py from a import * b=a() b._b() print b._c it print bbbb bbbb bbbb bbbb cccc Why can print out these, aren't _b and _c private variables.
[ "Prefixing a variable or function name with an underscore is a convention in Python to indicate that the variable is private. From the docs:\n\nPrivate” instance variables that cannot be accessed except from inside an object, don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.\n\n", "Per pep8 (http://www.python.org/dev/peps/pep-0008/), a single underscore is intended to denote a \"generally private\" method or attribute. The interpreter itself has no interaction with the single underscore, its more of a convention. The double underscore OTOH has significance within the interpreter.\n", "Basically, the idea is that in Python convention, there are three levels of encapsulation/hiding.\n\nPublic attributes and methods: These are meant to be accessed by other classes without restriction.\nPrivate attributes and methods (prefixed with an underscore): These are meant to be hidden from the outside world. The underscore serves as something like a warning to say: you shouldn't be touching this method unless you really know what you're doing. Primarily, this is used to differentiate between end users (the lesser mortals) and other developers.\nThere is a third level called mangled. Any attributes/methods that are mangled are basically not to be touched by anyone who is not the author of that code. It is important to the core functioning of the program and should not be touched, because if it is misused, then it may lead to unwanted/unplanned behavior.\n\nIn your case, the '_b' method is a private method. The author of this code wants to let you know that this is not meant for public use, rather if you are writing a wrapper around this class or something of that nature (basically if you are developer using this class), then you may use that method. Otherwise, it is better that you don't.\nAlso, a single underscore in front of a variable(or method) ties it to that class. So when a._b is called, the interpreter looks for it in the definition of the class a.\n", "Difference between single and double underscore:\nclass Foo(object):\n\n def regular_method(self):\n print 'ok'\n\n def _soft_private(self):\n print 'ok'\n\n def __mangled_private(self):\n print 'ok'\n\nf = Foo()\nf.regular_method()\n# prints ok\nf._soft_private()\n# print ok\nf.__mangled_private()\n# error! no such attribute. BUT:\nf._Foo__mangled_private()\n# prints ok\n\nSo in essence there is no real \"privacy\" in python, but convention of using single underscore to warn developer using your API that he's doing so at his own risk.\n", "You'll notice that b isn't defined anywhere. While _b is.\nUnless you're asking why that naming convention is being used, in which case, you should ask the author of that code.\n", "The underscore is simply used to denote that the variable is private.\n" ]
[ 10, 8, 4, 3, 0, 0 ]
[ "The class object a has an attribute _b which is found when asking for self._b. The same class object a has no attribute b.\n_b and b are as different as beehive and zulu. \nYou will get a parameter error when calling self._b because Python will implicitly pass self as the first argument to a bound method. The signature should be:\ndef _b(self):\n print('bbbb')\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0001943863_python.txt
Q: Singleton python generator? Or, pickle a python generator? I am using the following code, with nested generators, to iterate over a text document and return training examples using get_train_minibatch(). I would like to persist (pickle) the generators, so I can get back to the same place in the text document. However, you cannot pickle generators. Is there a simple workaround, so that I can save my position and start back where I stopped? Perhaps I can make get_train_example() a singleton, so I don't have several generators lying around. Then, I could make a global variable in this module that keeps track of how far along get_train_example() is. Do you have a better (cleaner) suggestion, to allow me to persist this generator? [edit: Two more ideas: Can I add a member variable/method to the generator, so I can call generator.tell() and find the file location? Because then, the next time I create the generator, I can ask it to seek to that location. This idea sounds the simplest of everything. Can I create a class and have the file location be a member variable, and then have the generator created within the class and update the file location member variable each time it yields? Because then I can know how far into the file it it. ] Here is the code: def get_train_example(): for l in open(HYPERPARAMETERS["TRAIN_SENTENCES"]): prevwords = [] for w in string.split(l): w = string.strip(w) id = None prevwords.append(wordmap.id(w)) if len(prevwords) >= HYPERPARAMETERS["WINDOW_SIZE"]: yield prevwords[-HYPERPARAMETERS["WINDOW_SIZE"]:] def get_train_minibatch(): minibatch = [] for e in get_train_example(): minibatch.append(e) if len(minibatch) >= HYPERPARAMETERS["MINIBATCH SIZE"]: assert len(minibatch) == HYPERPARAMETERS["MINIBATCH SIZE"] yield minibatch minibatch = [] A: You can create a standard iterator object, it just won't be as convenient as the generator; you need to store the iterator's state on the instace (so that it is pickled), and define a next() function to return the next object: class TrainExampleIterator (object): def __init__(self): # set up internal state here pass def next(self): # return next item here pass The iterator protocol is simple as that, defining the .next() method on an object is all you need to pass it to for loops etc. In Python 3, the iterator protocol uses the __next__ method instead (somewhat more consistent). A: The following code should do more-or-less what you want. The first class defines something that acts like a file but can be pickled. (When you unpickle it, it re-opens the file, and seeks to the location where it was when you pickled it). The second class is an iterator that generates word windows. class PickleableFile(object): def __init__(self, filename, mode='rb'): self.filename = filename self.mode = mode self.file = open(filename, mode) def __getstate__(self): state = dict(filename=self.filename, mode=self.mode, closed=self.file.closed) if not self.file.closed: state['filepos'] = self.file.tell() return state def __setstate__(self, state): self.filename = state['filename'] self.mode = state['mode'] self.file = open(self.filename, self.mode) if state['closed']: self.file.close() else: self.file.seek(state['filepos']) def __getattr__(self, attr): return getattr(self.file, attr) class WordWindowReader: def __init__(self, filenames, window_size): self.filenames = filenames self.window_size = window_size self.filenum = 0 self.stream = None self.filepos = 0 self.prevwords = [] self.current_line = [] def __iter__(self): return self def next(self): # Read through files until we have a non-empty current line. while not self.current_line: if self.stream is None: if self.filenum >= len(self.filenames): raise StopIteration else: self.stream = PickleableFile(self.filenames[self.filenum]) self.stream.seek(self.filepos) self.prevwords = [] line = self.stream.readline() self.filepos = self.stream.tell() if line == '': # End of file. self.stream = None self.filenum += 1 self.filepos = 0 else: # Reverse line so we can pop off words. self.current_line = line.split()[::-1] # Get the first word of the current line, and add it to # prevwords. Truncate prevwords when necessary. word = self.current_line.pop() self.prevwords.append(word) if len(self.prevwords) > self.window_size: self.prevwords = self.prevwords[-self.window_size:] # If we have enough words, then return a word window; # otherwise, go on to the next word. if len(self.prevwords) == self.window_size: return self.prevwords else: return self.next() A: This may not be an option for you, but Stackless Python (http://stackless.com) does allow you to pickle things like functions and generators, under certain conditions. This will work: In foo.py: def foo(): with open('foo.txt') as fi: buffer = fi.read() del fi for line in buffer.split('\n'): yield line In foo.txt: line1 line2 line3 line4 line5 In the interpreter: Python 2.6 Stackless 3.1b3 060516 (python-2.6:66737:66749M, Oct 2 2008, 18:31:31) IPython 0.9.1 -- An enhanced Interactive Python. In [1]: import foo In [2]: g = foo.foo() In [3]: g.next() Out[3]: 'line1' In [4]: import pickle In [5]: p = pickle.dumps(g) In [6]: g2 = pickle.loads(p) In [7]: g2.next() Out[7]: 'line2' Some things to note: you must buffer the contents of the file, and delete the file object. This means that the contents of the file will be duplicated in the pickle. A: You might also consider using NLTK's corpus readers: http://nltk.googlecode.com/svn/trunk/doc/api/nltk.corpus.reader-module.html http://nltk.googlecode.com/svn/trunk/doc/howto/corpus.html -Edward A: Convert the generator to a class in which the generator code is the __iter__ method Add __getstate__ and __setstate__ methods to the class, to handling pickling. Remember that you can’t pickle file objects. So __setstate__ will have to re-open files, as necessary. I describe this method in more depth, with sample code, here.
Singleton python generator? Or, pickle a python generator?
I am using the following code, with nested generators, to iterate over a text document and return training examples using get_train_minibatch(). I would like to persist (pickle) the generators, so I can get back to the same place in the text document. However, you cannot pickle generators. Is there a simple workaround, so that I can save my position and start back where I stopped? Perhaps I can make get_train_example() a singleton, so I don't have several generators lying around. Then, I could make a global variable in this module that keeps track of how far along get_train_example() is. Do you have a better (cleaner) suggestion, to allow me to persist this generator? [edit: Two more ideas: Can I add a member variable/method to the generator, so I can call generator.tell() and find the file location? Because then, the next time I create the generator, I can ask it to seek to that location. This idea sounds the simplest of everything. Can I create a class and have the file location be a member variable, and then have the generator created within the class and update the file location member variable each time it yields? Because then I can know how far into the file it it. ] Here is the code: def get_train_example(): for l in open(HYPERPARAMETERS["TRAIN_SENTENCES"]): prevwords = [] for w in string.split(l): w = string.strip(w) id = None prevwords.append(wordmap.id(w)) if len(prevwords) >= HYPERPARAMETERS["WINDOW_SIZE"]: yield prevwords[-HYPERPARAMETERS["WINDOW_SIZE"]:] def get_train_minibatch(): minibatch = [] for e in get_train_example(): minibatch.append(e) if len(minibatch) >= HYPERPARAMETERS["MINIBATCH SIZE"]: assert len(minibatch) == HYPERPARAMETERS["MINIBATCH SIZE"] yield minibatch minibatch = []
[ "You can create a standard iterator object, it just won't be as convenient as the generator; you need to store the iterator's state on the instace (so that it is pickled), and define a next() function to return the next object:\nclass TrainExampleIterator (object):\n def __init__(self):\n # set up internal state here\n pass\n def next(self):\n # return next item here\n pass\n\nThe iterator protocol is simple as that, defining the .next() method on an object is all you need to pass it to for loops etc.\nIn Python 3, the iterator protocol uses the __next__ method instead (somewhat more consistent).\n", "The following code should do more-or-less what you want. The first class defines something that acts like a file but can be pickled. (When you unpickle it, it re-opens the file, and seeks to the location where it was when you pickled it). The second class is an iterator that generates word windows.\nclass PickleableFile(object):\n def __init__(self, filename, mode='rb'):\n self.filename = filename\n self.mode = mode\n self.file = open(filename, mode)\n def __getstate__(self):\n state = dict(filename=self.filename, mode=self.mode,\n closed=self.file.closed)\n if not self.file.closed:\n state['filepos'] = self.file.tell()\n return state\n def __setstate__(self, state):\n self.filename = state['filename']\n self.mode = state['mode']\n self.file = open(self.filename, self.mode)\n if state['closed']: self.file.close()\n else: self.file.seek(state['filepos'])\n def __getattr__(self, attr):\n return getattr(self.file, attr)\n\nclass WordWindowReader:\n def __init__(self, filenames, window_size):\n self.filenames = filenames\n self.window_size = window_size\n self.filenum = 0\n self.stream = None\n self.filepos = 0\n self.prevwords = []\n self.current_line = []\n\n def __iter__(self):\n return self\n\n def next(self):\n # Read through files until we have a non-empty current line.\n while not self.current_line:\n if self.stream is None:\n if self.filenum >= len(self.filenames):\n raise StopIteration\n else:\n self.stream = PickleableFile(self.filenames[self.filenum])\n self.stream.seek(self.filepos)\n self.prevwords = []\n line = self.stream.readline()\n self.filepos = self.stream.tell()\n if line == '':\n # End of file.\n self.stream = None\n self.filenum += 1\n self.filepos = 0\n else:\n # Reverse line so we can pop off words.\n self.current_line = line.split()[::-1]\n\n # Get the first word of the current line, and add it to\n # prevwords. Truncate prevwords when necessary.\n word = self.current_line.pop()\n self.prevwords.append(word)\n if len(self.prevwords) > self.window_size:\n self.prevwords = self.prevwords[-self.window_size:]\n\n # If we have enough words, then return a word window;\n # otherwise, go on to the next word.\n if len(self.prevwords) == self.window_size:\n return self.prevwords\n else:\n return self.next()\n\n", "This may not be an option for you, but Stackless Python (http://stackless.com) does allow you to pickle things like functions and generators, under certain conditions. This will work:\nIn foo.py:\ndef foo():\n with open('foo.txt') as fi:\n buffer = fi.read()\n del fi\n for line in buffer.split('\\n'):\n yield line\n\nIn foo.txt:\nline1\nline2\nline3\nline4\nline5\n\nIn the interpreter:\nPython 2.6 Stackless 3.1b3 060516 (python-2.6:66737:66749M, Oct 2 2008, 18:31:31) \nIPython 0.9.1 -- An enhanced Interactive Python.\n\nIn [1]: import foo\n\nIn [2]: g = foo.foo()\n\nIn [3]: g.next()\nOut[3]: 'line1'\n\nIn [4]: import pickle\n\nIn [5]: p = pickle.dumps(g)\n\nIn [6]: g2 = pickle.loads(p)\n\nIn [7]: g2.next()\nOut[7]: 'line2'\n\nSome things to note: you must buffer the contents of the file, and delete the file object. This means that the contents of the file will be duplicated in the pickle.\n", "You might also consider using NLTK's corpus readers:\n\nhttp://nltk.googlecode.com/svn/trunk/doc/api/nltk.corpus.reader-module.html \nhttp://nltk.googlecode.com/svn/trunk/doc/howto/corpus.html\n\n-Edward\n", "\nConvert the generator to a class in which the generator code is the __iter__ method\nAdd __getstate__ and __setstate__ methods to the class, to handling pickling. Remember that you can’t pickle file objects. So __setstate__ will have to re-open files, as necessary.\n\nI describe this method in more depth, with sample code, here.\n" ]
[ 2, 2, 0, 0, 0 ]
[ "You can try create callable object: \nclass TrainExampleGenerator:\n\n def __call__(self):\n for l in open(HYPERPARAMETERS[\"TRAIN_SENTENCES\"]):\n prevwords = []\n for w in string.split(l):\n w = string.strip(w)\n id = None\n prevwords.append(wordmap.id(w))\n if len(prevwords) >= HYPERPARAMETERS[\"WINDOW_SIZE\"]:\n yield prevwords[-HYPERPARAMETERS[\"WINDOW_SIZE\"]:]\n\nget_train_example = TrainExampleGenerator()\n\nNow you can turn all state that needs to be saved into object fields and expose them to pickle. This is a basic idea and I hope this helps, but I haven't tried this myself yet.\nUPDATE:\nUnfortunately, I failed to deliver my idea. Provided example is not complete solution. You see, TrainExampleGenerator have no state. You must design this state and make it available for pickling. And __call__ method should use and modify that state so that to return generator which started from the position determined by object's state. Obviously, generator itself won't be pickle-able. But TrainExampleGenerator will be possible to pickle and you'll be able to recreate generator with it as if generator itself were pickled.\n" ]
[ -1 ]
[ "generator", "persistent", "pickle", "python", "singleton" ]
stackoverflow_0001939015_generator_persistent_pickle_python_singleton.txt
Q: Having trouble with Python's telnetlib module I have a basic chat server which I can easily connect to with telnet. I simply enter the host and port and, without any further authentication, can begin entering commands that the server can interpret. In an effort to simulate user traffic, I would like to create a script that will open telnet, connect to the server, and immediately begin sending commands to the server. I initially attempted to do this with batch scripts, but after encountering too many road blocks I have decided to use Python's telnetlib module. This is what the script looks like now import telnetlib myTel = telnetlib.Telnet('XXX.XXX.XXX.XXX', XXXX) myTel.write('login') myTel.write('move room') myTel.write('say message') myTel.write('exit') myTel.write('logout') Its really that simple and the script runs with no errors. However, if I've already manually logged into the server on another telnet session, I fail to see the script entering the main room or sending a chat message which leads me to believe that something is going wrong. If I manually start two telnet sessions I can easily send and receive messages between the sessions, so I would think that a manual telnet session should be receiving the messages from the session started by the script. Any ideas? A: Perhaps adding a newline would help? myTel.write('login\n') I'd also recommend using some network sniffing tool (i.e. Wireshark) to verify that you're really sending what you intended. A: In your code, you write to the server, but in order to receive data, you'll eventually have to one of the read methods of the library. To see an example implementation of a client with a 'reading thread', see this blog post: http://hahong.org/blog/posts/261. fn. Also try: myTel.write('login\n') .. with newlines. A: I would use read_until to check that the server is ready to receive the command here is a sample using telnet to talk to a cisco switch: from telnetlib import Telnet PASSWD = "mypass" t = Telnet(switch) t.read_until("Password: ", 2) t.write(PASSWD + "\r\n") Here I wait for a password prompt before sending the password.
Having trouble with Python's telnetlib module
I have a basic chat server which I can easily connect to with telnet. I simply enter the host and port and, without any further authentication, can begin entering commands that the server can interpret. In an effort to simulate user traffic, I would like to create a script that will open telnet, connect to the server, and immediately begin sending commands to the server. I initially attempted to do this with batch scripts, but after encountering too many road blocks I have decided to use Python's telnetlib module. This is what the script looks like now import telnetlib myTel = telnetlib.Telnet('XXX.XXX.XXX.XXX', XXXX) myTel.write('login') myTel.write('move room') myTel.write('say message') myTel.write('exit') myTel.write('logout') Its really that simple and the script runs with no errors. However, if I've already manually logged into the server on another telnet session, I fail to see the script entering the main room or sending a chat message which leads me to believe that something is going wrong. If I manually start two telnet sessions I can easily send and receive messages between the sessions, so I would think that a manual telnet session should be receiving the messages from the session started by the script. Any ideas?
[ "Perhaps adding a newline would help?\nmyTel.write('login\\n')\n\nI'd also recommend using some network sniffing tool (i.e. Wireshark) to verify that you're really sending what you intended.\n", "In your code, you write to the server, but in order to receive data, you'll eventually have to one of the read methods of the library. To see an example implementation of a client with a 'reading thread', see this blog post: http://hahong.org/blog/posts/261.\nfn. Also try: \nmyTel.write('login\\n')\n\n.. with newlines.\n", "I would use read_until to check that the server is ready to receive the command here is a sample using telnet to talk to a cisco switch:\nfrom telnetlib import Telnet\nPASSWD = \"mypass\"\n\nt = Telnet(switch)\nt.read_until(\"Password: \", 2)\nt.write(PASSWD + \"\\r\\n\")\n\nHere I wait for a password prompt before sending the password.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "python", "telnet" ]
stackoverflow_0001945084_python_telnet.txt
Q: Format for DateTimeField Possible Duplicate: Converting string into datetime In Django I get this error "Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." when I try to assign a string "22-DEC-2009" to a DateTimeField in a model. How is it possible to make DateTimeField accept a date string in format "22-DEC-2009"? A: You can pass the input formats as input_formats argument to DateTimeField, so you can do this # you can keep a list of formats yourself, or copy from django 1.2 version e.g. # my_formats = fields.DEFAULT_DATETIME_INPUT_FORMATS + ['%d-%b-%Y'] # for latest django use this from django.utils.formats import get_format my_formats = get_format('DATETIME_INPUT_FORMATS') field = DateTimeField(input_formats=my_formats,...) If instead you directly want to assign a date-str to models.DateTimeField best way is to just convert it to datetime before hand e.g. mymodel.date_of_birth = datetime.datetime.strptime("22-DEC-2009", "%d-%b-%Y")
Format for DateTimeField
Possible Duplicate: Converting string into datetime In Django I get this error "Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." when I try to assign a string "22-DEC-2009" to a DateTimeField in a model. How is it possible to make DateTimeField accept a date string in format "22-DEC-2009"?
[ "You can pass the input formats as input_formats argument to DateTimeField, so you can do this\n# you can keep a list of formats yourself, or copy from django 1.2 version e.g.\n# my_formats = fields.DEFAULT_DATETIME_INPUT_FORMATS + ['%d-%b-%Y']\n# for latest django use this\nfrom django.utils.formats import get_format\nmy_formats = get_format('DATETIME_INPUT_FORMATS')\nfield = DateTimeField(input_formats=my_formats,...)\n\nIf instead you directly want to assign a date-str to models.DateTimeField best way is to just convert it to datetime before hand e.g.\nmymodel.date_of_birth = datetime.datetime.strptime(\"22-DEC-2009\", \"%d-%b-%Y\")\n\n" ]
[ 9 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001945239_django_python.txt
Q: Why does the following code always output 16? def makeActions(): acts=[] for i in range(5): print len(acts) acts.append(lambda x: i ** x) print acts[i] return acts acts=makeActions() for i in range(5): print acts[i](2) Output: 16 16 16 16 16 Expected output: 0 1 4 9 16 A: Because the i in the lambda is probably not what you expect. To verify this, change the code: acts.append(lambda x: (i, i ** x)) Now the print tells you the value of i: (4, 16) (4, 16) (4, 16) (4, 16) (4, 16) This means that the lambda doesn't copy the value of i but keeps a reference to the variable, so all lambdas see the same value. To fix this, copy i: acts.append(lambda x, i=i: (i, i ** x)) The little i=i creates a local copy of i inside the lambda. [EDIT] Now why is this? In the versions of Python before 2.1, local functions (i.e. functions defined inside of other functions) couldn't see the variables in the same scope. def makeActions(): acts=[] for i in range(5): print len(acts) def f(x): # <-- Define local function return i ** x acts.append(f) print acts[i] return acts then you'd get an error that i isn't defined. lambda could see the enclosing scope at the cost of a somewhat wierd syntax. This behavior has been fixed in one of the recent versions of Python (2.5, IIRC). With these old versions of Python, you'd have to write: def f(x, i=i): # <-- Must copy i return i ** x Since the fix (see PEP 3104), f() can see variables in the same scope, so lambda isn't necessary anymore. A: Because all lambda functions you create are bound to i, which becomes 4 at the end of loop, and as we all well know 4*4 = 16 to avoid that create your functions using nested function(closure) e.g. def makePowerFunc(base): def powerFunc(x): return base**x return powerFunc def makeActions(): acts=[] for i in range(5): acts.append(makePowerFunc(i)) return acts acts=makeActions() for i in range(5): print acts[i](2) output: 0 1 4 9 16 There are other ways to solve it, but it is better to have a named nested function instead of lambda, and you can do many more things with such closures A: It's counterintuitive or at least less common syntax. I guess you meant: acts.append(lambda x, i = i: i ** x) which will output: 0 1 4 9 16 fn. in your version, acts.append(lambda x, i: i ** x) the lambda functions were created, but they all referenced the local i from the loop, which stopped at i = 4, so all your lambdas were saying: lambda x: 4 ** x, hence for i in range(5): print acts[i](2) would print all 16s. ffn. a blog post about broken lambda: http://math.andrej.com/2009/04/09/pythons-lambda-is-broken/ A: This phenomena is called lambda binding see What is "lambda binding" in Python?
Why does the following code always output 16?
def makeActions(): acts=[] for i in range(5): print len(acts) acts.append(lambda x: i ** x) print acts[i] return acts acts=makeActions() for i in range(5): print acts[i](2) Output: 16 16 16 16 16 Expected output: 0 1 4 9 16
[ "Because the i in the lambda is probably not what you expect. To verify this, change the code:\nacts.append(lambda x: (i, i ** x))\n\nNow the print tells you the value of i:\n(4, 16)\n(4, 16)\n(4, 16)\n(4, 16)\n(4, 16)\n\nThis means that the lambda doesn't copy the value of i but keeps a reference to the variable, so all lambdas see the same value. To fix this, copy i:\nacts.append(lambda x, i=i: (i, i ** x))\n\nThe little i=i creates a local copy of i inside the lambda.\n[EDIT] Now why is this? In the versions of Python before 2.1, local functions (i.e. functions defined inside of other functions) couldn't see the variables in the same scope.\ndef makeActions():\n acts=[]\n for i in range(5):\n print len(acts)\n def f(x): # <-- Define local function\n return i ** x\n acts.append(f)\n print acts[i]\n return acts\n\nthen you'd get an error that i isn't defined. lambda could see the enclosing scope at the cost of a somewhat wierd syntax.\nThis behavior has been fixed in one of the recent versions of Python (2.5, IIRC). With these old versions of Python, you'd have to write:\n def f(x, i=i): # <-- Must copy i\n return i ** x\n\nSince the fix (see PEP 3104), f() can see variables in the same scope, so lambda isn't necessary anymore.\n", "Because all lambda functions you create are bound to i, which becomes 4 at the end of loop, and as we all well know 4*4 = 16\nto avoid that create your functions using nested function(closure) e.g.\ndef makePowerFunc(base):\n def powerFunc(x):\n return base**x\n return powerFunc\n\ndef makeActions():\n acts=[]\n for i in range(5):\n acts.append(makePowerFunc(i))\n\n return acts\nacts=makeActions()\nfor i in range(5):\nprint acts[i](2)\n\noutput:\n0\n1\n4\n9\n16\n\nThere are other ways to solve it, but it is better to have a named nested function instead of lambda, and you can do many more things with such closures\n", "It's counterintuitive or at least less common syntax. I guess you meant:\nacts.append(lambda x, i = i: i ** x)\n\nwhich will output:\n0\n1\n4\n9\n16\n\n\nfn. in your version,\nacts.append(lambda x, i: i ** x)\n\nthe lambda functions were created, but they all referenced the local i from the loop, which stopped at i = 4, so all your lambdas were saying: lambda x: 4 ** x, hence\nfor i in range(5):\n print acts[i](2)\n\nwould print all 16s.\n\nffn. a blog post about broken lambda: http://math.andrej.com/2009/04/09/pythons-lambda-is-broken/\n", "This phenomena is called lambda binding see What is \"lambda binding\" in Python?\n" ]
[ 23, 6, 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001945270_python.txt
Q: How can I copy a remote image over HTTP to gtk.gdk.pixbuf by Python? this is first post here and I am a noob programmer. This may be a stupid question. I'd like to create a personal Twitter notifier on GNOE Desktop. And I've decided to use pynotify and Tweepy. Now I just want to make pynotify show Twitter user's icon, and there seems to be 2 ways using pynotify; setting URI to local image file, or using pixbuf API. I suppose downloading the icon and setting URI to the local icon by urllib is easier though don't want to make local cache file. Is it possible to pass directly a remote image to pixbuf? A: did you mean something like this?
How can I copy a remote image over HTTP to gtk.gdk.pixbuf by Python?
this is first post here and I am a noob programmer. This may be a stupid question. I'd like to create a personal Twitter notifier on GNOE Desktop. And I've decided to use pynotify and Tweepy. Now I just want to make pynotify show Twitter user's icon, and there seems to be 2 ways using pynotify; setting URI to local image file, or using pixbuf API. I suppose downloading the icon and setting URI to the local icon by urllib is easier though don't want to make local cache file. Is it possible to pass directly a remote image to pixbuf?
[ "did you mean something like this?\n" ]
[ 2 ]
[]
[]
[ "gtk", "pynotify", "python" ]
stackoverflow_0001945331_gtk_pynotify_python.txt
Q: MYSQLDB python module I am using MySQLdb module of python on FC11 machine. Here, i have an issue. I have the following implementation for one of our requirement: connect to mysqldb and get DB handle,open a cursor, execute a delete statement,commit and then close the cursor. Again using the DB handle above, iam performing a "select" statement one some different table using the cursor way as described above. I was able to delete few records using Step1, but step2 select is not working. It simply gives no records for step2 though there are some records available under DB. But, when i comment step1 and execute step2, i could see that step2 works fine. Why this is so? Though there are records, why the above sequence is failing to do so? Any ideas would be appreciated. Thanks! A: With no code, I can only make a guess: try not closing the cursor until you are done with that connection. I think that calling cursor() again after calling cursor.close() will just give you a reference to the same cursor, which can no longer be used for queries. I am not 100% sure if that is the intended behavior, but I haven't seen any MySQLDB examples of cursors being opened and closed within the same connection. A: It sounds as though the first cursor is being returned back to the second step. A: did u try records = cur.fetchall() ?
MYSQLDB python module
I am using MySQLdb module of python on FC11 machine. Here, i have an issue. I have the following implementation for one of our requirement: connect to mysqldb and get DB handle,open a cursor, execute a delete statement,commit and then close the cursor. Again using the DB handle above, iam performing a "select" statement one some different table using the cursor way as described above. I was able to delete few records using Step1, but step2 select is not working. It simply gives no records for step2 though there are some records available under DB. But, when i comment step1 and execute step2, i could see that step2 works fine. Why this is so? Though there are records, why the above sequence is failing to do so? Any ideas would be appreciated. Thanks!
[ "With no code, I can only make a guess: try not closing the cursor until you are done with that connection. I think that calling cursor() again after calling cursor.close() will just give you a reference to the same cursor, which can no longer be used for queries.\nI am not 100% sure if that is the intended behavior, but I haven't seen any MySQLDB examples of cursors being opened and closed within the same connection.\n", "It sounds as though the first cursor is being returned back to the second step.\n", "did u try \nrecords = cur.fetchall()\n\n?\n" ]
[ 0, 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001922623_mysql_python.txt
Q: python add a new div every 3rd iteration I have a product list that put 3 products on a row and clears the row and adds another 3, this works fine everywhere but IE6, i know that adding <div> around each group of 3 products will solve this is the template file at the moment {% for product in category.products.all %} <div class="{% cycle 'clear' '' '' %}"> <a href="{% url shop.views.product category.slug product.slug %}"><img src="{{MEDIA_URL}}{{product.mini_thumbnail}}" alt="{{product.name}}" class="thumbnail"/></a> <div class="prod-details"> <h3><a href="{% url shop.views.product category.slug product.slug %}">{{product.get_product_name}}</a></h3> <h4 class="strap">{{product.get_product_detail}}</h4> <p>{{ product.strap }}</p> <ul> <li class="price">&pound;{{product.price}}</li> <li class="quantity"> <select name="quantity_{{product.id}}"> <option label="1" value="1">1</option> <option label="2" value="2">2</option> <option label="3" value="3">3</option> <option label="4" value="4">4</option> <option label="5" value="5">5</option> <option label="6" value="6">6</option> <option label="7" value="7">7</option> <option label="8" value="8">8</option> <option label="9" value="9">9</option> </select> </li> <li><a href="{% url shop.views.product category.slug product.slug %}">Details &gt;</a></li> <li class="right"><input type="submit" name="add_to_basket_{{product.id}}" value="Add to Basket &gt;"/></li> </ul> </div> </div> {% endfor %} A: codeape's solution only works if you are using a very recent SVN checkout of Django trunk. If you're using version 1.1 or below, that syntax is not supported. Instead, you can use the divisibleby filter: {% if forloop.counter|divisibleby:3 %}<div>{% endif %} A: Use forloop.counter and a modulo operator inside the loop: {% for ... %} {% if forloop.counter|divisibleby:3 %}<div>{% endif %} ... {% if forloop.counter|divisibleby:3 %}</div>{% endif %} {% endfor %} See http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for EDIT: Fixed the code example.
python add a new div every 3rd iteration
I have a product list that put 3 products on a row and clears the row and adds another 3, this works fine everywhere but IE6, i know that adding <div> around each group of 3 products will solve this is the template file at the moment {% for product in category.products.all %} <div class="{% cycle 'clear' '' '' %}"> <a href="{% url shop.views.product category.slug product.slug %}"><img src="{{MEDIA_URL}}{{product.mini_thumbnail}}" alt="{{product.name}}" class="thumbnail"/></a> <div class="prod-details"> <h3><a href="{% url shop.views.product category.slug product.slug %}">{{product.get_product_name}}</a></h3> <h4 class="strap">{{product.get_product_detail}}</h4> <p>{{ product.strap }}</p> <ul> <li class="price">&pound;{{product.price}}</li> <li class="quantity"> <select name="quantity_{{product.id}}"> <option label="1" value="1">1</option> <option label="2" value="2">2</option> <option label="3" value="3">3</option> <option label="4" value="4">4</option> <option label="5" value="5">5</option> <option label="6" value="6">6</option> <option label="7" value="7">7</option> <option label="8" value="8">8</option> <option label="9" value="9">9</option> </select> </li> <li><a href="{% url shop.views.product category.slug product.slug %}">Details &gt;</a></li> <li class="right"><input type="submit" name="add_to_basket_{{product.id}}" value="Add to Basket &gt;"/></li> </ul> </div> </div> {% endfor %}
[ "codeape's solution only works if you are using a very recent SVN checkout of Django trunk. If you're using version 1.1 or below, that syntax is not supported.\nInstead, you can use the divisibleby filter:\n{% if forloop.counter|divisibleby:3 %}<div>{% endif %}\n\n", "Use forloop.counter and a modulo operator inside the loop:\n{% for ... %}\n {% if forloop.counter|divisibleby:3 %}<div>{% endif %}\n ...\n {% if forloop.counter|divisibleby:3 %}</div>{% endif %}\n{% endfor %}\n\nSee http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for\nEDIT:\nFixed the code example.\n" ]
[ 40, 10 ]
[]
[]
[ "django_templates", "python" ]
stackoverflow_0001945379_django_templates_python.txt
Q: Python Format string "}" fill Python 2.6 defines str.format(…), which, from Python 3.0, is preferred to the old % style of string formatting. Looking at the "mini-language", however, it seems that it is impossible to use the } character as a fill character. This seems like a strange omission to me. Is it possible to somehow escape that character and use it as a fill character? I know I could fill with some unique-to-the-string character and then use str.replace, or any number of other similar tricks to achieve the same result, but that feels like a hack to me… Edit: What I'm after is something like >>> "The word is {0:}<10}".format("spam") 'The word is spam}}}}}}' A: You could always specify it as a separate parameter like so: >>> "The word is {0:{1}<10}".format("spam", "}") 'The word is spam}}}}}}' See, it gets passed in and used in place of {1}.
Python Format string "}" fill
Python 2.6 defines str.format(…), which, from Python 3.0, is preferred to the old % style of string formatting. Looking at the "mini-language", however, it seems that it is impossible to use the } character as a fill character. This seems like a strange omission to me. Is it possible to somehow escape that character and use it as a fill character? I know I could fill with some unique-to-the-string character and then use str.replace, or any number of other similar tricks to achieve the same result, but that feels like a hack to me… Edit: What I'm after is something like >>> "The word is {0:}<10}".format("spam") 'The word is spam}}}}}}'
[ "You could always specify it as a separate parameter like so:\n>>> \"The word is {0:{1}<10}\".format(\"spam\", \"}\")\n'The word is spam}}}}}}'\n\nSee, it gets passed in and used in place of {1}.\n" ]
[ 8 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0001945230_python_string_formatting.txt
Q: Python: Fast extraction of intersections among all possible 2-combinations in a large number of lists I have a dataset of ca. 9K lists of variable length (1 to 100K elements). I need to calculate the length of the intersection of all possible 2-list combinations in this dataset. Note that elements in each list are unique so they can be stored as sets in python. What is the most efficient way to perform this in python? Edit I forgot to specify that I need to have the ability to match the intersection values to the corresponding pair of lists. Thanks everybody for the prompt response and apologies for the confusion! A: If your sets are stored in s, for example: s = [set([1, 2]), set([1, 3]), set([1, 2, 3]), set([2, 4])] Then you can use itertools.combinations to take them two by two, and calculate the intersection (note that, as Alex pointed out, combinations is only available since version 2.6). Here with a list comrehension (just for the sake of the example): from itertools import combinations [ i[0] & i[1] for i in combinations(s,2) ] Or, in a loop, which is probably what you need: for i in combinations(s, 2): inter = i[0] & i[1] # processes the intersection set result "inter" So, to have the length of each one of them, that "processing" would be: l = len(inter) This would be quite efficient, since it's using iterators to compute every combinations, and does not prepare all of them in advance. Edit: Note that with this method, each set in the list "s" can actually be something else that returns a set, like a generator. The list itself could simply be a generator if you are short on memory. It could be much slower though, depending on how you generate these elements, but you wouldn't need to have the whole list of sets in memory at the same time (not that it should be a problem in your case). For example, if each set is made from a function gen: def gen(parameter): while more_sets(): # ... some code to generate the next set 'x' yield x with open("results", "wt") as f_results: for i in combinations(gen("data"), 2): inter = i[0] & i[1] f_results.write("%d\n" % len(inter)) Edit 2: How to collect indices (following redrat's comment). Besides the quick solution I answered in comment, a more efficient way to collect the set indices would be to have a list of (index, set) instead of a list of set. Example with new format: s = [(0, set([1, 2])), (1, set([1, 3])), (2, set([1, 2, 3]))] If you are building this list to calculate the combinations anyway, it should be simple to adapt to your new requirements. The main loop becomes: with open("results", "wt") as f_results: for i in combinations(s, 2): inter = i[0][1] & i[1][1] f_results.write("length of %d & %d: %d\n" % (i[0][0],i[1][0],len(inter)) In the loop, i[0] and i[1] would be a tuple (index, set), so i[0][1] is the first set, i[0][0] its index. A: As you need to produce a (N by N/2) matrix of results, i.e., O(N squared) outputs, no approach can be less than O(N squared) -- in any language, of course. (N is "about 9K" in your question). So, I see nothing intrinsically faster than (a) making the N sets you need, and (b) iterating over them to produce the output -- i.e., the simplest approach. IOW: def lotsofintersections(manylists): manysets = [set(x) for x in manylists] moresets = list(manysets) for s in reversed(manysets): moresets.pop() for z in moresets: yield s & z This code's already trying to add some minor optimization (e.g. by avoiding slicing or popping off the front of lists, which might add other O(N squared) factors). If you have many cores and/or nodes available and are looking for parallel algorithms, it's a different case of course -- if that's your case, can you mention the kind of cluster you have, its size, how nodes and cores can best communicate, and so forth? Edit: as the OP has casually mentioned in a comment (!) that they actually need the numbers of the sets being intersected (really, why omit such crucial parts of the specs?! at least edit the question to clarify them...), this would only require changing this to: L = len(manysets) for i, s in enumerate(reversed(manysets)): moresets.pop() for j, z in enumerate(moresets): yield L - i, j + 1, s & z (if you need to "count from 1" for the progressive identifiers -- otherwise obvious change). But if that's part of the specs you might as well use simpler code -- forget moresets, and: L = len(manysets) for i xrange(L): s = manysets[i] for j in range(i+1, L): yield i, j, s & manysets[z] this time assuming you want to "count from 0" instead, just for variety;-) A: Try this: _lists = [[1, 2, 3, 7], [1, 3], [1, 2, 3], [1, 3, 4, 7]] _sets = map( set, _lists ) _intersection = reduce( set.intersection, _sets ) And to obtain the indexes: _idxs = [ map(_i.index, _intersection ) for _i in _lists ] Cheers, JosΓ© MarΓ­a GarcΓ­a PS: Sorry I misunderstood the question
Python: Fast extraction of intersections among all possible 2-combinations in a large number of lists
I have a dataset of ca. 9K lists of variable length (1 to 100K elements). I need to calculate the length of the intersection of all possible 2-list combinations in this dataset. Note that elements in each list are unique so they can be stored as sets in python. What is the most efficient way to perform this in python? Edit I forgot to specify that I need to have the ability to match the intersection values to the corresponding pair of lists. Thanks everybody for the prompt response and apologies for the confusion!
[ "If your sets are stored in s, for example:\ns = [set([1, 2]), set([1, 3]), set([1, 2, 3]), set([2, 4])]\n\nThen you can use itertools.combinations to take them two by two, and calculate the intersection (note that, as Alex pointed out, combinations is only available since version 2.6). Here with a list comrehension (just for the sake of the example):\nfrom itertools import combinations\n[ i[0] & i[1] for i in combinations(s,2) ]\n\nOr, in a loop, which is probably what you need:\nfor i in combinations(s, 2):\n inter = i[0] & i[1]\n # processes the intersection set result \"inter\"\n\nSo, to have the length of each one of them, that \"processing\" would be:\n l = len(inter)\n\nThis would be quite efficient, since it's using iterators to compute every combinations, and does not prepare all of them in advance.\n\nEdit: Note that with this method, each set in the list \"s\" can actually be something else that returns a set, like a generator. The list itself could simply be a generator if you are short on memory. It could be much slower though, depending on how you generate these elements, but you wouldn't need to have the whole list of sets in memory at the same time (not that it should be a problem in your case).\nFor example, if each set is made from a function gen:\ndef gen(parameter):\n while more_sets():\n # ... some code to generate the next set 'x'\n yield x\n\nwith open(\"results\", \"wt\") as f_results:\n for i in combinations(gen(\"data\"), 2):\n inter = i[0] & i[1]\n f_results.write(\"%d\\n\" % len(inter))\n\n\nEdit 2: How to collect indices (following redrat's comment).\nBesides the quick solution I answered in comment, a more efficient way to collect the set indices would be to have a list of (index, set) instead of a list of set.\nExample with new format:\ns = [(0, set([1, 2])), (1, set([1, 3])), (2, set([1, 2, 3]))]\n\nIf you are building this list to calculate the combinations anyway, it should be simple to adapt to your new requirements. The main loop becomes:\nwith open(\"results\", \"wt\") as f_results:\n for i in combinations(s, 2):\n inter = i[0][1] & i[1][1]\n f_results.write(\"length of %d & %d: %d\\n\" % (i[0][0],i[1][0],len(inter))\n\nIn the loop, i[0] and i[1] would be a tuple (index, set), so i[0][1] is the first set, i[0][0] its index.\n", "As you need to produce a (N by N/2) matrix of results, i.e., O(N squared) outputs, no approach can be less than O(N squared) -- in any language, of course. (N is \"about 9K\" in your question). So, I see nothing intrinsically faster than (a) making the N sets you need, and (b) iterating over them to produce the output -- i.e., the simplest approach. IOW:\ndef lotsofintersections(manylists):\n manysets = [set(x) for x in manylists]\n moresets = list(manysets)\n for s in reversed(manysets):\n moresets.pop()\n for z in moresets:\n yield s & z\n\nThis code's already trying to add some minor optimization (e.g. by avoiding slicing or popping off the front of lists, which might add other O(N squared) factors).\nIf you have many cores and/or nodes available and are looking for parallel algorithms, it's a different case of course -- if that's your case, can you mention the kind of cluster you have, its size, how nodes and cores can best communicate, and so forth?\nEdit: as the OP has casually mentioned in a comment (!) that they actually need the numbers of the sets being intersected (really, why omit such crucial parts of the specs?! at least edit the question to clarify them...), this would only require changing this to:\n L = len(manysets)\n for i, s in enumerate(reversed(manysets)):\n moresets.pop()\n for j, z in enumerate(moresets):\n yield L - i, j + 1, s & z\n\n(if you need to \"count from 1\" for the progressive identifiers -- otherwise obvious change).\nBut if that's part of the specs you might as well use simpler code -- forget moresets, and:\n L = len(manysets)\n for i xrange(L):\n s = manysets[i]\n for j in range(i+1, L):\n yield i, j, s & manysets[z]\n\nthis time assuming you want to \"count from 0\" instead, just for variety;-)\n", "Try this:\n_lists = [[1, 2, 3, 7], [1, 3], [1, 2, 3], [1, 3, 4, 7]]\n_sets = map( set, _lists )\n_intersection = reduce( set.intersection, _sets )\n\nAnd to obtain the indexes:\n_idxs = [ map(_i.index, _intersection ) for _i in _lists ]\n\nCheers,\nJosΓ© MarΓ­a GarcΓ­a\nPS: Sorry I misunderstood the question\n" ]
[ 3, 2, 0 ]
[]
[]
[ "combinations", "intersection", "list", "python", "set" ]
stackoverflow_0001757698_combinations_intersection_list_python_set.txt
Q: Sqlalchemy query not commiting I'm trying to create a simple unique username function for use in a Formencode schema. Here is the function: class UniqueUsername(formencode.FancyValidator): def _to_python(self, value, state): user = DBSession.query(User.user_name).filter(User.username==value) if user is not None: raise formencode.Invalid( 'That username already exists', value, state) return value The problem is that the query gets generated but never actually hits the database. The user variable simply contains the generated query, not the query results. How do I go about fixing this? Thanks so much. A: It should be: user = DBSession.query(User.user_name).filter(User.username==value).first() also: is it User.user_name or User.username ?
Sqlalchemy query not commiting
I'm trying to create a simple unique username function for use in a Formencode schema. Here is the function: class UniqueUsername(formencode.FancyValidator): def _to_python(self, value, state): user = DBSession.query(User.user_name).filter(User.username==value) if user is not None: raise formencode.Invalid( 'That username already exists', value, state) return value The problem is that the query gets generated but never actually hits the database. The user variable simply contains the generated query, not the query results. How do I go about fixing this? Thanks so much.
[ "It should be:\nuser = DBSession.query(User.user_name).filter(User.username==value).first()\n\nalso: is it User.user_name or User.username ?\n" ]
[ 4 ]
[]
[]
[ "formencode", "python", "sqlalchemy" ]
stackoverflow_0001944423_formencode_python_sqlalchemy.txt
Q: converting a zcml based python script to a standalone script in zope/plone I have a python class working in zope 3 zcml kind of way, but i want to move the python into a standalone script that a could access via something along the lines of tal:content='context/get_tags'. This is the code as it stands: class TagListView(BrowserView): def getCategories(self): categories = set() for cat in self.portal_catalog.uniqueValuesFor('Subject'): categories.add(cat.lower()) for cat in self.__mapping: categories.add(cat.lower()) return tuple(sorted(categories)) def getSynonyms(self,category): r = self.__mapping.get(category) if r is None: return () return r[0] def __init__(self,context,request): self.context = context self.request = request self.tool = self.context.portal_categories def entries(self): taglist = '([' for category in self.tool.getCategories(): taglist = taglist + '\'' + category + '\',' for synonym in self.tool.getSynonyms(category): if len(synonym) > 0: taglist = taglist + '\'' + synonym + '\',' taglist = taglist + '])' return taglist Not great (as you may have guessed programmer isn't my job title) but it's what i have. How do I convert it to work as a standalone script? A: You can access views from page templates with the @@ syntax: context/@@viewname: tal:define="view context/@@get_tags; entries view/entries;"
converting a zcml based python script to a standalone script in zope/plone
I have a python class working in zope 3 zcml kind of way, but i want to move the python into a standalone script that a could access via something along the lines of tal:content='context/get_tags'. This is the code as it stands: class TagListView(BrowserView): def getCategories(self): categories = set() for cat in self.portal_catalog.uniqueValuesFor('Subject'): categories.add(cat.lower()) for cat in self.__mapping: categories.add(cat.lower()) return tuple(sorted(categories)) def getSynonyms(self,category): r = self.__mapping.get(category) if r is None: return () return r[0] def __init__(self,context,request): self.context = context self.request = request self.tool = self.context.portal_categories def entries(self): taglist = '([' for category in self.tool.getCategories(): taglist = taglist + '\'' + category + '\',' for synonym in self.tool.getSynonyms(category): if len(synonym) > 0: taglist = taglist + '\'' + synonym + '\',' taglist = taglist + '])' return taglist Not great (as you may have guessed programmer isn't my job title) but it's what i have. How do I convert it to work as a standalone script?
[ "You can access views from page templates with the @@ syntax: context/@@viewname:\ntal:define=\"view context/@@get_tags;\n entries view/entries;\"\n\n" ]
[ 2 ]
[]
[]
[ "plone", "python", "zope" ]
stackoverflow_0001945812_plone_python_zope.txt
Q: Variable referenced instead of copied When I run the code below it removes deleted_partner from B. But as it removes it from B it also removes it from A. So that when I try to remove it from A the program crashes. What is the problem? for deleted_partner in self.list_of_trading_partners: B = A[:] print("t", deleted_partner) print(B[self.ID].list_of_trading_partners) B[self.ID].list_of_trading_partners.remove(deleted_partner) Round_neo_classic(B) Round_costs(B) if B[self.ID].final_good > reference_value: print("d", deleted_partner) print(A[self.ID].list_of_trading_partners) A[self.ID].list_of_trading_partners.remove(deleted_partner) Output: ('t', 1) [1, 2, 3, 4] ('d', 1) [2, 3, 4] A: You're not removing from B or A, but from A[some_ID].list_of_trading_partners and B[some_ID].list_of_trading_partners. [:] only makes a "shallow copy" of the list, in that it creates a new, separate list, but the elements contained in that list (one of which list_of_trading_partners is an attribute of) are not copied but referenced. Perhaps the copy module and its deepcopy function can help you? A: Since you do not put the real list is hard to do tests, buy you can try with copy.copy or copy.deepcopy import copy for deleted_partner in self.list_of_trading_partners: B = copy.copy(A) print("t", deleted_partner) print(B[self.ID].list_of_trading_partners) B[self.ID].list_of_trading_partners.remove(deleted_partner) Round_neo_classic(B) Round_costs(B) if B[self.ID].final_good > reference_value: print("d", deleted_partner) print(A[self.ID].list_of_trading_partners) A[self.ID].list_of_trading_partners.remove(deleted_partner) A: B=A[:] does copy only the list, but not it's contents. B[self.ID] and A[self.ID] still reference the same object, only A and B are different. You might way to explicitly copy all the elements of the list too - copy.deepcopy can do this. But beware: deepcopy copies everything - it looks like you only want to copy the list_of_trading_partners, so you should probably write a __deepcopy__ method on whatever class A[self.ID] is that does just that.
Variable referenced instead of copied
When I run the code below it removes deleted_partner from B. But as it removes it from B it also removes it from A. So that when I try to remove it from A the program crashes. What is the problem? for deleted_partner in self.list_of_trading_partners: B = A[:] print("t", deleted_partner) print(B[self.ID].list_of_trading_partners) B[self.ID].list_of_trading_partners.remove(deleted_partner) Round_neo_classic(B) Round_costs(B) if B[self.ID].final_good > reference_value: print("d", deleted_partner) print(A[self.ID].list_of_trading_partners) A[self.ID].list_of_trading_partners.remove(deleted_partner) Output: ('t', 1) [1, 2, 3, 4] ('d', 1) [2, 3, 4]
[ "You're not removing from B or A, but from A[some_ID].list_of_trading_partners and B[some_ID].list_of_trading_partners. [:] only makes a \"shallow copy\" of the list, in that it creates a new, separate list, but the elements contained in that list (one of which list_of_trading_partners is an attribute of) are not copied but referenced. Perhaps the copy module and its deepcopy function can help you?\n", "Since you do not put the real list is hard to do tests, buy you can try with copy.copy or copy.deepcopy\nimport copy\n\nfor deleted_partner in self.list_of_trading_partners: \n B = copy.copy(A)\n print(\"t\", deleted_partner)\n print(B[self.ID].list_of_trading_partners)\n B[self.ID].list_of_trading_partners.remove(deleted_partner)\n Round_neo_classic(B)\n Round_costs(B)\n if B[self.ID].final_good > reference_value:\n print(\"d\", deleted_partner)\n print(A[self.ID].list_of_trading_partners)\n A[self.ID].list_of_trading_partners.remove(deleted_partner)\n\n", "B=A[:] does copy only the list, but not it's contents. B[self.ID] and A[self.ID] still reference the same object, only A and B are different. \nYou might way to explicitly copy all the elements of the list too - copy.deepcopy can do this. But beware: deepcopy copies everything - it looks like you only want to copy the list_of_trading_partners, so you should probably write a __deepcopy__ method on whatever class A[self.ID] is that does just that.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001946109_python.txt
Q: Best way to serialize a range of hours to meaningful data A part of my web app involves creating 'appointments' (shifts) using a drag-and-drop selector for each day. Currently, this data is serialized to something like this: 9,10,11,12,13,14,15,16,76,77,78,298,299,300,301,302,303,304, Where each number represents the nth half-hour of the week (so 304 is the 300th half-hour of the week, or 8am Saturday). I then parse this on the server with Python into something a bit more sensible: [[9,16],[76,78],[298,304]] But then I am having trouble converting them to datetime objects neatly, mainly because of how... tacky the data is sent to the server is in the first place. My question is this: What is the 'best' way to serialize the selected 'shifts' and convert them to datetime objects with Javascript and Python I have a live version of the shoddy HTML/Javascript that I came up with. I am using Javascript/jQuery on the client-side, and Python/Django on the server. A: You're talking about intervals. The best way to have an interval is a start time and a duration. class Shift( object ): def __init__( self, start, length ): self.start= start self.length= length def __repr__( self ): return "Shift(%d,%d)" % ( self.start, self.length ) def ends( self ): return self.start + self.length You can serialize these objects. [ Shift(9,6), Shift(76,2), Shift(298,6) ] You can implement operators to compare shifts to see if they overlap or if one contains the other. Why length? Why not end time? It turns out that some of the math for detecting overlaps and containment seem very slightly simpler if you think of the intervals as starting at a particular time and running for given duration. I've found it slightly easier to prove there are no gaps between shifts done this way. You want to use a "half-open" interval. The start time is included in the shift, but the end time is not included. def contains( self, aTime ): return self.start <= aTime < self.start + self.length def before( self, nextShift ): return self.start + self.length == nextShift.start def after( self, prevShift ): return prevShift.ends() == self.start To convert to datetime, you need a base date for the start of the week. You can then do some math to work out the shift start time. The length is (trivially) an interval. def startDatetime( self, week_start_datetime ): offset= datetime.timedelta( seconds= self.start*30*60 ) return week_start_datetime + offset def lengthTimedelta( self ): return datetime.timedelta( seconds= self.length*30*60 ) def endDatetime( self, week_start_datetime ): return self.startDatetime( week_start_datetime ) + self.lengthTimedelta() A: Well, assuming you have the code in place to extract the ranges (i.e. 1,2,3,4 is converted to [1,4]), I don't see why you cannot use standard date/time arithmetic. from datetime import datetime, timedelta def get_shift(start_of_week, start, end): """Returns a 2-tuple of datetimes""" HALF_HOUR = timedelta(minutes=30) return start_of_week + start * HALF_HOUR, start_of_week + (end + 1) * HALF_HOUR start_of_week should be monday 00:00. To use this, you need a way of calculating "monday 00:00" for any given week. This function returns monday 00:00 for the week containing the date passed to it. Try for instance start_of_week_containing(datetime.now()). def start_of_week_containing(dt): while dt.weekday() > 0: dt = dt - timedelta(days=1) return datetime(dt.year, dt.month, dt.day, 0, 0, 0) Full example: start_of_week = start_of_week_containing(datetime.now()) shift_start, shift_end = get_shift(start_of_week, 4, 9) # now shift_start and shift_end will contain datetime objects
Best way to serialize a range of hours to meaningful data
A part of my web app involves creating 'appointments' (shifts) using a drag-and-drop selector for each day. Currently, this data is serialized to something like this: 9,10,11,12,13,14,15,16,76,77,78,298,299,300,301,302,303,304, Where each number represents the nth half-hour of the week (so 304 is the 300th half-hour of the week, or 8am Saturday). I then parse this on the server with Python into something a bit more sensible: [[9,16],[76,78],[298,304]] But then I am having trouble converting them to datetime objects neatly, mainly because of how... tacky the data is sent to the server is in the first place. My question is this: What is the 'best' way to serialize the selected 'shifts' and convert them to datetime objects with Javascript and Python I have a live version of the shoddy HTML/Javascript that I came up with. I am using Javascript/jQuery on the client-side, and Python/Django on the server.
[ "You're talking about intervals. \nThe best way to have an interval is a start time and a duration.\nclass Shift( object ):\n def __init__( self, start, length ):\n self.start= start\n self.length= length\n def __repr__( self ):\n return \"Shift(%d,%d)\" % ( self.start, self.length )\n def ends( self ):\n return self.start + self.length\n\nYou can serialize these objects.\n[ Shift(9,6), Shift(76,2), Shift(298,6) ]\n\nYou can implement operators to compare shifts to see if they overlap or if one contains the other.\nWhy length? Why not end time?\nIt turns out that some of the math for detecting overlaps and containment seem very slightly simpler if you think of the intervals as starting at a particular time and running for given duration. I've found it slightly easier to prove there are no gaps between shifts done this way.\nYou want to use a \"half-open\" interval. The start time is included in the shift, but the end time is not included.\ndef contains( self, aTime ):\n return self.start <= aTime < self.start + self.length\n\ndef before( self, nextShift ):\n return self.start + self.length == nextShift.start\n\ndef after( self, prevShift ):\n return prevShift.ends() == self.start\n\nTo convert to datetime, you need a base date for the start of the week. You can then do some math to work out the shift start time. The length is (trivially) an interval.\ndef startDatetime( self, week_start_datetime ):\n offset= datetime.timedelta( seconds= self.start*30*60 )\n return week_start_datetime + offset\n\ndef lengthTimedelta( self ):\n return datetime.timedelta( seconds= self.length*30*60 )\n\ndef endDatetime( self, week_start_datetime ):\n return self.startDatetime( week_start_datetime ) + self.lengthTimedelta()\n\n", "Well, assuming you have the code in place to extract the ranges (i.e. 1,2,3,4 is converted to [1,4]), I don't see why you cannot use standard date/time arithmetic.\nfrom datetime import datetime, timedelta\n\ndef get_shift(start_of_week, start, end):\n \"\"\"Returns a 2-tuple of datetimes\"\"\"\n HALF_HOUR = timedelta(minutes=30)\n return start_of_week + start * HALF_HOUR, start_of_week + (end + 1) * HALF_HOUR\n\nstart_of_week should be monday 00:00. To use this, you need a way of calculating \"monday 00:00\" for any given week.\nThis function returns monday 00:00 for the week containing the date passed to it. Try for instance start_of_week_containing(datetime.now()).\ndef start_of_week_containing(dt):\n while dt.weekday() > 0:\n dt = dt - timedelta(days=1)\n return datetime(dt.year, dt.month, dt.day, 0, 0, 0)\n\nFull example:\nstart_of_week = start_of_week_containing(datetime.now())\nshift_start, shift_end = get_shift(start_of_week, 4, 9)\n# now shift_start and shift_end will contain datetime objects\n\n" ]
[ 2, 1 ]
[]
[]
[ "javascript", "jquery", "python", "serialization" ]
stackoverflow_0001946265_javascript_jquery_python_serialization.txt
Q: How to create an internationalized Google App Engine application I would like to provide my Python GAE website in the user's own language, using only the tools available directly in App Engine. For that, I would like to use GNU gettext files (.po and .mo files). Has someone successfully combined Python Google App Engine and gettext files? If so, could you please provide the steps you used? I had started a discussion in GAE's Google group, but haven't been able to extract from it how I'd like to do it: I don't want to add external dependencies, like Babel (suggested in the discussion). I want to use plain vanilla Google App Engine, so no manual update of Django or this kind of stuff. At first, I will start using the language sent by the browser, so no need to manually force the language by using cookies etc. However, I might add a language changing feature later, once the basic internationalization works. As a background note to give you more details about what I'm trying to do, I would like to internationalize Issue Tracker Tracker, an open source application I've hosted on Launchpad. I plan to use Launchpad's translation platform (explaining why I'd like to use .mo files). You can have a look at the source code in it's Bazaar branch (sorry no link due to stackoverflow spam prevention limit for new users...) Thanks for helping me advance on this project! A: As my needs were simple, I used a simple hack instead of (unavailable) gettext. I created a file with string translations, translate.py. Approximately like this: en={} ru={} en['default_site_title']=u"Site title in English" ru['default_site_title']=u"НазваниС сайта ΠΏΠΎ-русски" Then in the main code I defined a function which returns a dictionary with translations into the most suitable language from the list (the first one to have a translation is used or English): import translate def get_messages(languages=[]): msgs=translate.en for lang in languages: if hasattr(translate,lang): msgs=getattr(translate,lang) break return msgs Usage: msgs = get_messages(["it","ru","en"]) hi = msgs['hello_message'] % 'yourname' I also defined a helper function which extracts a list of languages from Accept-Language header. It's not the most flexible solution, but it doesn't have any external dependencies and works for me (in a toy project). I think translate.py may be generated automatically from gettext files. In case you want to see more, my actual source is here. A: You can use the Django internationalisation tool, like explained here. They are also saying that there is no easy way to do this. I hope that helps you :)
How to create an internationalized Google App Engine application
I would like to provide my Python GAE website in the user's own language, using only the tools available directly in App Engine. For that, I would like to use GNU gettext files (.po and .mo files). Has someone successfully combined Python Google App Engine and gettext files? If so, could you please provide the steps you used? I had started a discussion in GAE's Google group, but haven't been able to extract from it how I'd like to do it: I don't want to add external dependencies, like Babel (suggested in the discussion). I want to use plain vanilla Google App Engine, so no manual update of Django or this kind of stuff. At first, I will start using the language sent by the browser, so no need to manually force the language by using cookies etc. However, I might add a language changing feature later, once the basic internationalization works. As a background note to give you more details about what I'm trying to do, I would like to internationalize Issue Tracker Tracker, an open source application I've hosted on Launchpad. I plan to use Launchpad's translation platform (explaining why I'd like to use .mo files). You can have a look at the source code in it's Bazaar branch (sorry no link due to stackoverflow spam prevention limit for new users...) Thanks for helping me advance on this project!
[ "As my needs were simple, I used a simple hack instead of (unavailable) gettext. I created a file with string translations, translate.py. Approximately like this:\nen={}\nru={}\n\nen['default_site_title']=u\"Site title in English\"\nru['default_site_title']=u\"НазваниС сайта ΠΏΠΎ-русски\"\n\nThen in the main code I defined a function which returns a dictionary with translations into the most suitable language from the list (the first one to have a translation is used or English):\nimport translate\n\ndef get_messages(languages=[]):\n msgs=translate.en\n for lang in languages:\n if hasattr(translate,lang):\n msgs=getattr(translate,lang)\n break\n return msgs\n\nUsage:\nmsgs = get_messages([\"it\",\"ru\",\"en\"])\nhi = msgs['hello_message'] % 'yourname'\n\nI also defined a helper function which extracts a list of languages from Accept-Language header.\nIt's not the most flexible solution, but it doesn't have any external dependencies and works for me (in a toy project). I think translate.py may be generated automatically from gettext files.\nIn case you want to see more, my actual source is here.\n", "You can use the Django internationalisation tool, like explained here.\nThey are also saying that there is no easy way to do this.\nI hope that helps you :)\n" ]
[ 6, 4 ]
[]
[]
[ "gettext", "google_app_engine", "internationalization", "python" ]
stackoverflow_0001946251_gettext_google_app_engine_internationalization_python.txt
Q: asm / C / Python / Perl / Lisp / Scheme Programmer looking for something new to learn I need to have an at-home project now that I'm working on Python/Django at work. I'd like to learn something new, so I was thinking of checking out Java. What's the most well respected web framework for deploying Java web apps? The only reason I'm not checking out ruby on rails is because of how similar the ORM and other parts are to Django. Alternatively, does anyone think I should take a look at seaside/smalltalk? Can anyone explain why I should? Haskell is something I'll consider if anyone can make a good argument for it. I'd need a web framework and database access library to go along with it though. I'd consider factor/forth if I wasn't so accustomed to the stack paradigm via x86/asm. I'd be willing to hear any counter-arguments to this as well. See also: http://www.reddit.com/r/programming/comments/9v3uf/asm_c_python_perl_lisp_scheme_programmer_looking/ A: With that range of skills, why don't you learn something more outside your comfort zone, like carpentry or painting, or any of hundreds of other skills that have little to do with your field. At some point, all languages are the same and you'll get scant benefit from learning another. Whereas, with something totally different, you will become a much more well-rounded individual. I, for one, like painting and golf, even though I'm not that good at either of them - when I asked my golf instructor what my handicap was, he said it was an inability to hit the ball straight :-) I find that I enjoy doing stuff I'm not accustomed to since it's a genuinely new experience. Learning another computer skill is a easy thing to do after a while and hence the pleasure from doing it is reduced. Don't get me wrong, I like to keep up with developments in the field but, for the most part, the brand new technologies give nothing to my career since most work I do is on stable technologies. You may be in a different situation. A: Haskell is pretty popular these days as a mind-bender, though it may not hurt as much for you if you already know Lisp and Scheme. It's purely functional, so there are no side effects to anything. You have to use monads to print text and do other things that require a certain order. It's also completely lazily evaluated, so you can make infinite lists in Haskell and not have to worry about memory consumption. The Haskell Platform may not be fully complete, but is intended to be a portable set of libraries for Haskell. It's list of packages includes some for CGI handling and (X)HTML generation. A: Sounds like you're into web programming, so smalltalk/seaside is a great one. IMO everyone should learn smalltalk even if they never use it, and seaside is a really different web framework than what you are used to. Django, fer instance, is all about REST, while the seaside philosophy basically says "to hell with REST." And if you've never coded in an image based environment there's just something about it that seems... natural, magical even. Lots of IDE functionality that originated in smalltalk have been implemented in file based language IDE's, but it always feels like an unnatural grafting, where those same features feel as if they simply belong there in smalltalk. Check out Pharo. Give it enough time to get used to the fact that there's no menu bar and see if it doesn't grab you. A: I do suggest Java. When I was looking for a job, I noticed lots of openings for Java developers, so there's a lot of it out there, and you might someday have a chance to use your Java skills. And then you should try out Scala. Scala is a sort of Python-ish language that uses functional programming to make very scalable programs. Unlike Python, in Scala you do need to declare types of things. Scala runs on the Java Virtual Machine so it can be used in Java shops. http://www.scala-lang.org/ It's possible I'm just giving you this answer because these are the next two languages I intend to learn, myself. You probably should also spend a little time playing around with Javascript. Javascript was sort of intended to be a "stealth Lisp" and I imagine you would pick it right up. http://www.crockford.com/javascript/javascript.html http://bc.tech.coop/blog/030920.html And heck, have some fun with it. Write a game or something! A: From your list I'd say you are due for a completely object oriented language. You could check out Ruby, but I'd recommend JavaScript since it offers a lot of interesting things you probably wouldn't expect, like support for closures, higher-order functions and prototypical inheritance - plus it's kinda fun and becoming very popular. A: I'd need a web framework and database access library to go along with it though. If all your programming is based on web frameworks and SQL databases, you will only be solving the same problems with different syntax if you switch languages. Build something using a different data model - Prolog, Conceptual Graphs, RDF, Linda/JavaSpaces, XQuery, HDF5, ASN.1, or a different network model - XMPP pub-sub, SNMP, a zero-config mesh or a swarm of ZigBee enabled Arduinos. Maybe look at languages like Oz, Io or Erlang/OTP, which are distributed rather than primarily monolithic like the ones you mention. A: What about the Java Spring framework? http://www.springsource.org/ Or maybe NHibernate? http://en.wikipedia.org/wiki/NHibernate At the end of the day its up to you. As I only listed two out of many. When I am programming a static language professonally... I try to learn a dynamic or scripting language. And vice versa. Also, I try to learn something totally different or outside my realm... maybe even Powershell or Korn shell or ActionScript. A: What's the most well respected web framework for deploying Java web apps? There is no single web framework more respected than others. Struts2, Spring MVC, Stripes or Wicket (which is event based) are all good candidates (I personally like Stripes). But you'll need a bit more for the persistence (Hibernate or JPA) and for the glue (Spring). Grails (Groovy on Rails) is another good option. Alternatively, does anyone think I should take a look at seaside/smalltalk? Can anyone explain why I should? Well, I guess that learning Smalltalk can't hurt but I don't see a good reason to choose Smalltalk over a moderner language like Java. Regarding tooling, I don't know anything in this field except VisualAge for Smalltalk but, personally, I'd really stay far away from it. Haskell is something I'll consider if anyone can make a good argument for it. [...] Looks like I'm not the right guy for that. I'd consider factor/forth if I wasn't so accustomed to the stack paradigm via x86/asm. I'd be willing to hear any counter-arguments to this as well. Same as above. A: I would have suggested mastering Lisp (in some relevant dialect) so even if you have Lisp and Scheme on your resume, it might be worthwhile to REALLY learn deeply. See http://www.paulgraham.com/avg.html for reasons why. Otherwise Prolog might interest you. It is related to SQL but for programming instead of communicating with an organised set of data tables. If you want to target web technologies I only have experience with Java. Here the newest Java Server Faces (JSF) allow for using Ajax to update pages, and Google Web Toolkit allow for very rich component based web pages. These might be juicy enough to interest you enough to learn enough Java to find them fun :) A: I don’t see C# and the .NET platform on your list. And I am surprised no one mentioned it yet. I have worked in C# for 5 years. I have looked at some Java code but I have never coded in it. I believe that Java is somewhat similar to C# enough so that if you become proficient in one I think you could pick up the other is a matter of a few days. One idea might be to create your own language / compiler. The one I would like to create (or see created) would be an Assembly Language level compiler with an object oriented syntax that would be very much like Python… but make it typed language. You could start with the basic raw binary types db, dw, dd, and then add on to these … The functions and methods could have assembly language freely mixed in the high-level code. Now, that would be a fun project, I think ? A: Definitely try Haskell or Smalltalk or Forth. I would say Smalltalk would be most useful while Forth would get you away from the x86 asm and C bullshit. There's more than one way to code close-to-the-hardware stuff. A: Why don't you try OCaml? And if you ever happen (sadly) to return to .NET world - you will have knowledge of F# in your baggage.
asm / C / Python / Perl / Lisp / Scheme Programmer looking for something new to learn
I need to have an at-home project now that I'm working on Python/Django at work. I'd like to learn something new, so I was thinking of checking out Java. What's the most well respected web framework for deploying Java web apps? The only reason I'm not checking out ruby on rails is because of how similar the ORM and other parts are to Django. Alternatively, does anyone think I should take a look at seaside/smalltalk? Can anyone explain why I should? Haskell is something I'll consider if anyone can make a good argument for it. I'd need a web framework and database access library to go along with it though. I'd consider factor/forth if I wasn't so accustomed to the stack paradigm via x86/asm. I'd be willing to hear any counter-arguments to this as well. See also: http://www.reddit.com/r/programming/comments/9v3uf/asm_c_python_perl_lisp_scheme_programmer_looking/
[ "With that range of skills, why don't you learn something more outside your comfort zone, like carpentry or painting, or any of hundreds of other skills that have little to do with your field.\nAt some point, all languages are the same and you'll get scant benefit from learning another. \nWhereas, with something totally different, you will become a much more well-rounded individual. I, for one, like painting and golf, even though I'm not that good at either of them - when I asked my golf instructor what my handicap was, he said it was an inability to hit the ball straight :-)\nI find that I enjoy doing stuff I'm not accustomed to since it's a genuinely new experience. Learning another computer skill is a easy thing to do after a while and hence the pleasure from doing it is reduced.\nDon't get me wrong, I like to keep up with developments in the field but, for the most part, the brand new technologies give nothing to my career since most work I do is on stable technologies. You may be in a different situation.\n", "Haskell is pretty popular these days as a mind-bender, though it may not hurt as much for you if you already know Lisp and Scheme. It's purely functional, so there are no side effects to anything. You have to use monads to print text and do other things that require a certain order. It's also completely lazily evaluated, so you can make infinite lists in Haskell and not have to worry about memory consumption.\nThe Haskell Platform may not be fully complete, but is intended to be a portable set of libraries for Haskell. It's list of packages includes some for CGI handling and (X)HTML generation.\n", "Sounds like you're into web programming, so smalltalk/seaside is a great one. IMO everyone should learn smalltalk even if they never use it, and seaside is a really different web framework than what you are used to. Django, fer instance, is all about REST, while the seaside philosophy basically says \"to hell with REST.\" \nAnd if you've never coded in an image based environment there's just something about it that seems... natural, magical even. Lots of IDE functionality that originated in smalltalk have been implemented in file based language IDE's, but it always feels like an unnatural grafting, where those same features feel as if they simply belong there in smalltalk. \nCheck out Pharo. Give it enough time to get used to the fact that there's no menu bar and see if it doesn't grab you. \n", "I do suggest Java. When I was looking for a job, I noticed lots of openings for Java developers, so there's a lot of it out there, and you might someday have a chance to use your Java skills.\nAnd then you should try out Scala. Scala is a sort of Python-ish language that uses functional programming to make very scalable programs. Unlike Python, in Scala you do need to declare types of things. Scala runs on the Java Virtual Machine so it can be used in Java shops.\nhttp://www.scala-lang.org/\nIt's possible I'm just giving you this answer because these are the next two languages I intend to learn, myself.\nYou probably should also spend a little time playing around with Javascript. Javascript was sort of intended to be a \"stealth Lisp\" and I imagine you would pick it right up.\nhttp://www.crockford.com/javascript/javascript.html\nhttp://bc.tech.coop/blog/030920.html\nAnd heck, have some fun with it. Write a game or something!\n", "From your list I'd say you are due for a completely object oriented language. \nYou could check out Ruby, but I'd recommend JavaScript since it offers a lot of interesting things you probably wouldn't expect, like support for closures, higher-order functions and prototypical inheritance - plus it's kinda fun and becoming very popular.\n", "\nI'd need a web framework and database access library to go along with it though.\n\nIf all your programming is based on web frameworks and SQL databases, you will only be solving the same problems with different syntax if you switch languages.\nBuild something using a different data model - Prolog, Conceptual Graphs, RDF, Linda/JavaSpaces, XQuery, HDF5, ASN.1, or a different network model - XMPP pub-sub, SNMP, a zero-config mesh or a swarm of ZigBee enabled Arduinos.\nMaybe look at languages like Oz, Io or Erlang/OTP, which are distributed rather than primarily monolithic like the ones you mention.\n", "What about the Java Spring framework?\nhttp://www.springsource.org/\nOr maybe NHibernate?\nhttp://en.wikipedia.org/wiki/NHibernate\nAt the end of the day its up to you. As I only listed two out of many. When I am programming a static language professonally... I try to learn a dynamic or scripting language. And vice versa.\nAlso, I try to learn something totally different or outside my realm... maybe even Powershell or Korn shell or ActionScript.\n", "\nWhat's the most well respected web framework for deploying Java web apps?\n\nThere is no single web framework more respected than others. Struts2, Spring MVC, Stripes or Wicket (which is event based) are all good candidates (I personally like Stripes). But you'll need a bit more for the persistence (Hibernate or JPA) and for the glue (Spring). \nGrails (Groovy on Rails) is another good option.\n\nAlternatively, does anyone think I should take a look at seaside/smalltalk? Can anyone explain why I should?\n\nWell, I guess that learning Smalltalk can't hurt but I don't see a good reason to choose Smalltalk over a moderner language like Java. Regarding tooling, I don't know anything in this field except VisualAge for Smalltalk but, personally, I'd really stay far away from it.\n\nHaskell is something I'll consider if anyone can make a good argument for it. [...]\n\nLooks like I'm not the right guy for that.\n\nI'd consider factor/forth if I wasn't so accustomed to the stack paradigm via x86/asm. I'd be willing to hear any counter-arguments to this as well.\n\nSame as above.\n", "I would have suggested mastering Lisp (in some relevant dialect) so even if you have Lisp and Scheme on your resume, it might be worthwhile to REALLY learn deeply. See http://www.paulgraham.com/avg.html for reasons why.\nOtherwise Prolog might interest you. It is related to SQL but for programming instead of communicating with an organised set of data tables.\nIf you want to target web technologies I only have experience with Java. Here the newest Java Server Faces (JSF) allow for using Ajax to update pages, and Google Web Toolkit allow for very rich component based web pages. These might be juicy enough to interest you enough to learn enough Java to find them fun :)\n", "I don’t see C# and the .NET platform on your list. And I am surprised no one mentioned it yet. \nI have worked in C# for 5 years. I have looked at some Java code but I have never coded in it. I believe that Java is somewhat similar to C# enough so that if you become proficient in one I think you could pick up the other is a matter of a few days. \nOne idea might be to create your own language / compiler. The one I would like to create (or see created) would be an Assembly Language level compiler with an object oriented syntax that would be very much like Python… but make it typed language. You could start with the basic raw binary types db, dw, dd, and then add on to these … The functions and methods could have assembly language freely mixed in the high-level code. Now, that would be a fun project, I think ?\n", "Definitely try Haskell or Smalltalk or Forth.\nI would say Smalltalk would be most useful while Forth would get you away from the x86 asm and C bullshit. There's more than one way to code close-to-the-hardware stuff.\n", "Why don't you try OCaml? And if you ever happen (sadly) to return to .NET world - you will have knowledge of F# in your baggage.\n" ]
[ 14, 6, 4, 3, 2, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "haskell", "java", "lisp", "python", "smalltalk" ]
stackoverflow_0001583597_haskell_java_lisp_python_smalltalk.txt
Q: Python: How to change hex string int integer? Possible Duplicate: Convert hex string to int in Python Hello, I want to use some string like "0xFF123456" as a 32-bit unsigned integer. Please give me some advice. Thanks. A: a = int("0xFF123456", 0) If it doesn't have a 0x prefix you could also use: a = int("FF123456", 16) A: >>> int('0xFF123456', 16) 4279383126 >>> A: try this: >>>print int("0xFF123456",0) or >>>print int("0xFF123456",16)
Python: How to change hex string int integer?
Possible Duplicate: Convert hex string to int in Python Hello, I want to use some string like "0xFF123456" as a 32-bit unsigned integer. Please give me some advice. Thanks.
[ "a = int(\"0xFF123456\", 0)\nIf it doesn't have a 0x prefix you could also use:\na = int(\"FF123456\", 16)\n", ">>> int('0xFF123456', 16)\n4279383126\n>>> \n\n", "try this:\n>>>print int(\"0xFF123456\",0)\n\nor\n>>>print int(\"0xFF123456\",16)\n\n" ]
[ 5, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001946796_python.txt
Q: Making Python code Pythonic How would you make the give code more Pythonic? I want to get Paths out of the sample like /usr/local/sources/devel/algebra.py: def _alg(...) without the character :. My code import os FunctionPath = "/usr/local/sources/devel/sage-main/build/sage/" cmd = "grep -R 'def ' %s | cut -d' ' -f1" % (FunctionPath) cmd += ' &' raw_path = os.system(cmd) path = raw_path.replace(':', '') // not working print path [edit]: The code cannot be written pythonically only with Built-in functions. A: Why not do this: for line in open(FunctionPath): line = line.strip() if line.startswith('def '): print '%s: %s' % (FunctionPath, line.partition(':')[0]) And if you use fileinput module you can iterate over lines from multiple input streams very easily: import fileinput for line in fileinput.input(paths): line = line.strip() if line.startswith('def '): print '%s: %s' % (fileinput.filename(), line.partition(':')[0]) BTW, if you don't give fileinput.input any path it will use sys.argv by default, so you can run your python script like this: $ python script.py filepath1 filepath2 filepath3 fileinput will read the files for you. if you really want to cover all cases, you shouldn't be using replace(':', '') because it is possible to have def func(): #comment myfunc(): pass The following will give you the correct result: >>> 'def func(): #comment myfunc():'.partition(':')[0] 'def func()' Unless you want the comment as well. A: Literaly: "without the modules os, subprocess or Popen" You can also use commands module :P A: Same with os.walk for path, dirnames, filenames in os.walk(function_path): for filename in filenames: path = os.path.join(path, filename) with open(path) as f: for line in f: # Instead of grep if 'def ' in line: # Instead of cut data = line.split(' ')[2] print data.replace(":", '') A: If you're using Python mainly as a wrapper to sh, why not doing everything directly from the shell? set SEARCH_PATH=/usr/local/sources/devel/sage-main/build/sage/ grep -R 'def ' $SEARCH_PATH | awk -F':' '{print $1 $2}'
Making Python code Pythonic
How would you make the give code more Pythonic? I want to get Paths out of the sample like /usr/local/sources/devel/algebra.py: def _alg(...) without the character :. My code import os FunctionPath = "/usr/local/sources/devel/sage-main/build/sage/" cmd = "grep -R 'def ' %s | cut -d' ' -f1" % (FunctionPath) cmd += ' &' raw_path = os.system(cmd) path = raw_path.replace(':', '') // not working print path [edit]: The code cannot be written pythonically only with Built-in functions.
[ "Why not do this:\nfor line in open(FunctionPath):\n line = line.strip()\n if line.startswith('def '):\n print '%s: %s' % (FunctionPath, line.partition(':')[0])\n\nAnd if you use fileinput module you can iterate over lines from multiple input streams very easily:\nimport fileinput\nfor line in fileinput.input(paths):\n line = line.strip()\n if line.startswith('def '):\n print '%s: %s' % (fileinput.filename(), line.partition(':')[0])\n\nBTW, if you don't give fileinput.input any path it will use sys.argv by default, so you can run your python script like this:\n$ python script.py filepath1 filepath2 filepath3\n\nfileinput will read the files for you.\nif you really want to cover all cases, you shouldn't be using replace(':', '') because it is possible to have \ndef func(): #comment myfunc():\n pass\n\nThe following will give you the correct result:\n>>> 'def func(): #comment myfunc():'.partition(':')[0]\n'def func()'\n\nUnless you want the comment as well.\n", "Literaly: \"without the modules os, subprocess or Popen\"\nYou can also use commands module :P\n", "Same with os.walk\nfor path, dirnames, filenames in os.walk(function_path):\n for filename in filenames:\n path = os.path.join(path, filename)\n with open(path) as f:\n for line in f:\n # Instead of grep\n if 'def ' in line:\n # Instead of cut\n data = line.split(' ')[2]\n print data.replace(\":\", '')\n\n", "If you're using Python mainly as a wrapper to sh, why not doing everything directly from the shell?\nset SEARCH_PATH=/usr/local/sources/devel/sage-main/build/sage/\ngrep -R 'def ' $SEARCH_PATH | awk -F':' '{print $1 $2}'\n\n" ]
[ 11, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001946701_python.txt
Q: Solr Facet Range with Integers My index contains peoples information, name, age, phone email etc. I am faceting on Age. I group ages kinda like Date Range functionality. My ranges are: 0 to 10 11 to 20 21 to 30 31 to 40 etc etc When I do a query: ?q=*:*&facet=true&fq=age:[21+TO+30] It returns all the ages I want in the range 21 to 30, but it also returns the age 3. ?q=*:*&facet=true&fq=age:[11+TO+20] this does the same thing, but it returns the age 2. ?q=*:*&facet=true&fq=age:[0+TO+10] this does the same thing, but it returns the age 1. Can anyone explain this to me - is it a in solr? A: In your request, you don't have any facet queries. You are using filter queries. Which will narrow you're results set down. Perhaps you could try adding some facet.query's to your request and copy the results from the facet.counts area, in to your question above. At the very least this will tell you how many results solr thinks are in the different age ranges: &facet.query=age:[21+TO+30]&facet.query=age:[11+TO+20]&facet.query=age:[0+TO+10]&facet.query=age:[*+TO+2]&facet.query=age:[*+TO+3] A: From trawling the web I found that Solr indexes all data as strings - even when you define it as an integer. Its still a string in Solr: <field name="age" type="integer" indexed="true" stored="true"/> So what I needed to do was: <field name="age" type="sint" indexed="true" stored="true"/> If you want to order your integers this is the way, I assume the "sint" type was designed specifically for this. Cheers A: I know nothing of solr but I would guess that it is treating your ranges as alphabetical rather than numeric. You may want to look at this answer which has links to various documents discussing a very similar issue
Solr Facet Range with Integers
My index contains peoples information, name, age, phone email etc. I am faceting on Age. I group ages kinda like Date Range functionality. My ranges are: 0 to 10 11 to 20 21 to 30 31 to 40 etc etc When I do a query: ?q=*:*&facet=true&fq=age:[21+TO+30] It returns all the ages I want in the range 21 to 30, but it also returns the age 3. ?q=*:*&facet=true&fq=age:[11+TO+20] this does the same thing, but it returns the age 2. ?q=*:*&facet=true&fq=age:[0+TO+10] this does the same thing, but it returns the age 1. Can anyone explain this to me - is it a in solr?
[ "In your request, you don't have any facet queries. You are using filter queries. Which will narrow you're results set down.\nPerhaps you could try adding some facet.query's to your request and copy the results from the facet.counts area, in to your question above. At the very least this will tell you how many results solr thinks are in the different age ranges:\n&facet.query=age:[21+TO+30]&facet.query=age:[11+TO+20]&facet.query=age:[0+TO+10]&facet.query=age:[*+TO+2]&facet.query=age:[*+TO+3]\n\n", "From trawling the web I found that Solr indexes all data as strings - even when you define it as an integer. Its still a string in Solr:\n<field name=\"age\" type=\"integer\" indexed=\"true\" stored=\"true\"/>\nSo what I needed to do was:\n<field name=\"age\" type=\"sint\" indexed=\"true\" stored=\"true\"/>\nIf you want to order your integers this is the way, I assume the \"sint\" type was designed specifically for this.\nCheers\n", "I know nothing of solr but I would guess that it is treating your ranges as alphabetical rather than numeric.\nYou may want to look at this answer which has links to various documents discussing a very similar issue\n" ]
[ 3, 3, 1 ]
[]
[]
[ "django", "python", "solr" ]
stackoverflow_0001901567_django_python_solr.txt
Q: select object to edit I have a simple view function that's designed to allow the user to choose from items listed in an html table (records). Clicking on a record should divert the user to the template from which he can edit that specific record. The code is as follows: def edit_record(request): if request.method == 'POST': a=ProjectRecord.objects.get() form = RecordForm(request.POST, instance=a) if form.is_valid(): form.save() return HttpResponseRedirect('/') else: a=ProjectRecord.objects.get() form = RecordForm(instance=a) return render_to_response('productionModulewire.html', {'form': form}) The problem is that the function works perfectly well ONLY so long as there is only 1 record in the database. As soon as I add another, I get a multiple returned item error. I suspect it has something to do with "objects.get()" but I don't know how to correctly structure the view? The url is simple (perhaps too much so): (r'^edit/', edit_record), and the model looks like this: class ProjectRecord(models.Model): client = models.CharField(max_length=50, choices=CLIENT_CHOICES) account = models.CharField(max_length=50, choices=ACCOUNT_CHOICES) project_type = models.CharField(max_length=50, choices=TYPE_CHOICES) market = models.CharField(max_length=50, choices=MARKET_CHOICES) agencyID = models.CharField(max_length=30, unique=True, blank=True, null=True) clientID = models.CharField(max_length=30, unique=True, blank=True, null=True) prjmanager = models.CharField(max_length=64, unique=False, blank=True, null=True) acclead = models.CharField(max_length=64, unique=False, blank=True, null=True) artdirector = models.CharField(max_length=64, unique=False, blank=True, null=True) prdlead = models.CharField(max_length=64, unique=False, blank=True, null=True) intlead = models.CharField(max_length=64, unique=False, blank=True, null=True) prjname = models.CharField(max_length=200, unique=True) prjstatus = models.CharField(max_length=50, choices=STATUS_CHOICES) as_of = models.DateField(auto_now_add=False) format = models.CharField(max_length=64, unique=False, blank=True, null=True) target_studio = models.DateField(unique=False, blank=True, null=True) mech_return = models.DateField(unique=False, blank=True, null=True) comp_return = models.DateField(unique=False, blank=True, null=True) target_release = models.DateField(unique=False, blank=True, null=True) record_added = models.DateField(auto_now_add=True) record_modified = models.DateTimeField() studio_name = models.CharField(max_length=64, unique=False, blank=True, null=True) studio_process = models.CharField(max_length=64, unique=False, blank=True, null=True, choices=PROCESS_CHOICES) to_studio = models.DateTimeField(unique=False, blank=True, null=True) from_studio = models.DateTimeField(unique=False, blank=True, null=True) studio_name2 = models.CharField(max_length=64, unique=False, blank=True, null=True) studio_process2 = models.CharField(max_length=64, unique=False, blank=True, null=True, choices=PROCESS_CHOICES) to_studio2 = models.DateTimeField(unique=False, blank=True, null=True) from_studio2 = models.DateTimeField(unique=False, blank=True, null=True) comments = models.TextField(max_length=500, unique=False, blank=True, null=True) summary = models.TextField(max_length=500, unique=False, blank=True, null=True) upload_pdf = models.CharField(max_length=50, unique=False, blank=True, null=True) upload_achive = models.CharField(max_length=50, unique=False, blank=True, null=True) def __unicode__(self): return u'%s' % self.prjname class Admin: pass from which the model form "RecordForm" was derived. A: The important thing about get is "get what?" When you say a=ProjectRecord.objects.get() you neglected to provide any selection criteria. Which row do you want from the database? Which row? Hmmmm... How does the GET transaction know which row is going to be edited? Usually, we put that in the URL. So, you'll need to update your urls.py to include the record ID on the URL path. You'll need to update your view function definition to accept this record ID. Finally, you'll need to update GET and POST to use this record identification which came from the URL. Update urls.py to include the object id. See http://docs.djangoproject.com/en/1.1/topics/http/urls/#named-groups urlpatterns = patterns('', (r'^class/(?P<object_id>\d+?)/$', 'app.views.edit_record'), Update your view function def edit_record( request, object_id = None ): if request.method == "POST": if object_id is None: return Http_404 ProjectRecord.objects.get( pk = int(object_id) ) etc. A: Without more information it is hard to tell what you need to change, but your guess is correct, the problem is with your ProjectRecord.objects.get() call. You should be passing some sort of information to get in order to limit the list down to one. In most cases, you will need: ProjectRecord.objects.get(pk=id) Where id is the primary key value of the ProjectRecord you are trying to edit. Could you show the relevant code from your urls.py as well as more information on your ProjectRecord model?
select object to edit
I have a simple view function that's designed to allow the user to choose from items listed in an html table (records). Clicking on a record should divert the user to the template from which he can edit that specific record. The code is as follows: def edit_record(request): if request.method == 'POST': a=ProjectRecord.objects.get() form = RecordForm(request.POST, instance=a) if form.is_valid(): form.save() return HttpResponseRedirect('/') else: a=ProjectRecord.objects.get() form = RecordForm(instance=a) return render_to_response('productionModulewire.html', {'form': form}) The problem is that the function works perfectly well ONLY so long as there is only 1 record in the database. As soon as I add another, I get a multiple returned item error. I suspect it has something to do with "objects.get()" but I don't know how to correctly structure the view? The url is simple (perhaps too much so): (r'^edit/', edit_record), and the model looks like this: class ProjectRecord(models.Model): client = models.CharField(max_length=50, choices=CLIENT_CHOICES) account = models.CharField(max_length=50, choices=ACCOUNT_CHOICES) project_type = models.CharField(max_length=50, choices=TYPE_CHOICES) market = models.CharField(max_length=50, choices=MARKET_CHOICES) agencyID = models.CharField(max_length=30, unique=True, blank=True, null=True) clientID = models.CharField(max_length=30, unique=True, blank=True, null=True) prjmanager = models.CharField(max_length=64, unique=False, blank=True, null=True) acclead = models.CharField(max_length=64, unique=False, blank=True, null=True) artdirector = models.CharField(max_length=64, unique=False, blank=True, null=True) prdlead = models.CharField(max_length=64, unique=False, blank=True, null=True) intlead = models.CharField(max_length=64, unique=False, blank=True, null=True) prjname = models.CharField(max_length=200, unique=True) prjstatus = models.CharField(max_length=50, choices=STATUS_CHOICES) as_of = models.DateField(auto_now_add=False) format = models.CharField(max_length=64, unique=False, blank=True, null=True) target_studio = models.DateField(unique=False, blank=True, null=True) mech_return = models.DateField(unique=False, blank=True, null=True) comp_return = models.DateField(unique=False, blank=True, null=True) target_release = models.DateField(unique=False, blank=True, null=True) record_added = models.DateField(auto_now_add=True) record_modified = models.DateTimeField() studio_name = models.CharField(max_length=64, unique=False, blank=True, null=True) studio_process = models.CharField(max_length=64, unique=False, blank=True, null=True, choices=PROCESS_CHOICES) to_studio = models.DateTimeField(unique=False, blank=True, null=True) from_studio = models.DateTimeField(unique=False, blank=True, null=True) studio_name2 = models.CharField(max_length=64, unique=False, blank=True, null=True) studio_process2 = models.CharField(max_length=64, unique=False, blank=True, null=True, choices=PROCESS_CHOICES) to_studio2 = models.DateTimeField(unique=False, blank=True, null=True) from_studio2 = models.DateTimeField(unique=False, blank=True, null=True) comments = models.TextField(max_length=500, unique=False, blank=True, null=True) summary = models.TextField(max_length=500, unique=False, blank=True, null=True) upload_pdf = models.CharField(max_length=50, unique=False, blank=True, null=True) upload_achive = models.CharField(max_length=50, unique=False, blank=True, null=True) def __unicode__(self): return u'%s' % self.prjname class Admin: pass from which the model form "RecordForm" was derived.
[ "The important thing about get is \"get what?\"\nWhen you say\na=ProjectRecord.objects.get()\n\nyou neglected to provide any selection criteria. Which row do you want from the database?\nWhich row? Hmmmm... How does the GET transaction know which row is going to be edited?\nUsually, we put that in the URL.\nSo, you'll need to update your urls.py to include the record ID on the URL path. You'll need to update your view function definition to accept this record ID. Finally, you'll need to update GET and POST to use this record identification which came from the URL.\n\nUpdate urls.py to include the object id. See http://docs.djangoproject.com/en/1.1/topics/http/urls/#named-groups\nurlpatterns = patterns('',\n (r'^class/(?P<object_id>\\d+?)/$', 'app.views.edit_record'),\n\nUpdate your view function\ndef edit_record( request, object_id = None ):\n if request.method == \"POST\":\n if object_id is None:\n return Http_404\n ProjectRecord.objects.get( pk = int(object_id) )\n\n etc.\n\n", "Without more information it is hard to tell what you need to change, but your guess is correct, the problem is with your ProjectRecord.objects.get() call. \nYou should be passing some sort of information to get in order to limit the list down to one.\nIn most cases, you will need:\nProjectRecord.objects.get(pk=id) \n\nWhere id is the primary key value of the ProjectRecord you are trying to edit.\nCould you show the relevant code from your urls.py as well as more information on your ProjectRecord model?\n" ]
[ 2, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0001947067_django_django_views_python.txt
Q: urllib2.urlopen() vs urllib.urlopen() - urllib2 throws 404 while urllib works! WHY? import urllib print urllib.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read() The above script works and returns the expected results while: import urllib2 print urllib2.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read() throws the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/urllib2.py", line 124, in urlopen return _opener.open(url, data) File "/usr/lib/python2.5/urllib2.py", line 387, in open response = meth(req, response) File "/usr/lib/python2.5/urllib2.py", line 498, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.5/urllib2.py", line 425, in error return self._call_chain(*args) File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain result = func(*args) File "/usr/lib/python2.5/urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 404: Not Found Does anyone know why this is? I'm running this from laptop on my home network with no proxy settings - just straight from my laptop to the router then to the www. A: That URL does indeed result in a 404, but with lots of HTML content. urllib2 is handling it (correctly) as an error condition. You can recover the content of that site's 404 page like so: import urllib2 try: print urllib2.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read() except urllib2.HTTPError, e: print e.code print e.msg print e.headers print e.fp.read()
urllib2.urlopen() vs urllib.urlopen() - urllib2 throws 404 while urllib works! WHY?
import urllib print urllib.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read() The above script works and returns the expected results while: import urllib2 print urllib2.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read() throws the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/urllib2.py", line 124, in urlopen return _opener.open(url, data) File "/usr/lib/python2.5/urllib2.py", line 387, in open response = meth(req, response) File "/usr/lib/python2.5/urllib2.py", line 498, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.5/urllib2.py", line 425, in error return self._call_chain(*args) File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain result = func(*args) File "/usr/lib/python2.5/urllib2.py", line 506, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 404: Not Found Does anyone know why this is? I'm running this from laptop on my home network with no proxy settings - just straight from my laptop to the router then to the www.
[ "That URL does indeed result in a 404, but with lots of HTML content. urllib2 is handling it (correctly) as an error condition. You can recover the content of that site's 404 page like so:\nimport urllib2\ntry:\n print urllib2.urlopen('http://www.reefgeek.com/equipment/Controllers_&_Monitors/Neptune_Systems_AquaController/Apex_Controller_&_Accessories/').read()\nexcept urllib2.HTTPError, e:\n print e.code\n print e.msg\n print e.headers\n print e.fp.read()\n\n" ]
[ 35 ]
[]
[]
[ "http_status_code_404", "python", "url", "urllib", "urllib2" ]
stackoverflow_0001947133_http_status_code_404_python_url_urllib_urllib2.txt
Q: Django - Using trees to build a comment system A few days back I was messing around with Django, trying to get a feel for how stuff works, when I decided to try and build a simple forum, one that resembled a forum that I frequented (but is now closed down). The idea was that each of the comments would be parent to any number of comments, like so: comment <--top comment <-- comment "A" comment <-- comment "B" comment <-- comment "C" comment <--C-1, reply to comment "C" comment <-- C-1-1, reply to comment "C-1" comment comment comment comment <-- C-1-1-1 reply to C-1-1 comment comment comment comment comment comment comment comment comment comment comment comment The idea here is that replies to a comment would stuffed one level beneath it, and each comment, with the exception of the very first comment, has a parent. The thing is, although I get the idea behind implementing tree traversals, none of the books/articles I've read on the subject take Django into account (or the MVC pattern for that matter), so my question is how would I go about implementing this system in Django? (here's the model code i've got for reference :-/) class Comment(models.Model): Parent = models.OneToOneField('self', null=True) Children = models.ForeignKey('self', null=True) Author = models.ForeignKey(User) Author_IP = models.IPAddressField() Created_On = models.DateTimeField(auto_now_add=True) Modified_On = models.DateTimeField(auto_now=True) Body = models.TextField() A: Have a look at django-threadedcomments. It's purpose is more fit to be used as comments on a blog than a full featured forum, but if it doesn't fit your case, you can at least look at the source code and learn a couple things from it. As far as tree-based structures go, there are three projects I'm aware of for Django's ORM: django-mptt (this one has the biggest "market share" with 3rd party django apps AFAIK), django-treebeard, and easytree (which is based on treebeard). Easytree comes with a nice admin interface, but the other two projects have at least patches in their issue trackers to add an admin interface (not sure if they integrated those patches already). A: I would only define the parent and give it a related name class Comment(models.Model): parent=models.ForeignKey('self', related_name="children", null=True, blank=True) #other fields Then you could get its children comment=Comment.objects.get(id=1) children=comment.children.all() for child in children: morechildren=child.children.all()
Django - Using trees to build a comment system
A few days back I was messing around with Django, trying to get a feel for how stuff works, when I decided to try and build a simple forum, one that resembled a forum that I frequented (but is now closed down). The idea was that each of the comments would be parent to any number of comments, like so: comment <--top comment <-- comment "A" comment <-- comment "B" comment <-- comment "C" comment <--C-1, reply to comment "C" comment <-- C-1-1, reply to comment "C-1" comment comment comment comment <-- C-1-1-1 reply to C-1-1 comment comment comment comment comment comment comment comment comment comment comment comment The idea here is that replies to a comment would stuffed one level beneath it, and each comment, with the exception of the very first comment, has a parent. The thing is, although I get the idea behind implementing tree traversals, none of the books/articles I've read on the subject take Django into account (or the MVC pattern for that matter), so my question is how would I go about implementing this system in Django? (here's the model code i've got for reference :-/) class Comment(models.Model): Parent = models.OneToOneField('self', null=True) Children = models.ForeignKey('self', null=True) Author = models.ForeignKey(User) Author_IP = models.IPAddressField() Created_On = models.DateTimeField(auto_now_add=True) Modified_On = models.DateTimeField(auto_now=True) Body = models.TextField()
[ "Have a look at django-threadedcomments. It's purpose is more fit to be used as comments on a blog than a full featured forum, but if it doesn't fit your case, you can at least look at the source code and learn a couple things from it.\nAs far as tree-based structures go, there are three projects I'm aware of for Django's ORM: django-mptt (this one has the biggest \"market share\" with 3rd party django apps AFAIK), django-treebeard, and easytree (which is based on treebeard). Easytree comes with a nice admin interface, but the other two projects have at least patches in their issue trackers to add an admin interface (not sure if they integrated those patches already).\n", "I would only define the parent and give it a related name\nclass Comment(models.Model):\n parent=models.ForeignKey('self', related_name=\"children\", null=True, blank=True)\n #other fields \n\nThen you could get its children\ncomment=Comment.objects.get(id=1)\nchildren=comment.children.all()\n\nfor child in children:\n morechildren=child.children.all()\n\n" ]
[ 2, 1 ]
[]
[]
[ "django", "python", "tree" ]
stackoverflow_0001947176_django_python_tree.txt
Q: fastcgi, cherrypy, and python So I'm trying to do more web development in python, and I've picked cherrypy, hosted by lighttpd w/ fastcgi. But my question is a very basic one: why do I need to restart lighttpd (or apache) every time I change my application code, or the code for an underlying library? I realize this question extends from a basic mis(i.e. poor)understanding of the fastcgi model, so I'm open to any schooling here, but I'm used to just changing a PHP file and it showing up, versus having to bounce the web server. Any elucidation/useful mockery appreciated. A: This is because of performance. For development, autoreloading is helpful. But for production, you don't want to autoreload. This is actually a decently-sized bottleneck in say PHP. Every time you access a PHP webpage, the server has to parse and load each page from scratch. With Python, the script is already loaded and running after the first access. As has been pointed out, CherryPy has a autoreload setting. I'd recommend using the CherryPy built-in server for development and using lighttpd for production. That will likely save you some time. The tutorial shows you how to do this. A: From a system-software-writer's pointer of view: This all depends on how the meta-data about the server process is organized within your daemon (lighttpd or fcgi). Some programs are designed for one time only initialization -- MOSTLY this allows a much simpler and better performing internal programming model. Often it is very hard to program a server process reload config data in a easy way. You might have to introduce locks and external event objects (signals in UNIX). When you can synchronize the data structures by design -- i.e., only initializing once .... why complicate things by making the data model modifiable multiple times ?
fastcgi, cherrypy, and python
So I'm trying to do more web development in python, and I've picked cherrypy, hosted by lighttpd w/ fastcgi. But my question is a very basic one: why do I need to restart lighttpd (or apache) every time I change my application code, or the code for an underlying library? I realize this question extends from a basic mis(i.e. poor)understanding of the fastcgi model, so I'm open to any schooling here, but I'm used to just changing a PHP file and it showing up, versus having to bounce the web server. Any elucidation/useful mockery appreciated.
[ "This is because of performance. For development, autoreloading is helpful. But for production, you don't want to autoreload. This is actually a decently-sized bottleneck in say PHP. Every time you access a PHP webpage, the server has to parse and load each page from scratch. With Python, the script is already loaded and running after the first access.\nAs has been pointed out, CherryPy has a autoreload setting. I'd recommend using the CherryPy built-in server for development and using lighttpd for production. That will likely save you some time. The tutorial shows you how to do this.\n", "From a system-software-writer's pointer of view: This all depends on how the meta-data about the server process is organized within your daemon (lighttpd or fcgi). Some programs are designed for one time only initialization -- MOSTLY this allows a much simpler and better performing internal programming model.\nOften it is very hard to program a server process reload config data in a easy way. You might have to introduce locks and external event objects (signals in UNIX). When you can synchronize the data structures by design -- i.e., only initializing once .... why complicate things by making the data model modifiable multiple times ?\n" ]
[ 8, 0 ]
[]
[]
[ "cherrypy", "fastcgi", "lighttpd", "python" ]
stackoverflow_0001947344_cherrypy_fastcgi_lighttpd_python.txt
Q: python email error I am trying to email a results file. I am getting an import error: Traceback (most recent call last): File "email_results.py", line 5, in ? from email import encoders ImportError: cannot import name encoders I am also unsure on how to get this to connect to the server. Can anyone help? Thanks #!/home/build/test/Python-2.6.4 import smtplib import zipfile import tempfile from email import encoders from email.message import Message from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart def send_file_zipped(the_file, recipients, sender='myname@myname.com'): zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip') zip = zipfile.ZipFile(zf, 'w') zip.write(the_file) zip.close() zf.seek(0) # Create the message themsg = MIMEMultipart() themsg['Subject'] = 'File %s' % the_file themsg['To'] = ', '.join(recipients) themsg['From'] = sender themsg.preamble = 'I am not using a MIME-aware mail reader.\n' msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment',filename=the_file + '.zip') themsg.attach(msg) themsg = themsg.as_string() # send the message smtp = smtplib.SMTP() smtp.connect() smtp.sendmail(sender, recipients, themsg) smtp.close() A: The problem isn't that you can't connect to the server, it's that you aren't able to import email.encoders for some reason. Do you have a file named email.py or email.pyc by any chance?
python email error
I am trying to email a results file. I am getting an import error: Traceback (most recent call last): File "email_results.py", line 5, in ? from email import encoders ImportError: cannot import name encoders I am also unsure on how to get this to connect to the server. Can anyone help? Thanks #!/home/build/test/Python-2.6.4 import smtplib import zipfile import tempfile from email import encoders from email.message import Message from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart def send_file_zipped(the_file, recipients, sender='myname@myname.com'): zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip') zip = zipfile.ZipFile(zf, 'w') zip.write(the_file) zip.close() zf.seek(0) # Create the message themsg = MIMEMultipart() themsg['Subject'] = 'File %s' % the_file themsg['To'] = ', '.join(recipients) themsg['From'] = sender themsg.preamble = 'I am not using a MIME-aware mail reader.\n' msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment',filename=the_file + '.zip') themsg.attach(msg) themsg = themsg.as_string() # send the message smtp = smtplib.SMTP() smtp.connect() smtp.sendmail(sender, recipients, themsg) smtp.close()
[ "The problem isn't that you can't connect to the server, it's that you aren't able to import email.encoders for some reason. Do you have a file named email.py or email.pyc by any chance?\n" ]
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0001947701_python.txt
Q: authenticate returns nothing what im experimenting is the next: S:\proj>manage.py shell Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) django 1.1.1 >>> from django.contrib.auth.models import User >>> u = User(username='luis', password='admin') >>> u.save() #sucessfull created in mysql db >>> from django.contrib.auth import authenticate >>> usuario = authenticate(username='luis', password='admin') >>> usuario >>> authenticate return nothing, what I am missing? A: The problem is not with authenticate, but with your creation of the user. The value stored in u.password needs to be the hashed value of the password, not the raw password itself. You can use u.set_password('password') to take care of the hashing for you: >>> u = User(name='luis') >>> u.set_password('password') >>> u.save() >>> authenticate(username='luis', password='password') <User: luis>
authenticate returns nothing
what im experimenting is the next: S:\proj>manage.py shell Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) django 1.1.1 >>> from django.contrib.auth.models import User >>> u = User(username='luis', password='admin') >>> u.save() #sucessfull created in mysql db >>> from django.contrib.auth import authenticate >>> usuario = authenticate(username='luis', password='admin') >>> usuario >>> authenticate return nothing, what I am missing?
[ "The problem is not with authenticate, but with your creation of the user.\nThe value stored in u.password needs to be the hashed value of the password, not the raw password itself.\nYou can use u.set_password('password') to take care of the hashing for you:\n>>> u = User(name='luis')\n>>> u.set_password('password')\n>>> u.save()\n>>> authenticate(username='luis', password='password')\n<User: luis>\n\n" ]
[ 4 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001947811_django_django_models_python.txt
Q: Diacritic signs How should I write "mΔ…ka" in Python without an exception? I've tried var= u"mΔ…ka" and var= unicode("mΔ…ka") etc... nothing helps I have coding definition in first line in my document, and still I've got that exception: 'utf8' codec can't decode byte 0xb1 in position 0: unexpected code byte A: Save the following 2 lines into write_mako.py: # -*- encoding: utf-8 -*- open(u"mΔ…ka.txt", 'w').write("mΔ…ka\n") Run: $ python write_mako.py mΔ…ka.txt file that contains the word mΔ…ka should be created in the current directory. If it doesn't work then you can use chardet to detect actual encoding of the file (see chardet example usage): import chardet print chardet.detect(open('write_mako.py', 'rb').read()) In my case it prints: {'confidence': 0.75249999999999995, 'encoding': 'utf-8'} A: The # -- coding: -- line must specify the encoding the source file is saved in. This error message: 'utf8' codec can't decode byte 0xb1 in position 0: unexpected code byte indicates you aren't saving the source file in UTF-8. You can save your source file in any encoding that supports the characters you are using in the source code, just make sure you know what it is and have an appropriate coding line. A: What exception are you getting? You might try saving your source code file as UTF-8, and putting this at the top of the file: # coding=utf-8 That tells Python that the file’s saved as UTF-8. A: This code works for me, saving the file as UTF-8: v = u"mΔ…ka" print repr(v) The output I get is: u'm\u0105ka' Please copy and paste the exact error you are getting. If you are getting this error: UnicodeEncodeError: 'charmap' codec can't encode character ... in position ...: character maps to <undefined> Then you are trying to output the character somewhere that does not support UTF-8 (e.g. your shell's character encoding is set to something other than UTF-8).
Diacritic signs
How should I write "mΔ…ka" in Python without an exception? I've tried var= u"mΔ…ka" and var= unicode("mΔ…ka") etc... nothing helps I have coding definition in first line in my document, and still I've got that exception: 'utf8' codec can't decode byte 0xb1 in position 0: unexpected code byte
[ "Save the following 2 lines into write_mako.py:\n# -*- encoding: utf-8 -*-\nopen(u\"mΔ…ka.txt\", 'w').write(\"mΔ…ka\\n\")\n\nRun:\n$ python write_mako.py\n\nmΔ…ka.txt file that contains the word mΔ…ka should be created in the current directory.\nIf it doesn't work then you can use chardet to detect actual encoding of the file (see chardet example usage):\nimport chardet\n\nprint chardet.detect(open('write_mako.py', 'rb').read())\n\nIn my case it prints:\n{'confidence': 0.75249999999999995, 'encoding': 'utf-8'}\n\n", "The # -- coding: -- line must specify the encoding the source file is saved in. This error message:\n'utf8' codec can't decode byte 0xb1 in position 0: unexpected code byte\n\nindicates you aren't saving the source file in UTF-8. You can save your source file in any encoding that supports the characters you are using in the source code, just make sure you know what it is and have an appropriate coding line.\n", "What exception are you getting?\nYou might try saving your source code file as UTF-8, and putting this at the top of the file:\n# coding=utf-8\n\nThat tells Python that the file’s saved as UTF-8. \n", "This code works for me, saving the file as UTF-8:\nv = u\"mΔ…ka\"\nprint repr(v)\n\nThe output I get is:\nu'm\\u0105ka'\n\nPlease copy and paste the exact error you are getting. If you are getting this error:\nUnicodeEncodeError: 'charmap' codec can't encode character ... in position ...: character maps to <undefined>\n\nThen you are trying to output the character somewhere that does not support UTF-8 (e.g. your shell's character encoding is set to something other than UTF-8).\n" ]
[ 4, 2, 1, 1 ]
[]
[]
[ "django", "python", "unicode" ]
stackoverflow_0001947837_django_python_unicode.txt
Q: Python library for sending/managing usage statistics Recall those applications that provide the option to "Send usage statistics to help improve X" during the installation? I presume it collects certain patterns of usage and sends it back to the server. Back at the server, there may be some sort of mining going on. Is there a Python library to do this .. at least from the client part? (other than manually having to code it up using urllib, for instance) A: Sending and receiving logging events across a network From the docs: import logging, logging.handlers rootLogger = logging.getLogger('') rootLogger.setLevel(logging.DEBUG) socketHandler = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT) # don't bother with a formatter, since a socket handler sends the event as # an unformatted pickle rootLogger.addHandler(socketHandler) # Now, we can log to the root logger, or any other logger. First the root... logging.info('Jackdaws love my big sphinx of quartz.') # ... You can also find there the code for receiving end. In your case it might be more appropriate to use logging.handlers.DatagramHandler on a non-root logger e.g., logging.getLogger('usage').
Python library for sending/managing usage statistics
Recall those applications that provide the option to "Send usage statistics to help improve X" during the installation? I presume it collects certain patterns of usage and sends it back to the server. Back at the server, there may be some sort of mining going on. Is there a Python library to do this .. at least from the client part? (other than manually having to code it up using urllib, for instance)
[ "Sending and receiving logging events across a network\nFrom the docs:\nimport logging, logging.handlers\n\nrootLogger = logging.getLogger('')\nrootLogger.setLevel(logging.DEBUG)\nsocketHandler = logging.handlers.SocketHandler('localhost',\n logging.handlers.DEFAULT_TCP_LOGGING_PORT)\n# don't bother with a formatter, since a socket handler sends the event as\n# an unformatted pickle\nrootLogger.addHandler(socketHandler)\n\n# Now, we can log to the root logger, or any other logger. First the root...\nlogging.info('Jackdaws love my big sphinx of quartz.')\n# ...\n\nYou can also find there the code for receiving end.\nIn your case it might be more appropriate to use logging.handlers.DatagramHandler on a non-root logger e.g., logging.getLogger('usage').\n" ]
[ 2 ]
[]
[]
[ "python", "usage_statistics" ]
stackoverflow_0001948404_python_usage_statistics.txt
Q: python - Importing a file that is a symbolic link If I have files x.py and y.py . And y.py is the link(symbolic or hard) of x.py . If I import both the modules in my script. Will it import it once or it assumes both are different files and import it twice. What it does exactly? A: You only have to be careful in the case where your script itself is a symbolic link, in which case the first entry of sys.path will be the directory containing the target of the link. A: Python will import it twice. A link is a file system concept. To the Python interpreter, x.py and y.py are two different modules. $ echo print \"importing \" + __file__ > x.py $ ln -s x.py y.py $ python -c "import x; import y" importing x.py importing y.py $ python -c "import x; import y" importing x.pyc importing y.pyc $ ls -F *.py *.pyc x.py x.pyc y.py@ y.pyc
python - Importing a file that is a symbolic link
If I have files x.py and y.py . And y.py is the link(symbolic or hard) of x.py . If I import both the modules in my script. Will it import it once or it assumes both are different files and import it twice. What it does exactly?
[ "You only have to be careful in the case where your script itself is a symbolic link, in which case the first entry of sys.path will be the directory containing the target of the link.\n", "Python will import it twice.\nA link is a file system concept. To the Python interpreter, x.py and y.py are two different modules.\n\n$ echo print \\\"importing \\\" + __file__ > x.py\n$ ln -s x.py y.py\n$ python -c \"import x; import y\"\nimporting x.py\nimporting y.py\n$ python -c \"import x; import y\"\nimporting x.pyc\nimporting y.pyc\n$ ls -F *.py *.pyc\nx.py x.pyc y.py@ y.pyc\n\n" ]
[ 13, 11 ]
[]
[]
[ "import", "python", "testing" ]
stackoverflow_0001158108_import_python_testing.txt
Q: pygtk: howto change background of a gtk.TextView widget I want to make the background of a textview widget black and the foreground white. Been trying the .modify_bg and .modify_fg methods, but none affect the way this thing looks. Can anyone suggest anything or is this just not possible? A: I resolved some similar manipulating the gtk rcstyles: widget.set_name('mywidget') # Set mywidget internal style. gtk.rc_parse_string('\ style "mywidget"\n\ {\n\ attribute1 = value1\n\ attribute2 = value2\n\ }\n\ widget "*.mywidget" style "mywidget"') See gtk.rcstyle at: bg[state] = color (Sets the color used for the background of most widgets.) A: Use gtk.Widget.modify_text and gtk.Widget.modify_base instead of fg and bg.
pygtk: howto change background of a gtk.TextView widget
I want to make the background of a textview widget black and the foreground white. Been trying the .modify_bg and .modify_fg methods, but none affect the way this thing looks. Can anyone suggest anything or is this just not possible?
[ "I resolved some similar manipulating the gtk rcstyles:\nwidget.set_name('mywidget')\n\n# Set mywidget internal style.\ngtk.rc_parse_string('\\\n style \"mywidget\"\\n\\\n {\\n\\\n attribute1 = value1\\n\\\n attribute2 = value2\\n\\\n }\\n\\\n widget \"*.mywidget\" style \"mywidget\"')\n\nSee gtk.rcstyle at: \nbg[state] = color (Sets the color used for the background of most widgets.)\n", "Use gtk.Widget.modify_text and gtk.Widget.modify_base instead of fg and bg.\n" ]
[ 2, 2 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0001948396_gtk_pygtk_python.txt
Q: how can I catch the error of "no existing page" in python I developpe a browser with python and pyqt4 but I don't know what I put in loaderror try: self.webView.load(QtCore.QUrl(self.lineEdit.text())) except loaderreur: self.webView.load(QtCore.QUrl('erreur.html')) when the page doesn't exist thx A: Try loading up your browser of choice, and see what they do when given a page that doesn't exist. You likely want to mimic that behaviour (Generic 404 page).
how can I catch the error of "no existing page" in python
I developpe a browser with python and pyqt4 but I don't know what I put in loaderror try: self.webView.load(QtCore.QUrl(self.lineEdit.text())) except loaderreur: self.webView.load(QtCore.QUrl('erreur.html')) when the page doesn't exist thx
[ "Try loading up your browser of choice, and see what they do when given a page that doesn't exist.\nYou likely want to mimic that behaviour (Generic 404 page).\n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0001949049_pyqt4_python.txt
Q: Displaying graphics on top of another full screen application; hardware overlay? On Windows (Vista32), I want to display some simple graphics on top of a fullscreen flash window (an overlay of useful information while using the flash application). What's the fastest way to accomplish it? I think I may be able to achieve it using DirectX with the DDSCAPS_OVERLAY flag but with the only example I've found I get an exception: E_NOTIMPL The function called is not supported at this time on m_direct_draw->CreateSurface(&ddsd, &m_overlay_surface, 0) (full code here: http://nexe.gamedev.net/files/Overlay-2005-11-21.zip) Something relevant to C/++ or Python would help me. I'm using the latest DirectX SDK. Thank you A: Just create a Layered Window and draw to it with an alpha channel - in WPF, this is as easy as setting the AllowsTransparency bit on the Window A: While the transparent layered window is useful, it doesn't appear on top of the fullscreen flash with WS_EX_TOPMOST set. Note sure how to reply to Paul sadly. Overlaying on a 3D fullscreen application is very relevant but while it works and flash appears to load dx9, it doesn't show on flash.
Displaying graphics on top of another full screen application; hardware overlay?
On Windows (Vista32), I want to display some simple graphics on top of a fullscreen flash window (an overlay of useful information while using the flash application). What's the fastest way to accomplish it? I think I may be able to achieve it using DirectX with the DDSCAPS_OVERLAY flag but with the only example I've found I get an exception: E_NOTIMPL The function called is not supported at this time on m_direct_draw->CreateSurface(&ddsd, &m_overlay_surface, 0) (full code here: http://nexe.gamedev.net/files/Overlay-2005-11-21.zip) Something relevant to C/++ or Python would help me. I'm using the latest DirectX SDK. Thank you
[ "Just create a Layered Window and draw to it with an alpha channel - in WPF, this is as easy as setting the AllowsTransparency bit on the Window\n", "While the transparent layered window is useful, it doesn't appear on top of the fullscreen flash with WS_EX_TOPMOST set.\nNote sure how to reply to Paul sadly.\nOverlaying on a 3D fullscreen application is very relevant but while it works and flash appears to load dx9, it doesn't show on flash.\n" ]
[ 1, 0 ]
[]
[]
[ "c++", "directx", "flash", "python", "windows" ]
stackoverflow_0001934910_c++_directx_flash_python_windows.txt
Q: Choice of database for a Django-based RSS application? I'm planning a web application using Django, and it's based on a big pile of data from RSS feeds. What would be the best database to use to store the content of a lot of posts and metadata, as well as data about how each user relates to each post? I've heard that the consensus is that ZODB is too slow, but it'd be handy to have a database of persistent objects. The other big options are CouchDB, which I'm not familiar with beyond "schema-less JSON document store", and a normal RDBMS. Has anyone built something like this before? What'd you use? A: Django is tuned to work (and perform) nicely with RDBMS, so that's probably the path of least resistance, until you've demonstrated to yourself that an RDBMS won't solve your problem. If you do reach that point, this page on the wiki is probably a good jumping off point for non-relational DBs in Django.
Choice of database for a Django-based RSS application?
I'm planning a web application using Django, and it's based on a big pile of data from RSS feeds. What would be the best database to use to store the content of a lot of posts and metadata, as well as data about how each user relates to each post? I've heard that the consensus is that ZODB is too slow, but it'd be handy to have a database of persistent objects. The other big options are CouchDB, which I'm not familiar with beyond "schema-less JSON document store", and a normal RDBMS. Has anyone built something like this before? What'd you use?
[ "Django is tuned to work (and perform) nicely with RDBMS, so that's probably the path of least resistance, until you've demonstrated to yourself that an RDBMS won't solve your problem. If you do reach that point, this page on the wiki is probably a good jumping off point for non-relational DBs in Django.\n" ]
[ 3 ]
[]
[]
[ "database", "django", "python", "rss" ]
stackoverflow_0001949228_database_django_python_rss.txt
Q: twisted threading with subprocess.Popen? I'm trying to implement a service with Twisted that's fairly close to the "finger" tutorial found here: http://twistedmatrix.com/documents/current/core/howto/tutorial/intro.html I've got a basic.LineListener waiting for a command and then executing it, then I have a client connecting and issuing commands. Trouble is that the command sometimes needs to execute something else and I'm using python's subprocess module for that. It's not just that calls to communicate() are hanging, that's a normal subprocess issue and I know how to get past it. It's that subprocess.Popen calls are hanging. Here's the twisted server code: from twisted.application import internet, service from twisted.internet import protocol, reactor, defer, threads from twisted.protocols import basic import sys import time import subprocess class MyProtocol(basic.LineReceiver): def lineReceived(self, line): self.go() def go(self): def writeResponse(message): self.transport.write(message + '\r\n') self.transport.loseConnection() threads.deferToThread(self.factory.action).addCallback(writeResponse) def connectionMade(self): self.lines = [] class ActionService(service.Service): def __init__(self, **kwargs): pass #self.users = kwargs def action(self): print "launching subprocess" sys.stdout.flush() p = subprocess.Popen(["ls"], stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE) print "launched subprocess, trying to communicate..." sys.stdout.flush() p.communicate() print "returning" sys.stdout.flush() return "%032d" % (0) def getActionFactory(self): f = protocol.ServerFactory() f.protocol = MyProtocol f.action = self.action return f reactor.suggestThreadPoolSize(300) application = service.Application('Action', uid=0, gid=0) f = ActionService() serviceCollection = service.IServiceCollection(application) internet.TCPServer(31337,f.getActionFactory() ).setServiceParent(serviceCollection) ...and here's some client code: #!/usr/bin/python import time import threading import socket def connectAction(host): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, 31337)) s.send("asdf\r\n") resp = s.recv(32) s.close() return resp class sscceThread(threading.Thread): def __init__(self, host): self.host = host threading.Thread.__init__(self) def run(self): connectAction(self.host) def main(): threads = [] for i in range(0, 1000): for j in range(0,5): t = sscceThread("localhost") t.start() threads.append(t) for t in threads: t.join() print i time.sleep(1) # print i if __name__ == "__main__": main() Start the service by running: twistd -y sscce_twisted_service.py -l twistdLog; tail -f twistdLog And run the client by running: ./sscce_twisted_client.py You should see the client go for a couple of iterations (I've seen it go as many as 10) and then hang. The client code contains a 1-second sleep so that you can tell the difference between twisted log entries from each iteration and on the one that hangs you'll see something like this in the twisted log: 2009-12-22 11:18:47-0800 [MyProtocol,55,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,56,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,55,127.0.0.1] launched subprocess, trying to communicate... 2009-12-22 11:18:47-0800 [MyProtocol,57,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,58,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,56,127.0.0.1] launched subprocess, trying to communicate... 2009-12-22 11:18:47-0800 [MyProtocol,55,127.0.0.1] returning 2009-12-22 11:18:47-0800 [MyProtocol,57,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,56,127.0.0.1] launching subprocess returning 2009-12-22 11:18:47-0800 [MyProtocol,59,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,58,127.0.0.1] launched subprocess, trying to communicate... 2009-12-22 11:18:47-0800 [MyProtocol,58,127.0.0.1] returning 2009-12-22 11:18:47-0800 [MyProtocol,59,127.0.0.1] launched subprocess, trying to communicate... 2009-12-22 11:18:47-0800 [MyProtocol,59,127.0.0.1] returning Of particular note is MyProtocol,57. It says it was about to try launching the subprocess but it never printed the "launched subprocess, trying to communicate" line. I think it must have hung there. A: As mg said in his comment, don't use the subprocess module. On POSIX platforms, it's necessary (more or less) to handle the SIGCHLD signal to deal with child processes that exit. Since there can only be one SIGCHLD handler, multiple libraries generally won't cooperate. Twisted's child process support and the subprocess module's support conflict. Either use Twisted's support (see http://twistedmatrix.com/documents/current/core/howto/process.html) or disable Twisted's support by passing installSignalHandlers=False to reactor.run (I recommend the former, as subprocess presents blocking interfaces which don't integrate well into Twisted-based applications).
twisted threading with subprocess.Popen?
I'm trying to implement a service with Twisted that's fairly close to the "finger" tutorial found here: http://twistedmatrix.com/documents/current/core/howto/tutorial/intro.html I've got a basic.LineListener waiting for a command and then executing it, then I have a client connecting and issuing commands. Trouble is that the command sometimes needs to execute something else and I'm using python's subprocess module for that. It's not just that calls to communicate() are hanging, that's a normal subprocess issue and I know how to get past it. It's that subprocess.Popen calls are hanging. Here's the twisted server code: from twisted.application import internet, service from twisted.internet import protocol, reactor, defer, threads from twisted.protocols import basic import sys import time import subprocess class MyProtocol(basic.LineReceiver): def lineReceived(self, line): self.go() def go(self): def writeResponse(message): self.transport.write(message + '\r\n') self.transport.loseConnection() threads.deferToThread(self.factory.action).addCallback(writeResponse) def connectionMade(self): self.lines = [] class ActionService(service.Service): def __init__(self, **kwargs): pass #self.users = kwargs def action(self): print "launching subprocess" sys.stdout.flush() p = subprocess.Popen(["ls"], stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE) print "launched subprocess, trying to communicate..." sys.stdout.flush() p.communicate() print "returning" sys.stdout.flush() return "%032d" % (0) def getActionFactory(self): f = protocol.ServerFactory() f.protocol = MyProtocol f.action = self.action return f reactor.suggestThreadPoolSize(300) application = service.Application('Action', uid=0, gid=0) f = ActionService() serviceCollection = service.IServiceCollection(application) internet.TCPServer(31337,f.getActionFactory() ).setServiceParent(serviceCollection) ...and here's some client code: #!/usr/bin/python import time import threading import socket def connectAction(host): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, 31337)) s.send("asdf\r\n") resp = s.recv(32) s.close() return resp class sscceThread(threading.Thread): def __init__(self, host): self.host = host threading.Thread.__init__(self) def run(self): connectAction(self.host) def main(): threads = [] for i in range(0, 1000): for j in range(0,5): t = sscceThread("localhost") t.start() threads.append(t) for t in threads: t.join() print i time.sleep(1) # print i if __name__ == "__main__": main() Start the service by running: twistd -y sscce_twisted_service.py -l twistdLog; tail -f twistdLog And run the client by running: ./sscce_twisted_client.py You should see the client go for a couple of iterations (I've seen it go as many as 10) and then hang. The client code contains a 1-second sleep so that you can tell the difference between twisted log entries from each iteration and on the one that hangs you'll see something like this in the twisted log: 2009-12-22 11:18:47-0800 [MyProtocol,55,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,56,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,55,127.0.0.1] launched subprocess, trying to communicate... 2009-12-22 11:18:47-0800 [MyProtocol,57,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,58,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,56,127.0.0.1] launched subprocess, trying to communicate... 2009-12-22 11:18:47-0800 [MyProtocol,55,127.0.0.1] returning 2009-12-22 11:18:47-0800 [MyProtocol,57,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,56,127.0.0.1] launching subprocess returning 2009-12-22 11:18:47-0800 [MyProtocol,59,127.0.0.1] launching subprocess 2009-12-22 11:18:47-0800 [MyProtocol,58,127.0.0.1] launched subprocess, trying to communicate... 2009-12-22 11:18:47-0800 [MyProtocol,58,127.0.0.1] returning 2009-12-22 11:18:47-0800 [MyProtocol,59,127.0.0.1] launched subprocess, trying to communicate... 2009-12-22 11:18:47-0800 [MyProtocol,59,127.0.0.1] returning Of particular note is MyProtocol,57. It says it was about to try launching the subprocess but it never printed the "launched subprocess, trying to communicate" line. I think it must have hung there.
[ "As mg said in his comment, don't use the subprocess module. On POSIX platforms, it's necessary (more or less) to handle the SIGCHLD signal to deal with child processes that exit. Since there can only be one SIGCHLD handler, multiple libraries generally won't cooperate. Twisted's child process support and the subprocess module's support conflict. Either use Twisted's support (see http://twistedmatrix.com/documents/current/core/howto/process.html) or disable Twisted's support by passing installSignalHandlers=False to reactor.run (I recommend the former, as subprocess presents blocking interfaces which don't integrate well into Twisted-based applications).\n" ]
[ 7 ]
[]
[]
[ "multithreading", "python", "subprocess", "twisted" ]
stackoverflow_0001948641_multithreading_python_subprocess_twisted.txt
Q: RabbitMQ gives a "access refused, login refused for user" error when attempting to follow the celery tutorial I'm attempting to follow the celery tutorial, but I run into a problem when I run python manage.py celeryd: my RabbitMQ server (installed on a virtual machine on my dev box) won't let my user login. I get the following on my Django management console: [ERROR/MainProcess] AMQP Listener: Connection Error: Socket closed. Trying again in 2 seconds... and this shows up in my rabbit.log file on my RabbitMQ server: exception on TCP connection <0.5814.0> from $DJANGO_BOX_IP {channel0_error,starting,{amqp,access_refused,"login refused for user '$CONFIGURED_USER'",'connection.start_ok'}} I've double-checked my user, permissions, and vhost info, and they all seem to match up. Any help troubleshooting is greatly appreciated. UPDATE: Following the advice of @asksol I get the following traceback: $MY_VIRTUAL_ENV/lib/python2.6/site-packages/carrot/connection.pyc in connection(self) 118 return 119 if not self._connection: --> 120 self._connection = self._establish_connection() 121 self._closed = False 122 return self._connection $MY_VIRTUAL_ENV/lib/python2.6/site-packages/carrot/connection.pyc in _establish_connection(self) 131 132 def _establish_connection(self): --> 133 return self.create_backend().establish_connection() 134 135 def get_backend_cls(self): $MY_VIRTUAL_ENV/lib/python2.6/site-packages/carrot/backends/pyamqplib.pyc in establish_connection(self) 110 insist=conninfo.insist, 111 ssl=conninfo.ssl, --> 112 connect_timeout=conninfo.connect_timeout) 113 114 def close_connection(self, connection): $MY_VIRTUAL_ENV/lib/python2.6/site-packages/amqplib/client_0_8/connection.pyc in __init__(self, host, userid, password, login_method, login_response, virtual_host, locale, client_properties, ssl, insist, connect_timeout, **kwargs) 138 self.wait(allowed_methods=[ 139 (10, 20), # secure --> 140 (10, 30), # tune 141 ]) 142 $MY_VIRTUAL_ENV/lib/python2.6/site-packages/amqplib/client_0_8/abstract_channel.pyc in wait(self, allowed_methods) 88 method_sig, args, content = self.connection._wait_method( ---> 89 self.channel_id, allowed_methods) 90 91 if content \ $MY_VIRTUAL_ENV/lib/python2.6/site-packages/amqplib/client_0_8/connection.pyc in _wait_method(self, channel_id, allowed_methods) 196 while True: 197 channel, method_sig, args, content = \ --> 198 self.method_reader.read_method() 199 200 if (channel == channel_id) \ $MY_VIRTUAL_ENV/lib/python2.6/site-packages/amqplib/client_0_8/method_framing.pyc in read_method(self) 213 m = self.queue.get() 214 if isinstance(m, Exception): --> 215 raise m 216 return m 217 IOError: Socket closed A: Are you running django? If so, then try this: >>> from carrot.connection import DjangoBrokerConnection >>> c = DjangoBrokerConnection() >>> c.connection Does it give the same thing? Are you sure you're connecting to the right hostname, and that the username and password has access to the virtual host? UPDATE: >>> from carrot.connection import DjangoBrokerConnection >>> c = DjangoBrokerConnection() >>> for n in ("host", "userid", "password", "virtual_host", "ssl"): ... print("%s -> %s" % (n, repr(getattr(c, n, None)))) UPDATE: You have to do the above before running c.connection, as the connection is established lazily in carrot.
RabbitMQ gives a "access refused, login refused for user" error when attempting to follow the celery tutorial
I'm attempting to follow the celery tutorial, but I run into a problem when I run python manage.py celeryd: my RabbitMQ server (installed on a virtual machine on my dev box) won't let my user login. I get the following on my Django management console: [ERROR/MainProcess] AMQP Listener: Connection Error: Socket closed. Trying again in 2 seconds... and this shows up in my rabbit.log file on my RabbitMQ server: exception on TCP connection <0.5814.0> from $DJANGO_BOX_IP {channel0_error,starting,{amqp,access_refused,"login refused for user '$CONFIGURED_USER'",'connection.start_ok'}} I've double-checked my user, permissions, and vhost info, and they all seem to match up. Any help troubleshooting is greatly appreciated. UPDATE: Following the advice of @asksol I get the following traceback: $MY_VIRTUAL_ENV/lib/python2.6/site-packages/carrot/connection.pyc in connection(self) 118 return 119 if not self._connection: --> 120 self._connection = self._establish_connection() 121 self._closed = False 122 return self._connection $MY_VIRTUAL_ENV/lib/python2.6/site-packages/carrot/connection.pyc in _establish_connection(self) 131 132 def _establish_connection(self): --> 133 return self.create_backend().establish_connection() 134 135 def get_backend_cls(self): $MY_VIRTUAL_ENV/lib/python2.6/site-packages/carrot/backends/pyamqplib.pyc in establish_connection(self) 110 insist=conninfo.insist, 111 ssl=conninfo.ssl, --> 112 connect_timeout=conninfo.connect_timeout) 113 114 def close_connection(self, connection): $MY_VIRTUAL_ENV/lib/python2.6/site-packages/amqplib/client_0_8/connection.pyc in __init__(self, host, userid, password, login_method, login_response, virtual_host, locale, client_properties, ssl, insist, connect_timeout, **kwargs) 138 self.wait(allowed_methods=[ 139 (10, 20), # secure --> 140 (10, 30), # tune 141 ]) 142 $MY_VIRTUAL_ENV/lib/python2.6/site-packages/amqplib/client_0_8/abstract_channel.pyc in wait(self, allowed_methods) 88 method_sig, args, content = self.connection._wait_method( ---> 89 self.channel_id, allowed_methods) 90 91 if content \ $MY_VIRTUAL_ENV/lib/python2.6/site-packages/amqplib/client_0_8/connection.pyc in _wait_method(self, channel_id, allowed_methods) 196 while True: 197 channel, method_sig, args, content = \ --> 198 self.method_reader.read_method() 199 200 if (channel == channel_id) \ $MY_VIRTUAL_ENV/lib/python2.6/site-packages/amqplib/client_0_8/method_framing.pyc in read_method(self) 213 m = self.queue.get() 214 if isinstance(m, Exception): --> 215 raise m 216 return m 217 IOError: Socket closed
[ "Are you running django?\nIf so, then try this:\n>>> from carrot.connection import DjangoBrokerConnection\n>>> c = DjangoBrokerConnection()\n>>> c.connection\n\nDoes it give the same thing?\nAre you sure you're connecting to the right hostname, and that the username and password has access to the virtual host?\nUPDATE:\n>>> from carrot.connection import DjangoBrokerConnection\n>>> c = DjangoBrokerConnection()\n>>> for n in (\"host\", \"userid\", \"password\", \"virtual_host\", \"ssl\"):\n... print(\"%s -> %s\" % (n, repr(getattr(c, n, None))))\n\nUPDATE: You have to do the above before running c.connection, as the connection is established lazily in carrot.\n" ]
[ 5 ]
[]
[]
[ "amqp", "celery", "django", "python", "rabbitmq" ]
stackoverflow_0001878306_amqp_celery_django_python_rabbitmq.txt
Q: Parsing an html file and adding found images to a zip file I am trying to parse an html for all its img tags, download all the images pointed to by src, and then add those files to a zip file. I would prefer to do all this in memory since I can guarantee there won't be that many images. Assume the images variable is already populated from parsing the html. What I need help with is getting the images into the zipfile. from zipfile import ZipFile from StringIO import StringIO from urllib2 import urlopen s = StringIO() zip_file = ZipFile(s, 'w') try: for image in images: internet_image = urlopen(image) zip_file.writestr('some-image.jpg', internet_image.fp.read()) # it is not obvious why I have to use writestr() instead of write() finally: zip_file.close() A: I'm not quite sure what you're asking here, since you appear to have most of it sorted. Have you investigated HtmlParser to actually perform the HTML parsing ? I wouldn't try hand-rolling a parser yourself - it's a major task with numerous edge cases. Don't even think about regexps for anything but the most trivial cases. For each <img/> tag you can use HttpLib to actually get each image. It may be worth getting the images in multiple threads to speed up the compilation of the zip file. A: The easiest way I can think of to do this would be to use the BeautifulSoup library. Something along the lines of: from BeautifulSoup import BeautifulSoup from collections import defaultdict def getImgSrces(html): srcs = [] soup = BeautifulSoup(html) for tag in soup('img'): attrs = defaultdict(str) for attr in tag.attrs: attrs[ attr[0] ] = attr[1] attrs = dict(attrs) if 'src' in attrs.keys(): srcs.append( attrs['src'] ) return srcs That should give you a list of URLs derived from your img tags to loop through. A: To answer your specific question about how you create the ZIP archive (others here have discussed parsing the URLs), I tested out your code. You are really remarkably close to having a finished product already. Here's how I would augment what you have to create a Zip archive (in this example, I'm writing the archive to the drive so that I can verify it was properly written). from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED import zlib from cStringIO import StringIO from urllib2 import urlopen from urlparse import urlparse from os import path images = ['http://sstatic.net/so/img/logo.png', 'http://sstatic.net/so/Img/footer-cc-wiki-peak-internet.png'] buf = StringIO() # By default, zip archives are not compressed... adding ZIP_DEFLATED # to achieve that. If you don't want that, or don't have zlib on or # system, delete the compression kwarg zip_file = ZipFile(buf, mode='w', compression=ZIP_DEFLATED) for image in images: internet_image = urlopen(image) fname = path.basename(urlparse(image).path) zip_file.writestr(fname, internet_image.read()) zip_file.close() output = open('images.zip', 'wb') output.write(buf.getvalue()) output.close() buf.close()
Parsing an html file and adding found images to a zip file
I am trying to parse an html for all its img tags, download all the images pointed to by src, and then add those files to a zip file. I would prefer to do all this in memory since I can guarantee there won't be that many images. Assume the images variable is already populated from parsing the html. What I need help with is getting the images into the zipfile. from zipfile import ZipFile from StringIO import StringIO from urllib2 import urlopen s = StringIO() zip_file = ZipFile(s, 'w') try: for image in images: internet_image = urlopen(image) zip_file.writestr('some-image.jpg', internet_image.fp.read()) # it is not obvious why I have to use writestr() instead of write() finally: zip_file.close()
[ "I'm not quite sure what you're asking here, since you appear to have most of it sorted. \nHave you investigated HtmlParser to actually perform the HTML parsing ? I wouldn't try hand-rolling a parser yourself - it's a major task with numerous edge cases. Don't even think about regexps for anything but the most trivial cases.\nFor each <img/> tag you can use HttpLib to actually get each image. It may be worth getting the images in multiple threads to speed up the compilation of the zip file.\n", "The easiest way I can think of to do this would be to use the BeautifulSoup library.\nSomething along the lines of:\nfrom BeautifulSoup import BeautifulSoup\nfrom collections import defaultdict\n\ndef getImgSrces(html):\n srcs = []\n soup = BeautifulSoup(html)\n\n for tag in soup('img'):\n attrs = defaultdict(str)\n for attr in tag.attrs:\n attrs[ attr[0] ] = attr[1]\n attrs = dict(attrs)\n\n if 'src' in attrs.keys():\n srcs.append( attrs['src'] )\n\n return srcs\n\nThat should give you a list of URLs derived from your img tags to loop through.\n", "To answer your specific question about how you create the ZIP archive (others here have discussed parsing the URLs), I tested out your code. You are really remarkably close to having a finished product already. \nHere's how I would augment what you have to create a Zip archive (in this example, I'm writing the archive to the drive so that I can verify it was properly written).\nfrom zipfile import ZipFile, ZipInfo, ZIP_DEFLATED\nimport zlib\nfrom cStringIO import StringIO\nfrom urllib2 import urlopen\nfrom urlparse import urlparse\nfrom os import path\n\nimages = ['http://sstatic.net/so/img/logo.png', \n 'http://sstatic.net/so/Img/footer-cc-wiki-peak-internet.png']\n\nbuf = StringIO()\n# By default, zip archives are not compressed... adding ZIP_DEFLATED\n# to achieve that. If you don't want that, or don't have zlib on or\n# system, delete the compression kwarg\nzip_file = ZipFile(buf, mode='w', compression=ZIP_DEFLATED)\n\nfor image in images:\n internet_image = urlopen(image)\n fname = path.basename(urlparse(image).path) \n zip_file.writestr(fname, internet_image.read())\n\nzip_file.close()\n\noutput = open('images.zip', 'wb')\noutput.write(buf.getvalue())\noutput.close()\nbuf.close()\n\n" ]
[ 1, 1, 1 ]
[]
[]
[ "python", "zip" ]
stackoverflow_0001949549_python_zip.txt
Q: What is a good & free game engine? For C++, Java, or Python, what are some good game + free game engines that are easy to pick up? Any type of game engine is okay. I just want to get started somewhere by looking into different game engines and their capabilities. A: For my Computer Graphics course in College we used the open source OGRE 3D engine. Not only is this an extremely robust 3D engine but it was a blast! Develop a medium sized game using it and you will get a good taste of many of the different game programming specialties. You'll find yourself doing 3d modeling, sound effects, physics programming, AI, the works. alt text http://www.mactabilisarts.com/Images/multiplayer%20games.jpg Screenshot of a recent OGRE 3D Game A: Java hasn't got any love here? For 2D and 3D OpenGL on win/mac/linux/android, try libgdx. For 2D with API similar to Java2D try Slick. LWJGL for pure OpenGL bindings. Ardor3D or JMonkeyEngine for a higher level 3D library. For networking, KryoNet. A: I would suggest pygame It has work well for me in the past. It is very easy to use and comes with the bonus of python :) It has an active community and works on both Unix and Windows. (I haven't tried it on Mac) A: For python game development I would look into using panda3d. A: Not really the language you want but I still think it's a good engine: LΓΆve, and it's written in Lua. A: Python I've ditched Pygame and started using Pyglet. It is extremely easy to play around with, it is nicely complete (OpenGL, mp3 support, image formats, joystick...), and it has a nice tutorial. A: If you are ready for deeper mechanics but greater freedom, have a look at Crystal Space (C++), if you want to use more already-prepared objects you can consider the Irrlicht Engine (C++ too). A: I'd recommend Ogre3D as well, it's rather extensive, cross-platform and you can add functionality like physics through existing add-ons - or write your own in C++. It is however a graphics engine, rather than a dedicated game engine, but the add-ons amend that. More importantly there are wrappers for Python (Python-Ogre), Java (ogre4j) and .Net (MOGRE). A: I heard good things about Ogre, but i haven't used it myself. In a completely different area, i think Blender has been complemented with interaction capabilities. A: Many open source projects are hosted on launchpad, some are games, and some of those use a 3rd party engine. Maybe you could have a look there? A: Garry's Mod was written using Half-Life 2's Source engine, presumably using the Hammer editor. Granted, this is arguably closer to level design than game design, but might be interesting regardless. A: On the Java front, check out jMonkeyEngine. It's got a lot of features including hardware acceleration using OpenGL. I haven't attempted to develop anything using it, but I've been following the community for a while; they did a demo and presentation a few JavaOnes ago. Moving from the client to the server, if you are interested in toolkits for building MMOGs, then check out Project Darkstar. It's a server-side framework (written in Java) with client-side SDKs for Java and C. The whole project is sponsored by Sun. A: If you're interested in 3D game programming, id Software of Doom and Quake fame often release the source code for their engines. You can find the source code for Quake I, II and III here and a substantial chunk of the Doom 3 code here and Quake IV here. A: There is a RPG engine called VERGE if you're interested. Never tried it but I heard good things from it. I think it's in C++.
What is a good & free game engine?
For C++, Java, or Python, what are some good game + free game engines that are easy to pick up? Any type of game engine is okay. I just want to get started somewhere by looking into different game engines and their capabilities.
[ "For my Computer Graphics course in College we used the open source OGRE 3D engine. Not only is this an extremely robust 3D engine but it was a blast! \nDevelop a medium sized game using it and you will get a good taste of many of the different game programming specialties. You'll find yourself doing 3d modeling, sound effects, physics programming, AI, the works. \nalt text http://www.mactabilisarts.com/Images/multiplayer%20games.jpg\nScreenshot of a recent OGRE 3D Game\n", "Java hasn't got any love here? For 2D and 3D OpenGL on win/mac/linux/android, try libgdx. For 2D with API similar to Java2D try Slick. LWJGL for pure OpenGL bindings. Ardor3D or JMonkeyEngine for a higher level 3D library. For networking, KryoNet.\n", "I would suggest pygame It has work well for me in the past. It is very easy to use and comes with the bonus of python :) \nIt has an active community and works on both Unix and Windows. (I haven't tried it on Mac)\n", "For python game development I would look into using panda3d.\n", "Not really the language you want but I still think it's a good engine: LΓΆve, and it's written in Lua.\n", "Python\nI've ditched Pygame and started using Pyglet.\nIt is extremely easy to play around with, it is nicely complete (OpenGL, mp3 support, image formats, joystick...), and it has a nice tutorial.\n", "If you are ready for deeper mechanics but greater freedom, have a look at Crystal Space (C++), if you want to use more already-prepared objects you can consider the Irrlicht Engine (C++ too).\n", "I'd recommend Ogre3D as well, it's rather extensive, cross-platform and you can add functionality like physics through existing add-ons - or write your own in C++. It is however a graphics engine, rather than a dedicated game engine, but the add-ons amend that.\nMore importantly there are wrappers for Python (Python-Ogre), Java (ogre4j) and .Net (MOGRE).\n", "I heard good things about Ogre, but i haven't used it myself.\nIn a completely different area, i think Blender has been complemented with interaction capabilities.\n", "Many open source projects are hosted on launchpad, some are games, and some of those use a 3rd party engine. Maybe you could have a look there?\n", "Garry's Mod was written using Half-Life 2's Source engine, presumably using the Hammer editor.\nGranted, this is arguably closer to level design than game design, but might be interesting regardless.\n", "On the Java front, check out jMonkeyEngine. It's got a lot of features including hardware acceleration using OpenGL. I haven't attempted to develop anything using it, but I've been following the community for a while; they did a demo and presentation a few JavaOnes ago.\nMoving from the client to the server, if you are interested in toolkits for building MMOGs, then check out Project Darkstar. It's a server-side framework (written in Java) with client-side SDKs for Java and C. The whole project is sponsored by Sun.\n", "If you're interested in 3D game programming, id Software of Doom and Quake fame often release the source code for their engines. You can find the source code for Quake I, II and III here and a substantial chunk of the Doom 3 code here and Quake IV here.\n", "There is a RPG engine called VERGE if you're interested. Never tried it but I heard good things from it. \nI think it's in C++.\n" ]
[ 17, 14, 13, 5, 3, 3, 2, 2, 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "c++", "java", "python" ]
stackoverflow_0000564469_c++_java_python.txt
Q: Which is a more functional programming language, Haskell or Python? Had learned Haskell during a Functional Programming course in school. Had found Haskell a bit difficult to work with. Have now worked a lot on Python. Python is quite easy to work with. Python does support some functional programming constructs. Was thinking of revisiting Functional Programming. What would be a better language to code? Haskell or Python? Why? A: Haskell is a functional programming language, whereas Python just has some features of functional programming languages. So, this is settled. Q.e.d. Edit: What is lacking in Python, just to give one example, is the optimization of recursive function calls. This is vital in most real functional programming languages. Googling, by the way, just produced this nice article. A: You'll find many criticisms elsewhere about how Python programmers should not use functional features like lambda. Alex Martelli is particularly good at this. But if you approach functional programming as a Python programmer, you will not get much of a feel for why people are interested in functional programming in the first place. In particular, you will not have access to a powerful static type system and algebraic data types. These tools are definitely part of the Haskell mindset. Functional programming is not so much a set of features a a way of thinking. To see that way of thinking in action and to start to learn it, check out the paper Why Functional Programming Matters by John Hughes. What you learn from Hughes you can easily apply in Haskell. In fact, Haskell is much more likely to force you to learn that new way of thinking. With Python you can use a few lambdas here and there and fool yourself that you're learning functional programming. You won't be. That said, Haskell can be a lot to swallow all at once. If you're finding it difficult you might want to try Standard ML or Racket (formerly called PLT Scheme or DrScheme). Standard ML will introduce you to more new ideas, but those people don't have their act together to welcome newcomers in the way that the Racketeers or the Haskell people do. A: This question highlights one of my pet peeves about the common understanding of functional programming. Having language features like closures and first-class functions do not make a language a functional programming language. Functional programming is as much about a specific style of programming as it is about specific language constructs. Python has closures, first-class functions, and yes, even a function called "map", but the language itself encourages a procedural, OOP, imperative style of programming; so even if you make use of the functional features, you're still programming imperatively. As a purely functional language, Haskell basically mandates that one program in a declarative, functional style, so hands-down, Haskell is "more functional" than Python. A: While Python does indeed support some functional constructs, Haskell is a functional language. What you also need to consider, is that Haskell is also purely functional and lazy, two concepts that may be the cause of the difficulty you find in Haskell. If this is the case, read on. What you may want to consider, if, of course, you have the time, is learning another, less complex, functional language. I found that learning a less "aggressively functional" language before moving on to Haskell is a step worth taking. You may want to consider OCaml (Objective Caml), another functional programming language, that is not pure nor lazy. Thus, some imperative programming constructs will be available to you (references, loops, mutable arrays, etc), and you won't have to cope with the monads until you actually want to. This entirely depends on the time you are willing to spend revisiting functional programming, and on your current background in this same paradigm. A: What Boldewyn said. Haskell is one of the most "hardcore" functional languages there is, insofar as there simply isn't any way to maintain mutable state. That said, Haskell is (unsurprisingly) wildly different from all the imperative and mixed-model languages most people come in contact with, so there would be a learning curve involved in picking it up if one came from a background of, say, VB or C(++) or Java. Python, on the other hand, features a "Functional Show and Tell" section where a handful of functional features can be test driven within an otherwise predominantly imperative environment. Thus, if in his original question, the OP's "better" meant "more functional" or "a better citizen of functional-land" (as he has since made clearer), then Haskell "wins" hands down.
Which is a more functional programming language, Haskell or Python?
Had learned Haskell during a Functional Programming course in school. Had found Haskell a bit difficult to work with. Have now worked a lot on Python. Python is quite easy to work with. Python does support some functional programming constructs. Was thinking of revisiting Functional Programming. What would be a better language to code? Haskell or Python? Why?
[ "Haskell is a functional programming language, whereas Python just has some features of functional programming languages. So, this is settled. Q.e.d.\nEdit: What is lacking in Python, just to give one example, is the optimization of recursive function calls. This is vital in most real functional programming languages. \nGoogling, by the way, just produced this nice article.\n", "You'll find many criticisms elsewhere about how Python programmers should not use functional features like lambda. Alex Martelli is particularly good at this. But if you approach functional programming as a Python programmer, you will not get much of a feel for why people are interested in functional programming in the first place. In particular, you will not have access to a powerful static type system and algebraic data types. These tools are definitely part of the Haskell mindset.\nFunctional programming is not so much a set of features a a way of thinking. To see that way of thinking in action and to start to learn it, check out the paper Why Functional Programming Matters by John Hughes. What you learn from Hughes you can easily apply in Haskell. In fact, Haskell is much more likely to force you to learn that new way of thinking. With Python you can use a few lambdas here and there and fool yourself that you're learning functional programming. You won't be.\nThat said, Haskell can be a lot to swallow all at once. If you're finding it difficult you might want to try Standard ML or Racket (formerly called PLT Scheme or DrScheme). Standard ML will introduce you to more new ideas, but those people don't have their act together to welcome newcomers in the way that the Racketeers or the Haskell people do.\n", "This question highlights one of my pet peeves about the common understanding of functional programming. Having language features like closures and first-class functions do not make a language a functional programming language. Functional programming is as much about a specific style of programming as it is about specific language constructs. Python has closures, first-class functions, and yes, even a function called \"map\", but the language itself encourages a procedural, OOP, imperative style of programming; so even if you make use of the functional features, you're still programming imperatively.\nAs a purely functional language, Haskell basically mandates that one program in a declarative, functional style, so hands-down, Haskell is \"more functional\" than Python.\n", "While Python does indeed support some functional constructs, Haskell is a functional language. What you also need to consider, is that Haskell is also purely functional and lazy, two concepts that may be the cause of the difficulty you find in Haskell. If this is the case, read on.\nWhat you may want to consider, if, of course, you have the time, is learning another, less complex, functional language. I found that learning a less \"aggressively functional\" language before moving on to Haskell is a step worth taking. You may want to consider OCaml (Objective Caml), another functional programming language, that is not pure nor lazy. Thus, some imperative programming constructs will be available to you (references, loops, mutable arrays, etc), and you won't have to cope with the monads until you actually want to.\nThis entirely depends on the time you are willing to spend revisiting functional programming, and on your current background in this same paradigm.\n", "What Boldewyn said. Haskell is one of the most \"hardcore\" functional languages there is, insofar as there simply isn't any way to maintain mutable state.\nThat said, Haskell is (unsurprisingly) wildly different from all the imperative and mixed-model languages most people come in contact with, so there would be a learning curve involved in picking it up if one came from a background of, say, VB or C(++) or Java.\nPython, on the other hand, features a \"Functional Show and Tell\" section where a handful of functional features can be test driven within an otherwise predominantly imperative environment.\nThus, if in his original question, the OP's \"better\" meant \"more functional\" or \"a better citizen of functional-land\" (as he has since made clearer), then Haskell \"wins\" hands down.\n" ]
[ 38, 33, 11, 7, 0 ]
[ "From the Haskell homepage:\n\nHaskell is an advanced purely functional programming language. An open source product of more than twenty years of cutting edge research, it allows rapid development of robust, concise, correct software. \n\nSarcastic translation: \n\n\"advanced\" = \"Not for everyone\"\n\"purely functional\" = \"Definitely not for everyone\"\n\"more than twenty years\" = \"And still not everyone likes it!\"\n\"cutting edge research\" = \"There is a chance that you may find a practical problem which you can solve with it but we're still working on it!\"\n\"robust, concise, correct software\" = \"Are you missing simple, understandable, obvious, readable? Guess why!\"\n\nJokes aside, functional languages aren't meant for the majority and never will be. There are people who can think like a stack but I, for one, prefer that the computer tries harder to understand my gibberish.\n" ]
[ -3 ]
[ "functional_programming", "haskell", "python" ]
stackoverflow_0001945634_functional_programming_haskell_python.txt
Q: Is the Python 3.x signal library for Windows incomplete? I went to write a system script using 3.0 and found the SIGALRM signal and signal.alarm() call missing amongst many others on the Windows deployment. Does anyone know why these are missing? Below is a dir() of the 2.5 vs 3.0 signal packages on windows. I haven't found any 3.0 docs yet mentioning that this was moved EDIT: signals do work in python25 on windows, they were removed in 3.0. I should reword my request as 'where did they go or get turned into' or is the windows 3.0 release just not complete yet? python25> python Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import signal >>> dir(signal) ['NSIG', 'SIGABRT', 'SIGALRM', 'SIGBUS', 'SIGCHLD', 'SIGCLD', 'SIGCONT', 'SIGEMT', 'SIGFPE', 'SIGHUP', 'SIGILL', 'SIGINT ', 'SIGIO', 'SIGKILL', 'SIGPIPE', 'SIGPOLL', 'SIGPROF', 'SIGQUIT', 'SIGRTMAX', 'SIGRTMIN', 'SIGSEGV', 'SIGSTOP', 'SIGSYS ', 'SIGTERM', 'SIGTRAP', 'SIGTSTP', 'SIGTTIN', 'SIGTTOU', 'SIGURG', 'SIGUSR1', 'SIGUSR2', 'SIGVTALRM', 'SIGWINCH', 'SIGX CPU', 'SIGXFSZ', 'SIG_DFL', 'SIG_IGN', '__doc__', '__name__', 'alarm', 'default_int_handler', 'getsignal', 'pause', 'sig nal'] >>> exit() python25> cd ../python31 python31> python Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import signal >>> dir(signal) ['NSIG', 'SIGABRT', 'SIGBREAK', 'SIGFPE', 'SIGILL', 'SIGINT', 'SIGSEGV', 'SIGTERM', 'SIG_DFL', 'SIG_IGN', '__doc__', '__ name__', '__package__', 'default_int_handler', 'getsignal', 'set_wakeup_fd', 'signal'] >>> A: Windows is NOT posix compliant OS so it does not have all signals - my guess is that on 3.0 the missing signals do not show up there any longer. A: It seems you are running your 2.5 in cygwin, which is probably the reason that it shows up there. Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin In my 2.5 for win32 it looks just like in your 3.1: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import signal >>> dir(signal) ['NSIG', 'SIGABRT', 'SIGBREAK', 'SIGFPE', 'SIGILL', 'SIGINT', 'SIGSEGV', 'SIGTERM', 'SIG_DFL', 'SIG_IGN', '__doc__', '__ name__', 'default_int_handler', 'getsignal', 'signal']
Is the Python 3.x signal library for Windows incomplete?
I went to write a system script using 3.0 and found the SIGALRM signal and signal.alarm() call missing amongst many others on the Windows deployment. Does anyone know why these are missing? Below is a dir() of the 2.5 vs 3.0 signal packages on windows. I haven't found any 3.0 docs yet mentioning that this was moved EDIT: signals do work in python25 on windows, they were removed in 3.0. I should reword my request as 'where did they go or get turned into' or is the windows 3.0 release just not complete yet? python25> python Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import signal >>> dir(signal) ['NSIG', 'SIGABRT', 'SIGALRM', 'SIGBUS', 'SIGCHLD', 'SIGCLD', 'SIGCONT', 'SIGEMT', 'SIGFPE', 'SIGHUP', 'SIGILL', 'SIGINT ', 'SIGIO', 'SIGKILL', 'SIGPIPE', 'SIGPOLL', 'SIGPROF', 'SIGQUIT', 'SIGRTMAX', 'SIGRTMIN', 'SIGSEGV', 'SIGSTOP', 'SIGSYS ', 'SIGTERM', 'SIGTRAP', 'SIGTSTP', 'SIGTTIN', 'SIGTTOU', 'SIGURG', 'SIGUSR1', 'SIGUSR2', 'SIGVTALRM', 'SIGWINCH', 'SIGX CPU', 'SIGXFSZ', 'SIG_DFL', 'SIG_IGN', '__doc__', '__name__', 'alarm', 'default_int_handler', 'getsignal', 'pause', 'sig nal'] >>> exit() python25> cd ../python31 python31> python Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import signal >>> dir(signal) ['NSIG', 'SIGABRT', 'SIGBREAK', 'SIGFPE', 'SIGILL', 'SIGINT', 'SIGSEGV', 'SIGTERM', 'SIG_DFL', 'SIG_IGN', '__doc__', '__ name__', '__package__', 'default_int_handler', 'getsignal', 'set_wakeup_fd', 'signal'] >>>
[ "Windows is NOT posix compliant OS so it does not have all signals - my guess is that on 3.0 the missing signals do not show up there any longer.\n", "It seems you are running your 2.5 in cygwin, which is probably the reason that it shows up there.\nPython 2.5.1 (r251:54863, May 18 2007, 16:56:43)\n[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin\n\nIn my 2.5 for win32 it looks just like in your 3.1:\nPython 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import signal\n>>> dir(signal)\n['NSIG', 'SIGABRT', 'SIGBREAK', 'SIGFPE', 'SIGILL', 'SIGINT', 'SIGSEGV', 'SIGTERM', 'SIG_DFL', 'SIG_IGN', '__doc__', '__\nname__', 'default_int_handler', 'getsignal', 'signal']\n\n" ]
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001948862_python.txt
Q: wxPython file dialog error: missing "|" in the wildcard string! I am on Windows7, using Python 2.6 and wxPython 2.8.10.1. I am trying to get this Open File dialog to work but am running into a weird error. This looks like a valid wildcard string to me, but whenever I choose a file and click 'Ok' on the File Dialog, I get this: Traceback (most recent call last): File "D:\Projects\python\wxTest.py", line 92, in OnOpen self.__DoOpen() File "D:\Projects\python\wxTest.py", line 101, in __DoOpen if open_dlg.ShowModal() == wx.ID_OK: File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 711, in ShowModal return _windows_.Dialog_ShowModal(*args, **kwargs) wx._core.PyAssertionError: C++ assertion "wxAssertFailure" failed at ..\..\src\common\filefn.cpp(1746) in wxParseCommonDialogsFilter(): missing '|' in the wildcard string! When the dialog is open everything looks fine. Any ideas? EDIT: typing too fast, forgot to include the wildcard string in question! sorry... wcd = "All files(*.*)|*.*|Text files (*.txt)|*.txt|" open_dlg = wx.FileDialog(self, message='Choose a file', defaultDir=directory, defaultFile='', style=wx.OPEN | wx.CHANGE_DIR) open_dlg.SetWildcard(wcd) if open_dlg.ShowModal() == wx.ID_OK: path = open_dlg.GetPath() ... A: The wildcard string has a quirky format, borrowed from Win32: Desc1|wildcard1|Desc2|wildcard2 ... There should be an odd number of pipes, so that the pipe-separated pieces form pairs, a description, and a wildcard. For example: Spreadsheet (*.xls)|*.xls|Plain-old text (*.txt)|*.txt|Random noise|*.dat Note that the description often contains a parenthetical wildcard just for display purposes. Your problem is the trailing pipe symbol. Remove it.
wxPython file dialog error: missing "|" in the wildcard string!
I am on Windows7, using Python 2.6 and wxPython 2.8.10.1. I am trying to get this Open File dialog to work but am running into a weird error. This looks like a valid wildcard string to me, but whenever I choose a file and click 'Ok' on the File Dialog, I get this: Traceback (most recent call last): File "D:\Projects\python\wxTest.py", line 92, in OnOpen self.__DoOpen() File "D:\Projects\python\wxTest.py", line 101, in __DoOpen if open_dlg.ShowModal() == wx.ID_OK: File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 711, in ShowModal return _windows_.Dialog_ShowModal(*args, **kwargs) wx._core.PyAssertionError: C++ assertion "wxAssertFailure" failed at ..\..\src\common\filefn.cpp(1746) in wxParseCommonDialogsFilter(): missing '|' in the wildcard string! When the dialog is open everything looks fine. Any ideas? EDIT: typing too fast, forgot to include the wildcard string in question! sorry... wcd = "All files(*.*)|*.*|Text files (*.txt)|*.txt|" open_dlg = wx.FileDialog(self, message='Choose a file', defaultDir=directory, defaultFile='', style=wx.OPEN | wx.CHANGE_DIR) open_dlg.SetWildcard(wcd) if open_dlg.ShowModal() == wx.ID_OK: path = open_dlg.GetPath() ...
[ "The wildcard string has a quirky format, borrowed from Win32:\nDesc1|wildcard1|Desc2|wildcard2 ...\n\nThere should be an odd number of pipes, so that the pipe-separated pieces form pairs, a description, and a wildcard. For example:\nSpreadsheet (*.xls)|*.xls|Plain-old text (*.txt)|*.txt|Random noise|*.dat\n\nNote that the description often contains a parenthetical wildcard just for display purposes.\nYour problem is the trailing pipe symbol. Remove it.\n" ]
[ 7 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001950454_python_wxpython.txt
Q: Python: Split list into list of dicts? Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list: data = ['ID:0:0:0', 'Status:Ok', 'Name:PhysicalDisk0:0:0', 'State:Online', 'FailurePredicted:No', 'ID:0:0:1', 'Status:Ok', 'Name:PhysicalDisk0:0:1', 'State:Online', 'FailurePredicted:No'] Finished list of dicts: [{'Status': 'Ok', 'State': 'Online', 'ID': '0:0:0', 'FailurePredicted': 'No', 'Name': 'PhysicalDisk0:0:0'}, {'Status': 'Ok', 'State': 'Online', 'ID': '0:0:1', 'Name': 'PhysicalDisk0:0:1', 'FailurePredicted': 'No'}] The list has repeating elements that require multiple dicts and the list varies in length. My code seems like it could be simplified, if only I knew Python better. My current code: DELETED CODE It didn't work. :( ----------- File output as requested ------------------- # omreport storage pdisk controller=0 List of Physical Disks on Controller PERC 5/i Integrated (Embedded) Controller PERC 5/i Integrated (Embedded) ID : 0:0:0 Status : Ok Name : Physical Disk 0:0:0 State : Online Failure Predicted : No Progress : Not Applicable Type : SAS Capacity : 136.13 GB (146163105792 bytes) Used RAID Disk Space : 136.13 GB (146163105792 bytes) Available RAID Disk Space : 0.00 GB (0 bytes) Hot Spare : No Vendor ID : DELL Product ID : ST3146755SS Revision : T107 Serial No. : 3LN1EF0G Negotiated Speed : Not Available Capable Speed : Not Available Manufacture Day : 07 Manufacture Week : 24 Manufacture Year : 2005 SAS Address : 5000C50004731C35 ID : 0:0:1 Status : Ok Name : Physical Disk 0:0:1 State : Online Failure Predicted : No Progress : Not Applicable Type : SAS Capacity : 136.13 GB (146163105792 bytes) Used RAID Disk Space : 136.13 GB (146163105792 bytes) Available RAID Disk Space : 0.00 GB (0 bytes) Hot Spare : No Vendor ID : DELL Product ID : ST3146755SS Revision : T107 Serial No. : 3LN1EF88 Negotiated Speed : Not Available Capable Speed : Not Available Manufacture Day : 07 Manufacture Week : 24 Manufacture Year : 2005 SAS Address : 5000C500047320B9 A: result = [{}] for item in data: key, val = item.split(":", 1) if key in result[-1]: result.append({}) result[-1][key] = val A: import re results = [] temp = {} for item in data: (key, value) = re.search('(.*?):(.*)', item).groups() if temp.has_key(key): temp = {} temp[key] = value if temp not in results: results.append(temp) A: If you have no more info than "each repetition of a key signals the need to start a new dict", your code can be improved only marginally, for example as: results = [] curd = {} for x in data: k, v = x.split(':', 1) if k in curd: results.append(curd) curd = {} curd[k] = v results.append(curd) i.e., no need to keep an intermediate list tmp rather than an intermediate dict curd. The semantics are subtly different -- you're initiating a new dict only when both key and value coincide (so an item such as 'Status:Borked' would "trample over" one being built from 'Status:Ok', for example), I'm taking the key only as the identifier (so, no trampling over in such a case) -- you sure the exact semantics you implement are what you require? A: ret = [] ITEMS_AMOUNT = 5 while True: tmp = {} for i in data[0:ITEMS_AMOUNT]: tmp.update(dict([i.split(':', 1)])) ret.append(tmp) if len(data) == ITEMS_AMOUNT: break data = data[ITEMS_AMOUNT:] print ret A: d=dict([]) c=0 whatiwant=["ID","Status","Name","State","Failure Predicted"] for line in open("file"): line=line.rstrip() sline=line.split(":",1) sline[0]=sline[0].strip() if sline[0]=="ID": c+=1 d.setdefault(c,[]) if sline[0] in whatiwant: d[c].append((sline[0],' '.join(sline[1:]))) for i,j in d.iteritems(): print i,j output $ ./python.py 1 [('ID', ' 0:0:0'), ('Status', ' Ok'), ('Name', ' Physical Disk 0:0:0'), ('State', ' Online'), ('Failure Predicted', ' No')] 2 [('ID', ' 0:0:1'), ('Status', ' Ok'), ('Name', ' Physical Disk 0:0:1'), ('State', ' Online'), ('Failure Predicted', ' No')]
Python: Split list into list of dicts?
Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list: data = ['ID:0:0:0', 'Status:Ok', 'Name:PhysicalDisk0:0:0', 'State:Online', 'FailurePredicted:No', 'ID:0:0:1', 'Status:Ok', 'Name:PhysicalDisk0:0:1', 'State:Online', 'FailurePredicted:No'] Finished list of dicts: [{'Status': 'Ok', 'State': 'Online', 'ID': '0:0:0', 'FailurePredicted': 'No', 'Name': 'PhysicalDisk0:0:0'}, {'Status': 'Ok', 'State': 'Online', 'ID': '0:0:1', 'Name': 'PhysicalDisk0:0:1', 'FailurePredicted': 'No'}] The list has repeating elements that require multiple dicts and the list varies in length. My code seems like it could be simplified, if only I knew Python better. My current code: DELETED CODE It didn't work. :( ----------- File output as requested ------------------- # omreport storage pdisk controller=0 List of Physical Disks on Controller PERC 5/i Integrated (Embedded) Controller PERC 5/i Integrated (Embedded) ID : 0:0:0 Status : Ok Name : Physical Disk 0:0:0 State : Online Failure Predicted : No Progress : Not Applicable Type : SAS Capacity : 136.13 GB (146163105792 bytes) Used RAID Disk Space : 136.13 GB (146163105792 bytes) Available RAID Disk Space : 0.00 GB (0 bytes) Hot Spare : No Vendor ID : DELL Product ID : ST3146755SS Revision : T107 Serial No. : 3LN1EF0G Negotiated Speed : Not Available Capable Speed : Not Available Manufacture Day : 07 Manufacture Week : 24 Manufacture Year : 2005 SAS Address : 5000C50004731C35 ID : 0:0:1 Status : Ok Name : Physical Disk 0:0:1 State : Online Failure Predicted : No Progress : Not Applicable Type : SAS Capacity : 136.13 GB (146163105792 bytes) Used RAID Disk Space : 136.13 GB (146163105792 bytes) Available RAID Disk Space : 0.00 GB (0 bytes) Hot Spare : No Vendor ID : DELL Product ID : ST3146755SS Revision : T107 Serial No. : 3LN1EF88 Negotiated Speed : Not Available Capable Speed : Not Available Manufacture Day : 07 Manufacture Week : 24 Manufacture Year : 2005 SAS Address : 5000C500047320B9
[ "result = [{}]\nfor item in data:\n key, val = item.split(\":\", 1)\n if key in result[-1]:\n result.append({})\n result[-1][key] = val\n\n", "import re\n\nresults = []\ntemp = {}\nfor item in data:\n (key, value) = re.search('(.*?):(.*)', item).groups()\n if temp.has_key(key): temp = {}\n temp[key] = value\n if temp not in results: results.append(temp)\n\n", "If you have no more info than \"each repetition of a key signals the need to start a new dict\", your code can be improved only marginally, for example as:\nresults = []\ncurd = {}\nfor x in data:\n k, v = x.split(':', 1)\n if k in curd:\n results.append(curd)\n curd = {}\n curd[k] = v\nresults.append(curd)\n\ni.e., no need to keep an intermediate list tmp rather than an intermediate dict curd. The semantics are subtly different -- you're initiating a new dict only when both key and value coincide (so an item such as 'Status:Borked' would \"trample over\" one being built from 'Status:Ok', for example), I'm taking the key only as the identifier (so, no trampling over in such a case) -- you sure the exact semantics you implement are what you require?\n", "ret = []\nITEMS_AMOUNT = 5 \nwhile True:\n tmp = {}\n for i in data[0:ITEMS_AMOUNT]:\n tmp.update(dict([i.split(':', 1)]))\n ret.append(tmp)\n\n if len(data) == ITEMS_AMOUNT:\n break\n data = data[ITEMS_AMOUNT:]\n\nprint ret \n\n", "d=dict([])\nc=0\nwhatiwant=[\"ID\",\"Status\",\"Name\",\"State\",\"Failure Predicted\"]\nfor line in open(\"file\"):\n line=line.rstrip()\n sline=line.split(\":\",1)\n sline[0]=sline[0].strip()\n if sline[0]==\"ID\":\n c+=1\n d.setdefault(c,[])\n if sline[0] in whatiwant:\n d[c].append((sline[0],' '.join(sline[1:])))\nfor i,j in d.iteritems():\n print i,j\n\noutput\n$ ./python.py\n1 [('ID', ' 0:0:0'), ('Status', ' Ok'), ('Name', ' Physical Disk 0:0:0'), ('State', ' Online'), ('Failure Predicted', ' No')]\n2 [('ID', ' 0:0:1'), ('Status', ' Ok'), ('Name', ' Physical Disk 0:0:1'), ('State', ' Online'), ('Failure Predicted', ' No')]\n\n" ]
[ 8, 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0001950672_dictionary_list_python.txt
Q: python lottery suggestion I know python offers random module to do some simple lottery. Let say random.shuffle() is a good one. However, I want to build my own simple one. What should I look into? Is there any specific mathematical philosophies behind lottery? Let say, the simplest situation. 100 names and generate 20 names randomly. I don't want to use shuffle, since I want to learn to build one myself. I need some advise to start. Thanks. A: You can generate your own pseudo-random numbers -- there's a huge amount of theory behind that, start for example here -- and of course you won't be able to compete with Python's random "Mersenne twister" (explained halfway down the large wikipedia page I pointed you to), in either quality or speed, but for purposes of understanding, it's a good endeavor. Or, you can get physically-random numbers, for example from /dev/random or /dev/urandom on Linux machines (Windows machines have their own interfaces for that, too) -- one has more pushy physical randomness, the other one has better performance. Once you do have (or borrow from random;-) a pseudo-random (or really random) number generator, picking 20 items at random from 100 is still an interesting problem. While shuffling is a more general approach, a more immediately understandable one might be, assuming your myrand(N) function returns a random or pseudorandom int between 0 included and N excluded: def pickfromlist(howmany, thelist): result = [] listcopy = list(thelist) while listcopy and len(result) < howmany: i = myrand(len(listcopy)) result.append(listcopy.pop(i)) return result Definitely not maximally efficient, but, I hope, maximally clear!-) In words: as long as required and feasible, pick one random item out of the remaining ones (the auxiliary list listcopy gives us the "remaining ones" at any step, and gets modified by .pop without altering the input parameter thelist, since it's a shallow copy). A: See the Fisher-Yates Shuffle, described also in Knuth's The Art of Computer Programming. A: I praise your desire to do this on your own. Back in the 1950's, random numbers were unavailable to most people without a supercomputer (of the time). The RAND corporation published a book called a million random digits with 100,000 normal deviates which had, literally, just that: random numbers. It was awesome because it enabled laypeople to use high-quality random numbers for research purposes. Now, back to your question. I recommend you read the instructions on how to use the book (yes, it comes with instructions) and try to implement that in your Python code. This will not be efficient or elegant, but you will understand the implications of the algorithm you ultimately settle for. I love the part that instructs you to open the book to an unselected page of the digit table and blindly choose a five-digit number; this number with the first number reduced modulo 2 determines the starting line; the two digits to the right of the initially selected five-digit number are reduced modulo 50 to determine the starting column in the starting line It was an art to read that table of numbers! To be sure, I'm not encouraging you to reinvent the wheel for production code. I'm encouraging you to learn about the art of randomness by implementing a clever, if not very efficient, random number generator. My work requires that I use high-quality random numbers, on limited occasions I have found the site www.random.org a very good source of both insight and material. From their website: RANDOM.ORG offers true random numbers to anyone on the Internet. The randomness comes from atmospheric noise, which for many purposes is better than the pseudo-random number algorithms typically used in computer programs. People use RANDOM.ORG for holding drawings, lotteries and sweepstakes, to drive games and gambling sites, for scientific applications and for art and music. Now, go and implement your own lottery. A: You can use: random.sample Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. For a more low-level approach, use `random.choice', in a loop: Return a random element from the non-empty sequence seq. The pseudo-random generator (PRNG) in Python is pretty good. If you want to go even more low-level, you can implement your own. Start with reading this article. The mathematical name for lottery is "sampling without replacement". Google that for information - here's a good link. A: The main shortcoming of software-based methods of generating lottery numbers is the fact that all random numbers generated by software are pseudo-random. This may not be a problem for your simple application, but you did ask about a 'specific mathematical philosophy'. You will have noticed that all commercial lottery systems use physical methods: balls with numbers. And behind the scenes, the numbers generated by physical lottery systems will be carefully scrutunised for indications of non-randomness and steps taken to eliminate it. As I say, this may not be a consideration for your simple application, but the overriding requirement of a true lottery (the 'specific mathematical philosophy') should be mathematically demonstrable randomness
python lottery suggestion
I know python offers random module to do some simple lottery. Let say random.shuffle() is a good one. However, I want to build my own simple one. What should I look into? Is there any specific mathematical philosophies behind lottery? Let say, the simplest situation. 100 names and generate 20 names randomly. I don't want to use shuffle, since I want to learn to build one myself. I need some advise to start. Thanks.
[ "You can generate your own pseudo-random numbers -- there's a huge amount of theory behind that, start for example here -- and of course you won't be able to compete with Python's random \"Mersenne twister\" (explained halfway down the large wikipedia page I pointed you to), in either quality or speed, but for purposes of understanding, it's a good endeavor. Or, you can get physically-random numbers, for example from /dev/random or /dev/urandom on Linux machines (Windows machines have their own interfaces for that, too) -- one has more pushy physical randomness, the other one has better performance.\nOnce you do have (or borrow from random;-) a pseudo-random (or really random) number generator, picking 20 items at random from 100 is still an interesting problem. While shuffling is a more general approach, a more immediately understandable one might be, assuming your myrand(N) function returns a random or pseudorandom int between 0 included and N excluded:\ndef pickfromlist(howmany, thelist):\n result = []\n listcopy = list(thelist)\n while listcopy and len(result) < howmany:\n i = myrand(len(listcopy))\n result.append(listcopy.pop(i))\n return result\n\nDefinitely not maximally efficient, but, I hope, maximally clear!-) In words: as long as required and feasible, pick one random item out of the remaining ones (the auxiliary list listcopy gives us the \"remaining ones\" at any step, and gets modified by .pop without altering the input parameter thelist, since it's a shallow copy).\n", "See the Fisher-Yates Shuffle, described also in Knuth's The Art of Computer Programming.\n", "I praise your desire to do this on your own.\nBack in the 1950's, random numbers were unavailable to most people without a supercomputer (of the time). The RAND corporation published a book called a million random digits with 100,000 normal deviates which had, literally, just that: random numbers. It was awesome because it enabled laypeople to use high-quality random numbers for research purposes.\nNow, back to your question.\nI recommend you read the instructions on how to use the book (yes, it comes with instructions) and try to implement that in your Python code. This will not be efficient or elegant, but you will understand the implications of the algorithm you ultimately settle for. I love the part that instructs you to \n\nopen the book to an unselected page of\n the digit table and blindly choose a\n five-digit number; this number with\n the first number reduced modulo 2\n determines the starting line; the two\n digits to the right of the initially\n selected five-digit number are reduced\n modulo 50 to determine the starting\n column in the starting line\n\nIt was an art to read that table of numbers!\nTo be sure, I'm not encouraging you to reinvent the wheel for production code. I'm encouraging you to learn about the art of randomness by implementing a clever, if not very efficient, random number generator.\nMy work requires that I use high-quality random numbers, on limited occasions I have found the site www.random.org a very good source of both insight and material. From their website:\n\nRANDOM.ORG offers true random numbers\n to anyone on the Internet. The\n randomness comes from atmospheric\n noise, which for many purposes is\n better than the pseudo-random number\n algorithms typically used in computer\n programs. People use RANDOM.ORG for\n holding drawings, lotteries and\n sweepstakes, to drive games and\n gambling sites, for scientific\n applications and for art and music.\n\nNow, go and implement your own lottery.\n", "You can use: random.sample\n\nReturn a k length list of unique\n elements chosen from the population\n sequence. Used for random sampling\n without replacement.\n\nFor a more low-level approach, use `random.choice', in a loop:\n\nReturn a random element from the\n non-empty sequence seq.\n\nThe pseudo-random generator (PRNG) in Python is pretty good. If you want to go even more low-level, you can implement your own. Start with reading this article. The mathematical name for lottery is \"sampling without replacement\". Google that for information - here's a good link.\n", "The main shortcoming of software-based methods of generating lottery numbers is the fact that all random numbers generated by software are pseudo-random.\nThis may not be a problem for your simple application, but you did ask about a 'specific mathematical philosophy'. You will have noticed that all commercial lottery systems use physical methods: balls with numbers.\nAnd behind the scenes, the numbers generated by physical lottery systems will be carefully scrutunised for indications of non-randomness and steps taken to eliminate it.\nAs I say, this may not be a consideration for your simple application, but the overriding requirement of a true lottery (the 'specific mathematical philosophy') should be mathematically demonstrable randomness \n" ]
[ 4, 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001950539_python.txt
Q: What is the purpose of classmethod in this code? In django.utils.tree.py: def _new_instance(cls, children=None, connector=None, negated=False): obj = Node(children, connector, negated) obj.__class__ = cls return obj _new_instance = classmethod(_new_instance) I don't know what classmethod does in this code sample. Can someone explain what it does and how to use it? A: classmethod is a decorator, wrapping a function, and you can call the resulting object on a class or (equivalently) an instance thereof: >>> class x(object): ... def c1(*args): print 'c1', args ... c1 = classmethod(c1) ... @classmethod ... def c2(*args): print 'c2', args ... >>> inst = x() >>> x.c1() c1 (<class '__main__.x'>,) >>> x.c2() c2 (<class '__main__.x'>,) >>> inst.c1() c1 (<class '__main__.x'>,) >>> inst.c2() c2 (<class '__main__.x'>,) As you see, whether you define it directly or with decorator syntax, and whether you call it on the class or the instance, the classmethod always receives the class as its first argument. One of the main uses of classmethod is to define alternative constructors: >>> class y(object): ... def __init__(self, astring): ... self.s = astring ... @classmethod ... def fromlist(cls, alist): ... x = cls('') ... x.s = ','.join(str(s) for s in alist) ... return x ... def __repr__(self): ... return 'y(%r)' % self.s ... >>> y1 = y('xx') >>> y1 y('xx') >>> y2 = y.fromlist(range(3)) >>> y2 y('0,1,2') Now if you subclass y, the classmethod keeps working, e.g.: >>> class k(y): ... def __repr__(self): ... return 'k(%r)' % self.s.upper() ... >>> k1 = k.fromlist(['za','bu']) >>> k1 k('ZA,BU') A: It makes it possible to call the method on the class instead of an object: class MyClass(object): def _new_instance(cls, blah): pass _new_instance = classmethod(_new_instance) MyClass._new_instance("blah")
What is the purpose of classmethod in this code?
In django.utils.tree.py: def _new_instance(cls, children=None, connector=None, negated=False): obj = Node(children, connector, negated) obj.__class__ = cls return obj _new_instance = classmethod(_new_instance) I don't know what classmethod does in this code sample. Can someone explain what it does and how to use it?
[ "classmethod is a decorator, wrapping a function, and you can call the resulting object on a class or (equivalently) an instance thereof:\n>>> class x(object):\n... def c1(*args): print 'c1', args\n... c1 = classmethod(c1)\n... @classmethod\n... def c2(*args): print 'c2', args\n... \n>>> inst = x()\n>>> x.c1()\nc1 (<class '__main__.x'>,)\n>>> x.c2()\nc2 (<class '__main__.x'>,)\n>>> inst.c1()\nc1 (<class '__main__.x'>,)\n>>> inst.c2()\nc2 (<class '__main__.x'>,)\n\nAs you see, whether you define it directly or with decorator syntax, and whether you call it on the class or the instance, the classmethod always receives the class as its first argument.\nOne of the main uses of classmethod is to define alternative constructors:\n>>> class y(object):\n... def __init__(self, astring):\n... self.s = astring\n... @classmethod\n... def fromlist(cls, alist):\n... x = cls('')\n... x.s = ','.join(str(s) for s in alist)\n... return x\n... def __repr__(self):\n... return 'y(%r)' % self.s\n...\n>>> y1 = y('xx')\n>>> y1\ny('xx')\n>>> y2 = y.fromlist(range(3))\n>>> y2\ny('0,1,2')\n\nNow if you subclass y, the classmethod keeps working, e.g.:\n>>> class k(y):\n... def __repr__(self):\n... return 'k(%r)' % self.s.upper()\n...\n>>> k1 = k.fromlist(['za','bu'])\n>>> k1\nk('ZA,BU')\n\n", "It makes it possible to call the method on the class instead of an object:\nclass MyClass(object):\n def _new_instance(cls, blah):\n pass\n _new_instance = classmethod(_new_instance)\n\nMyClass._new_instance(\"blah\")\n\n" ]
[ 213, 9 ]
[]
[]
[ "python" ]
stackoverflow_0001950414_python.txt
Q: Insights on SystemError: com_backpatch: offset too large In python, "SystemError: com_backpatch: offset too large" is thrown when executing the code generated by the following: f = open("test.py", "w") f.write("def fn():\n a =1000\n") for a in xrange(3000): if a == 0: f.write(" if a == "+str(a)+": \n print "+str(a)+"\n") else: f.write(" elif a == "+str(a)+": \n print "+str(a)+"\n") f.close() import test It is clear that if the length statement goes beyond a certain length, it throws this error. Can someone give more insight into this error? A: Accourding to this: http://www.cgl.ucsf.edu/pipermail/chimera-dev/2007/000404.html The Python bytecode compiler has a limitation of a maximum of a 16 bit offset in a jump instruction. This means that you don't want to have 64K worth of characters in a single conditional block of code More details here: http://www.mail-archive.com/python-list@python.org/msg72631.html A: Looks like you are hitting a python interpreter limit. It appears that the branch from the start of the if to the end is too far - probably because offset is limited to 16 bits. If you change the "elif" to "if" then the problem goes away. You need to reduce the size of the "if/elif" chain. HIH ...richie A: JFYI, this script worked for me in a Debian Testing host with a 32bits userspace and kernel and Python 2.5.4. $ ls -ln total 4 -rw-r--r-- 1 1000 1000 270 2009-12-23 02:53 gentest.py $ python gentest.py $ ls -ln total 216 -rw-r--r-- 1 1000 1000 270 2009-12-23 02:53 gentest.py -rw-r--r-- 1 1000 1000 111799 2009-12-23 02:58 test.py -rw-r--r-- 1 1000 1000 93299 2009-12-23 02:58 test.pyc $ uname -srvmo Linux 2.6.30-2-486 #1 Thu Dec 3 23:32:25 UTC 2009 i686 GNU/Linux $ python --version Python 2.5.4
Insights on SystemError: com_backpatch: offset too large
In python, "SystemError: com_backpatch: offset too large" is thrown when executing the code generated by the following: f = open("test.py", "w") f.write("def fn():\n a =1000\n") for a in xrange(3000): if a == 0: f.write(" if a == "+str(a)+": \n print "+str(a)+"\n") else: f.write(" elif a == "+str(a)+": \n print "+str(a)+"\n") f.close() import test It is clear that if the length statement goes beyond a certain length, it throws this error. Can someone give more insight into this error?
[ "Accourding to this: http://www.cgl.ucsf.edu/pipermail/chimera-dev/2007/000404.html\n\nThe Python bytecode compiler has a\n limitation of a maximum of a 16 bit\n offset in a jump instruction. This\n means that you don't want to have 64K\n worth of characters in a single\n conditional block of code\n\nMore details here: http://www.mail-archive.com/python-list@python.org/msg72631.html\n", "Looks like you are hitting a python interpreter limit. It appears that the branch from the start of the if to the end is too far - probably because offset is limited to 16 bits. If you change the \"elif\" to \"if\" then the problem goes away.\nYou need to reduce the size of the \"if/elif\" chain.\nHIH\n...richie\n", "JFYI, this script worked for me in a Debian Testing host with a 32bits userspace and kernel and Python 2.5.4.\n$ ls -ln\ntotal 4\n-rw-r--r-- 1 1000 1000 270 2009-12-23 02:53 gentest.py\n$ python gentest.py \n$ ls -ln\ntotal 216\n-rw-r--r-- 1 1000 1000 270 2009-12-23 02:53 gentest.py\n-rw-r--r-- 1 1000 1000 111799 2009-12-23 02:58 test.py\n-rw-r--r-- 1 1000 1000 93299 2009-12-23 02:58 test.pyc\n$ uname -srvmo\nLinux 2.6.30-2-486 #1 Thu Dec 3 23:32:25 UTC 2009 i686 GNU/Linux\n$ python --version\nPython 2.5.4\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001867070_python.txt
Q: Making Django admin display the Primary Key rather than each object's Object type In Django 1.1 admin, when I go to add or change an object, my objects are displayed as: Select host to change * Add host Host object Host object Host object Host object Host object This happens for all models in my site, not just Hosts. Rather than display the same name for each object, I would like Django to display the primary key. Select host to change * Add host machine1 machine2 Here is my code: from django.db import models # Create your models here. class Host(models.Model): host = models.CharField(max_length=100,primary_key=True) class Admin: list_display = ('host') class Test(models.Model): testname = models.CharField(max_length=100,primary_key=True) class Admin: list_display = ('testname') class Result(models.Model): host = models.ForeignKey(Host) TESTRESULT_CHOICES = ( ('P', 'Pass'), ('F', 'Fail'), ) testresult = models.CharField(max_length=1, choices=TESTRESULT_CHOICES) reason = models.CharField(max_length=100) time = models.DateTimeField() testname = models.OneToOneField(Test, primary_key=True) class Admin: list_display = ('host','testname','time','testresult','reason') Reading http://docs.djangoproject.com/en/dev/ref/contrib/admin/: "ModelAdmin.list_display Set list_display to control which fields are displayed on the change list page of the admin." However this simply does not seem to work. Am I doing something wrong? A: Add a __unicode__() method to Host. To show the primary key of your host objects, you'd want something like: class Host(models.Model): host = models.CharField(max_length=100, primary_key=True) def __unicode__(self): return self.pk ... You might want to think about showing the contents of the host field: class Host(models.Model): host = models.CharField(max_length=100, primary_key=True) def __unicode__(self): return self.host ... You'll need to do something similar for every model you've got. For Python 3 compatibility, you'll want to do something like this (see the documentation): from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Host(models.Model): host = models.CharField(max_length=100, primary_key=True) def __str__(self): return self.host ... A: contrib.admin has been reworked in 1.0, and old Admin classes inside models no longer work. What you need is ModelAdmin subclass in your_application.admin module, e.g. from your_application.models import Host from django.contrib import admin class HostAdmin(admin.ModelAdmin): list_display = ('host',) admin.site.register(Host, HostAdmin) Or use __unicode__ in the model itself, e.g. class Host(models.Model): host = models.CharField(max_length=100,primary_key=True) def __unicode__(self): return self.host A: It might also be worth mentioning that, if you are using an auto-incrementing primary key for your models, you will need to coerce it into a string, eg: def __unicode__(self): return str(self.pk)
Making Django admin display the Primary Key rather than each object's Object type
In Django 1.1 admin, when I go to add or change an object, my objects are displayed as: Select host to change * Add host Host object Host object Host object Host object Host object This happens for all models in my site, not just Hosts. Rather than display the same name for each object, I would like Django to display the primary key. Select host to change * Add host machine1 machine2 Here is my code: from django.db import models # Create your models here. class Host(models.Model): host = models.CharField(max_length=100,primary_key=True) class Admin: list_display = ('host') class Test(models.Model): testname = models.CharField(max_length=100,primary_key=True) class Admin: list_display = ('testname') class Result(models.Model): host = models.ForeignKey(Host) TESTRESULT_CHOICES = ( ('P', 'Pass'), ('F', 'Fail'), ) testresult = models.CharField(max_length=1, choices=TESTRESULT_CHOICES) reason = models.CharField(max_length=100) time = models.DateTimeField() testname = models.OneToOneField(Test, primary_key=True) class Admin: list_display = ('host','testname','time','testresult','reason') Reading http://docs.djangoproject.com/en/dev/ref/contrib/admin/: "ModelAdmin.list_display Set list_display to control which fields are displayed on the change list page of the admin." However this simply does not seem to work. Am I doing something wrong?
[ "Add a __unicode__() method to Host. To show the primary key of your host objects, you'd want something like:\nclass Host(models.Model):\n host = models.CharField(max_length=100, primary_key=True)\n\n def __unicode__(self):\n return self.pk\n\n ...\n\nYou might want to think about showing the contents of the host field:\nclass Host(models.Model):\n host = models.CharField(max_length=100, primary_key=True)\n\n def __unicode__(self):\n return self.host\n\n ...\n\nYou'll need to do something similar for every model you've got.\nFor Python 3 compatibility, you'll want to do something like this (see the documentation):\nfrom __future__ import unicode_literals\nfrom django.utils.encoding import python_2_unicode_compatible\n\n@python_2_unicode_compatible\nclass Host(models.Model):\n host = models.CharField(max_length=100, primary_key=True)\n\n def __str__(self):\n return self.host\n\n ...\n\n", "contrib.admin has been reworked in 1.0, and old Admin classes inside models no longer work. What you need is ModelAdmin subclass in your_application.admin module, e.g.\nfrom your_application.models import Host\nfrom django.contrib import admin\n\nclass HostAdmin(admin.ModelAdmin):\n list_display = ('host',)\n\nadmin.site.register(Host, HostAdmin)\n\nOr use __unicode__ in the model itself, e.g.\nclass Host(models.Model):\n host = models.CharField(max_length=100,primary_key=True)\n\n def __unicode__(self):\n return self.host\n\n", "It might also be worth mentioning that, if you are using an auto-incrementing primary key for your models, you will need to coerce it into a string, eg:\ndef __unicode__(self):\n return str(self.pk)\n\n" ]
[ 33, 10, 3 ]
[]
[]
[ "admin", "django", "python" ]
stackoverflow_0001594436_admin_django_python.txt
Q: SendKeys failing after 2 runs in thread Python and SendKeys import SendKeys, threading, pyHook, pythoncom class Auto(threading.Thread): def run(self): SendKeys.SendKeys("{ENTER}",pause=0.1); print('Sent'); exit(); def OnKeyboardEvent(event): if event.Ascii == 22: Auto().start(); return True hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages() For some reason this program fails after running it exactly two times, I have no idea what the cause for this is. When you comment out the SendKeys part the program runs fine, so it has to be a problem with send keys. [edit] Also, to clarify, running SendKeys.SendKeys(...) in a for i in range(0,100) works, so I assume it's something to do with the thread. I've never programmed threads before. Also this is just a mockup example to replicate the problem. I'm running on windows 7, python2.6 [edit]Also, the program doesn't 'fail' it simply freezes (the function isn't run at all, it just sits there) A: It seems that SendKeys is thread safe. The following code works on Vista - Python 2.6 class Auto(threading.Thread): def run(self): SendKeys.SendKeys("#",pause=0.1); print('Sent'); exit(); for i in xrange(30): Auto().start() Maybe the problem comes from some interferences with PyHook or the Windows PumpMessage mechanism. Have you tried to put the SendKeys part in a different process rather than in a different thread? I hope it helps A: I am not so sure with the program but if you put exit(); in the middle of the program, It will quit program completely. So Could you try without exit();?
SendKeys failing after 2 runs in thread
Python and SendKeys import SendKeys, threading, pyHook, pythoncom class Auto(threading.Thread): def run(self): SendKeys.SendKeys("{ENTER}",pause=0.1); print('Sent'); exit(); def OnKeyboardEvent(event): if event.Ascii == 22: Auto().start(); return True hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages() For some reason this program fails after running it exactly two times, I have no idea what the cause for this is. When you comment out the SendKeys part the program runs fine, so it has to be a problem with send keys. [edit] Also, to clarify, running SendKeys.SendKeys(...) in a for i in range(0,100) works, so I assume it's something to do with the thread. I've never programmed threads before. Also this is just a mockup example to replicate the problem. I'm running on windows 7, python2.6 [edit]Also, the program doesn't 'fail' it simply freezes (the function isn't run at all, it just sits there)
[ "It seems that SendKeys is thread safe. The following code works on Vista - Python 2.6\nclass Auto(threading.Thread):\n def run(self):\n SendKeys.SendKeys(\"#\",pause=0.1);\n print('Sent');\n exit();\n\nfor i in xrange(30):\n Auto().start()\n\nMaybe the problem comes from some interferences with PyHook or the Windows PumpMessage mechanism. Have you tried to put the SendKeys part in a different process rather than in a different thread?\nI hope it helps\n", "I am not so sure with the program but if you put exit(); in the middle of the program, It will quit program completely.\nSo Could you try without exit();?\n" ]
[ 1, 0 ]
[]
[]
[ "python", "sendkeys" ]
stackoverflow_0001950781_python_sendkeys.txt
Q: Python: intercept a class loading action Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice. Reason: I am working on some legacy code. I need to write some unit test code before I start some enhancement/refactoring. The code imports a certain module which will fail in a unit test setting, however. (Because of database server dependency) Pseduo Code: from LegacyDataLoader import load_me_data ... def do_something(): data = load_me_data() So, ideally, when python excutes the import line above in a unit test, an alternative class, says MockDataLoader, is loaded instead. I am still using 2.4.3. I suppose there is an import hook I can manipulate Edit Thanks a lot for the answers so far. They are all very helpful. One particular type of suggestion is about manipulation of PYTHONPATH. It does not work in my case. So I will elaborate my particular situation here. The original codebase is organised in this way ./dir1/myapp/database/LegacyDataLoader.py ./dir1/myapp/database/Other.py ./dir1/myapp/database/__init__.py ./dir1/myapp/__init__.py My goal is to enhance the Other class in the Other module. But since it is legacy code, I do not feel comfortable working on it without strapping a test suite around it first. Now I introduce this unit test code ./unit_test/test.py The content is simply: from myapp.database.Other import Other def test1(): o = Other() o.do_something() if __name__ == "__main__": test1() When the CI server runs the above test, the test fails. It is because class Other uses LegacyDataLoader, and LegacydataLoader cannot establish database connection to the db server from the CI box. Now let's add a fake class as suggested: ./unit_test_fake/myapp/database/LegacyDataLoader.py ./unit_test_fake/myapp/database/__init__.py ./unit_test_fake/myapp/__init__.py Modify the PYTHONPATH to export PYTHONPATH=unit_test_fake:dir1:unit_test Now the test fails for another reason File "unit_test/test.py", line 1, in <module> from myapp.database.Other import Other ImportError: No module named Other It has something to do with the way python resolves classes/attributes in a module A: You can intercept import and from ... import statements by defining your own __import__ function and assigning it to __builtin__.__import__ (make sure to save the previous value, since your override will no doubt want to delegate to it; and you'll need to import __builtin__ to get the builtin-objects module). For example (Py2.4 specific, since that's what you're asking about), save in aim.py the following: import __builtin__ realimp = __builtin__.__import__ def my_import(name, globals={}, locals={}, fromlist=[]): print 'importing', name, fromlist return realimp(name, globals, locals, fromlist) __builtin__.__import__ = my_import from os import path and now: $ python2.4 aim.py importing os ('path',) So this lets you intercept any specific import request you want, and alter the imported module[s] as you wish before you return them -- see the specs here. This is the kind of "hook" you're looking for, right? A: Well, if the import fails by raising an exception, you could put it in a try...except loop: try: from LegacyDataLoader import load_me_data except: # put error that occurs here, so as not to mask actual problems from MockDataLoader import load_me_data Is that what you're looking for? If it fails, but doesn't raise an exception, you could have it run the unit test with a special command line tag, like --unittest, like this: import sys if "--unittest" in sys.argv: from MockDataLoader import load_me_data else: from LegacyDataLoader import load_me_data A: There are cleaner ways to do this, but I'll assume that you can't modify the file containing from LegacyDataLoader import load_me_data. The simplest thing to do is probably to create a new directory called testing_shims, and create LegacyDataLoader.py file in it. In that file, define whatever fake load_me_data you like. When running the unit tests, put testing_shims into your PYTHONPATH environment variable as the first directory. Alternately, you can modify your test runner to insert testing_shims as the first value in sys.path. This way, your file will be found when importing LegacyDataLoader, and your code will be loaded instead of the real code. A: The import statement just grabs stuff from sys.modules if a matching name is found there, so the simplest thing is to make sure you insert your own module into sys.modules under the target name before anything else tries to import the real thing. # in test code import sys import MockDataLoader sys.modules['LegacyDataLoader'] = MockDataLoader import module_under_test There are a handful of variations on the theme, but that basic approach should work fine to do what you describe in the question. A slightly simpler approach would be this, using just a mock function to replace the one in question: # in test code import module_under_test def mock_load_me_data(): # do mock stuff here module_under_test.load_me_data = mock_load_me_data That simply replaces the appropriate name right in the module itself, so when you invoke the code under test, presumably do_something() in your question, it calls your mock routine.
Python: intercept a class loading action
Summary: when a certain python module is imported, I want to be able to intercept this action, and instead of loading the required class, I want to load another class of my choice. Reason: I am working on some legacy code. I need to write some unit test code before I start some enhancement/refactoring. The code imports a certain module which will fail in a unit test setting, however. (Because of database server dependency) Pseduo Code: from LegacyDataLoader import load_me_data ... def do_something(): data = load_me_data() So, ideally, when python excutes the import line above in a unit test, an alternative class, says MockDataLoader, is loaded instead. I am still using 2.4.3. I suppose there is an import hook I can manipulate Edit Thanks a lot for the answers so far. They are all very helpful. One particular type of suggestion is about manipulation of PYTHONPATH. It does not work in my case. So I will elaborate my particular situation here. The original codebase is organised in this way ./dir1/myapp/database/LegacyDataLoader.py ./dir1/myapp/database/Other.py ./dir1/myapp/database/__init__.py ./dir1/myapp/__init__.py My goal is to enhance the Other class in the Other module. But since it is legacy code, I do not feel comfortable working on it without strapping a test suite around it first. Now I introduce this unit test code ./unit_test/test.py The content is simply: from myapp.database.Other import Other def test1(): o = Other() o.do_something() if __name__ == "__main__": test1() When the CI server runs the above test, the test fails. It is because class Other uses LegacyDataLoader, and LegacydataLoader cannot establish database connection to the db server from the CI box. Now let's add a fake class as suggested: ./unit_test_fake/myapp/database/LegacyDataLoader.py ./unit_test_fake/myapp/database/__init__.py ./unit_test_fake/myapp/__init__.py Modify the PYTHONPATH to export PYTHONPATH=unit_test_fake:dir1:unit_test Now the test fails for another reason File "unit_test/test.py", line 1, in <module> from myapp.database.Other import Other ImportError: No module named Other It has something to do with the way python resolves classes/attributes in a module
[ "You can intercept import and from ... import statements by defining your own __import__ function and assigning it to __builtin__.__import__ (make sure to save the previous value, since your override will no doubt want to delegate to it; and you'll need to import __builtin__ to get the builtin-objects module).\nFor example (Py2.4 specific, since that's what you're asking about), save in aim.py the following:\nimport __builtin__\nrealimp = __builtin__.__import__\ndef my_import(name, globals={}, locals={}, fromlist=[]):\n print 'importing', name, fromlist\n return realimp(name, globals, locals, fromlist)\n__builtin__.__import__ = my_import\n\nfrom os import path\n\nand now:\n$ python2.4 aim.py\nimporting os ('path',)\n\nSo this lets you intercept any specific import request you want, and alter the imported module[s] as you wish before you return them -- see the specs here. This is the kind of \"hook\" you're looking for, right?\n", "Well, if the import fails by raising an exception, you could put it in a try...except loop:\ntry:\n from LegacyDataLoader import load_me_data\nexcept: # put error that occurs here, so as not to mask actual problems\n from MockDataLoader import load_me_data\n\nIs that what you're looking for? If it fails, but doesn't raise an exception, you could have it run the unit test with a special command line tag, like --unittest, like this:\nimport sys\nif \"--unittest\" in sys.argv:\n from MockDataLoader import load_me_data\nelse:\n from LegacyDataLoader import load_me_data\n\n", "There are cleaner ways to do this, but I'll assume that you can't modify the file containing from LegacyDataLoader import load_me_data.\nThe simplest thing to do is probably to create a new directory called testing_shims, and create LegacyDataLoader.py file in it. In that file, define whatever fake load_me_data you like. When running the unit tests, put testing_shims into your PYTHONPATH environment variable as the first directory. Alternately, you can modify your test runner to insert testing_shims as the first value in sys.path.\nThis way, your file will be found when importing LegacyDataLoader, and your code will be loaded instead of the real code.\n", "The import statement just grabs stuff from sys.modules if a matching name is found there, so the simplest thing is to make sure you insert your own module into sys.modules under the target name before anything else tries to import the real thing.\n# in test code\nimport sys\nimport MockDataLoader\nsys.modules['LegacyDataLoader'] = MockDataLoader\n\nimport module_under_test\n\nThere are a handful of variations on the theme, but that basic approach should work fine to do what you describe in the question. A slightly simpler approach would be this, using just a mock function to replace the one in question:\n# in test code\nimport module_under_test\n\ndef mock_load_me_data():\n # do mock stuff here\n\nmodule_under_test.load_me_data = mock_load_me_data\n\nThat simply replaces the appropriate name right in the module itself, so when you invoke the code under test, presumably do_something() in your question, it calls your mock routine.\n" ]
[ 5, 1, 1, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0001950062_python_unit_testing.txt
Q: What is meant by 2D array support? I read that Python does not actually support 2D arrays but rather an array of an array. I understand the array of an array thing but what does it mean by supporting 2D arrays? In C a 2D array is simply converted to a 1D array by doing some fancy math (Seen here). Are there languages that implement actual 2D arrays? Thanks for the help and I hope I haven't written a duplicate question; if so give me a link and close my question :) A: There are languages that implement 2D (or 3D, etc) arrays. Fortran is one of them. It means you can write an array index expression like array[x,y] and the language will take care of the math to find the correct element. Also, Numpy is a numerical extension to Python that provides n-dimensional arrays. A: Somebody already mentioned numpy, and the OP commented that "it's back to the fancy pointer math with C arrays" -- that's a totally trivial implementation detail! Since the underlying memory in a (normal;-) computer can be seen as an array of bytes (or words), well then of course any data structure whatsoever is implemented in top of that array (or slices thereof) plus "fancy pointer math" -- double-ended queues, multi-dimensional arrays, binary trees, you name it, the underlying implementations will always boil down to that (just like all fancy control structures boil down to conditional and unconditional jumps at machine level, and so forth). SO WHAT?! These are implementation details, of course. numpy, just like Fortran and other languages and libraries, provides N-dimensional arrays -- no matter how it implements them "deep inside" (actually numpy's pretty up front about that, as you can easily flatten and reshape arrays -- it's pretty typical of Python to provide higher level abstractions with pretty good "hooks" on how they relate to lower-level ones;-). E.g., >>> import numpy >>> x = numpy.arange(12) >>> x array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) >>> x.reshape((3,4)) array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.reshape((4,3)) array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) >>> x.reshape((4,3))[::2, ::2] array([[0, 2], [6, 8]]) >>> x.reshape((4,3))[(0,1,3), ::2] array([[ 0, 2], [ 3, 5], [ 9, 11]]) >>> You can reshape, index, slice and mold the data in the N-dimensional array with high flexibility and excellent performance -- even while knowing that the underlying data block is just that one-dimensional array (here x is born and stays 1-D, but even if that weren't the case you could still access the underlying 1-D array by flattening). This is what "support for N-dimensional array" means (though in most other languages and frameworks offering such support you may get less transparency, lower functionality, or both;-). A: C# has multi-dimensional arrays, but they are recommended against as jagged arrays (arrays of arrays) are more performant. A: Fortran has real multi-dimensional arrays. This link talks about them in the FORTRAN 77 case. A: I guess 'support of 2D arrays' means how the language allows you to access the data as if it was a 2D array. In c the fancy math is hidden by array constructs: char arr[5][5]; char c = arr[2][3]; There is a way to do this by pointer arithmetics as well (which you probably refer as fancy math). In reality memory is a big chunk of addressable bytes of data [0,1,2,3,4,5,6 ... end of memory] so there is no 'native' notion of 2D array, something somewhere has to translate programmers "row 1 col 2" to actual address in memory. Programming languages usually give you a way to hide the translation. A: Actual arrays in Python - that is, the array object created by the array module - are strictly one-dimensional. They're also something you probably won't use unless your code has to interoperate with C data structures, you're working with huge quantities of data that must be kept in memory, or you're writing something like numpy. A: Rosetta Code has Python examples for creating a two dimensional array.
What is meant by 2D array support?
I read that Python does not actually support 2D arrays but rather an array of an array. I understand the array of an array thing but what does it mean by supporting 2D arrays? In C a 2D array is simply converted to a 1D array by doing some fancy math (Seen here). Are there languages that implement actual 2D arrays? Thanks for the help and I hope I haven't written a duplicate question; if so give me a link and close my question :)
[ "There are languages that implement 2D (or 3D, etc) arrays. Fortran is one of them. It means you can write an array index expression like array[x,y] and the language will take care of the math to find the correct element.\nAlso, Numpy is a numerical extension to Python that provides n-dimensional arrays.\n", "Somebody already mentioned numpy, and the OP commented that \"it's back to the fancy pointer math with C arrays\" -- that's a totally trivial implementation detail! Since the underlying memory in a (normal;-) computer can be seen as an array of bytes (or words), well then of course any data structure whatsoever is implemented in top of that array (or slices thereof) plus \"fancy pointer math\" -- double-ended queues, multi-dimensional arrays, binary trees, you name it, the underlying implementations will always boil down to that (just like all fancy control structures boil down to conditional and unconditional jumps at machine level, and so forth). SO WHAT?! These are implementation details, of course. numpy, just like Fortran and other languages and libraries, provides N-dimensional arrays -- no matter how it implements them \"deep inside\" (actually numpy's pretty up front about that, as you can easily flatten and reshape arrays -- it's pretty typical of Python to provide higher level abstractions with pretty good \"hooks\" on how they relate to lower-level ones;-).\nE.g.,\n>>> import numpy\n>>> x = numpy.arange(12)\n>>> x\narray([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])\n>>> x.reshape((3,4))\narray([[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]])\n>>> x.reshape((4,3))\narray([[ 0, 1, 2],\n [ 3, 4, 5],\n [ 6, 7, 8],\n [ 9, 10, 11]])\n>>> x.reshape((4,3))[::2, ::2]\narray([[0, 2],\n [6, 8]])\n>>> x.reshape((4,3))[(0,1,3), ::2]\narray([[ 0, 2],\n [ 3, 5],\n [ 9, 11]])\n>>> \n\nYou can reshape, index, slice and mold the data in the N-dimensional array with high flexibility and excellent performance -- even while knowing that the underlying data block is just that one-dimensional array (here x is born and stays 1-D, but even if that weren't the case you could still access the underlying 1-D array by flattening).\nThis is what \"support for N-dimensional array\" means (though in most other languages and frameworks offering such support you may get less transparency, lower functionality, or both;-).\n", "C# has multi-dimensional arrays, but they are recommended against as jagged arrays (arrays of arrays) are more performant.\n", "Fortran has real multi-dimensional arrays. This link talks about them in the FORTRAN 77 case.\n", "I guess 'support of 2D arrays' means how the language allows you to access the data as if it was a 2D array. In c the fancy math is hidden by array constructs:\nchar arr[5][5];\nchar c = arr[2][3];\n\nThere is a way to do this by pointer arithmetics as well (which you probably refer as fancy math).\nIn reality memory is a big chunk of addressable bytes of data [0,1,2,3,4,5,6 ... end of memory] so there is no 'native' notion of 2D array, something somewhere has to translate programmers \"row 1 col 2\" to actual address in memory. Programming languages usually give you a way to hide the translation.\n", "Actual arrays in Python - that is, the array object created by the array module - are strictly one-dimensional. They're also something you probably won't use unless your code has to interoperate with C data structures, you're working with huge quantities of data that must be kept in memory, or you're writing something like numpy.\n", "Rosetta Code has Python examples for creating a two dimensional array.\n" ]
[ 10, 6, 2, 1, 1, 1, 1 ]
[]
[]
[ "arrays", "c", "multidimensional_array", "python" ]
stackoverflow_0001698553_arrays_c_multidimensional_array_python.txt
Q: Python - Things I shouldn't be doing? I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code: ... junk_block = "".join(open("foo.txt","rb").read().split()) ... I don't do this anymore because I can see that it makes code harder to read, but would the code run slower if I split the statements up like so: f_obj = open("foo.txt", "rb") f_data = f_obj.read() f_data_list = f_data.split() junk_block = "".join(f_data_list) I also noticed that there's nothing keeping you from doing an 'import' within a function block, is there any reason why I should do that? A: As long as you're inside a function (not at module top level), assigning intermediate results to local barenames has an essentially-negligible cost (at module top level, assigning to the "local" barenames implies churning on a dict -- the module's __dict__ -- and is measurably costlier than it would be within a function; the remedy is never to have "substantial" code at module top level... always stash substantial code within a function!-). Python's general philosophy includes "flat is better than nested" -- and that includes highly "nested" expressions. Looking at your original example...: junk_block = "".join(open("foo.txt","rb").read().split()) presents another important issues: when is that file getting closed? In CPython today, you need not worry -- reference counting in practice does ensure timely closure. But most other Python implementations (Jython on the JVM, IronPython on .NET, PyPy on all sorts of backends, pynie on Parrot, Unladen Swallow on LLVM if and when it matures per its published roadmap, ...) do not guarantee the use of reference counting -- many garbage collection strategies may be involved, with all sort of other advantages. Without any guarantee of reference counting (and even in CPython it's always been deemed an implementation artifact, not part of the language semantics!), you might be exhausting resources, by executing such "open but no close" code in a tight loop -- garbage collection is triggered by scarcity of memory, and does not consider other limited resources such as file descriptors. Since 2.6 (and 2.5, with an "import from the future"), Python has a great solution via the RAII ("resource acquisition is initialization") approach supported by the with statement: with open("foo.txt","rb") as f: junk_block = "".join(f.read().split()) is the least-"unnested" way that will ensure timely closure of the file across all compliant versions of Python. The stronger semantics make it preferable. Beyond ensuring the correct, and prudent;-), semantics, there's not that much to choose between nested and flattened versions of an expression such as this. Given the task "remove all runs of whitespace from the file's contents", I would be tempted to benchmark alternative approaches based on re and on the .translate method of strings (the latter, esp. in Python 2.*, is often the fastest way to delete all characters from a certain set!), before settling on the "split and rejoin" approach if it proves to be faster -- but that's really a rather different issue;-). A: First of all, there's not really a reason you shouldn't use the first example - it'd quite readable in that it's concise about what it does. No reason to break it up since it's just a linear combination of calls. Second, import within a function block is useful if there's a particular library function that you only need within that function - since the scope of an imported symbol is only the block within which it is imported, if you only ever use something once, you can just import it where you need it and not have to worry about name conflicts in other functions. This is especially handy with from X import Y statements, since Y won't be qualified by its containing module name and thus might conflict with a similarly named function in a different module being used elsewhere. A: from PEP 8 (which is worth reading anyway) Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants A: That line has the same result as this: junk_block = open("foo.txt","rb").read().replace(' ', '') In your example you are splitting the words of the text into a list of words, and then you are joining them back together with no spaces. The above example instead uses the str.replace() method. The differences: Yours builds a file object into memory, builds a string into memory by reading it, builds a list into memory by splitting the string, builds a new string by joining the list. Mine builds a file object into memory, builds a string into memory by reading it, builds a new string into memory by replacing spaces. You can see a bit less RAM is used in the new variation but more processor is used. RAM is more valuable in some cases and so memory waste is frowned upon when it can be avoided. Most of the memory will be garbage collected immediately but multiple users at the same time will hog RAM. A: If you want to know if your second code fragment is slower, the quick way to find out would be to just use timeit. I wouldn't expect there to be that much difference though, since they seem pretty equivalent. You should also ask if a performance difference actually matters in the code in question. Often readability is of more value than performance. I can't think of any good reasons for importing a module in a function, but sometimes you just don't know you'll need to do something until you see the problem. I'll have to leave it to others to point out a constructive example of that, if it exists. A: I think the two codes are readable. I (and that's just a question of personal style) will probably use the first, adding a coment line, something like: "Open the file and convert the data inside into a list" Also, there are times when I use the second, maybe not so separated, but something like f_data = open("foo.txt", "rb").read() f_data_list = f_data.split() junk_block = "".join(f_data_list) But then I'm giving more entity to each operation, which could be important in the flow of the code. I think it's important you are confortable and don't think that the code is difficult to understand in the future. Definitly, the code will not be (at least, much) slower, as the only "overload" you're making is to asing the results to values.
Python - Things I shouldn't be doing?
I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code: ... junk_block = "".join(open("foo.txt","rb").read().split()) ... I don't do this anymore because I can see that it makes code harder to read, but would the code run slower if I split the statements up like so: f_obj = open("foo.txt", "rb") f_data = f_obj.read() f_data_list = f_data.split() junk_block = "".join(f_data_list) I also noticed that there's nothing keeping you from doing an 'import' within a function block, is there any reason why I should do that?
[ "As long as you're inside a function (not at module top level), assigning intermediate results to local barenames has an essentially-negligible cost (at module top level, assigning to the \"local\" barenames implies churning on a dict -- the module's __dict__ -- and is measurably costlier than it would be within a function; the remedy is never to have \"substantial\" code at module top level... always stash substantial code within a function!-).\nPython's general philosophy includes \"flat is better than nested\" -- and that includes highly \"nested\" expressions. Looking at your original example...:\njunk_block = \"\".join(open(\"foo.txt\",\"rb\").read().split())\n\npresents another important issues: when is that file getting closed? In CPython today, you need not worry -- reference counting in practice does ensure timely closure. But most other Python implementations (Jython on the JVM, IronPython on .NET, PyPy on all sorts of backends, pynie on Parrot, Unladen Swallow on LLVM if and when it matures per its published roadmap, ...) do not guarantee the use of reference counting -- many garbage collection strategies may be involved, with all sort of other advantages.\nWithout any guarantee of reference counting (and even in CPython it's always been deemed an implementation artifact, not part of the language semantics!), you might be exhausting resources, by executing such \"open but no close\" code in a tight loop -- garbage collection is triggered by scarcity of memory, and does not consider other limited resources such as file descriptors. Since 2.6 (and 2.5, with an \"import from the future\"), Python has a great solution via the RAII (\"resource acquisition is initialization\") approach supported by the with statement:\nwith open(\"foo.txt\",\"rb\") as f:\n junk_block = \"\".join(f.read().split())\n\nis the least-\"unnested\" way that will ensure timely closure of the file across all compliant versions of Python. The stronger semantics make it preferable.\nBeyond ensuring the correct, and prudent;-), semantics, there's not that much to choose between nested and flattened versions of an expression such as this. Given the task \"remove all runs of whitespace from the file's contents\", I would be tempted to benchmark alternative approaches based on re and on the .translate method of strings (the latter, esp. in Python 2.*, is often the fastest way to delete all characters from a certain set!), before settling on the \"split and rejoin\" approach if it proves to be faster -- but that's really a rather different issue;-).\n", "First of all, there's not really a reason you shouldn't use the first example - it'd quite readable in that it's concise about what it does. No reason to break it up since it's just a linear combination of calls.\nSecond, import within a function block is useful if there's a particular library function that you only need within that function - since the scope of an imported symbol is only the block within which it is imported, if you only ever use something once, you can just import it where you need it and not have to worry about name conflicts in other functions. This is especially handy with from X import Y statements, since Y won't be qualified by its containing module name and thus might conflict with a similarly named function in a different module being used elsewhere.\n", "from PEP 8 (which is worth reading anyway)\n\nImports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants\n\n", "That line has the same result as this:\njunk_block = open(\"foo.txt\",\"rb\").read().replace(' ', '')\nIn your example you are splitting the words of the text into a list of words, and then you are joining them back together with no spaces. The above example instead uses the str.replace() method.\nThe differences:\nYours builds a file object into memory, builds a string into memory by reading it, builds a list into memory by splitting the string, builds a new string by joining the list.\nMine builds a file object into memory, builds a string into memory by reading it, builds a new string into memory by replacing spaces.\nYou can see a bit less RAM is used in the new variation but more processor is used. RAM is more valuable in some cases and so memory waste is frowned upon when it can be avoided.\nMost of the memory will be garbage collected immediately but multiple users at the same time will hog RAM.\n", "If you want to know if your second code fragment is slower, the quick way to find out would be to just use timeit. I wouldn't expect there to be that much difference though, since they seem pretty equivalent. \nYou should also ask if a performance difference actually matters in the code in question. Often readability is of more value than performance.\nI can't think of any good reasons for importing a module in a function, but sometimes you just don't know you'll need to do something until you see the problem. I'll have to leave it to others to point out a constructive example of that, if it exists.\n", "I think the two codes are readable. I (and that's just a question of personal style) will probably use the first, adding a coment line, something like: \"Open the file and convert the data inside into a list\"\nAlso, there are times when I use the second, maybe not so separated, but something like\nf_data = open(\"foo.txt\", \"rb\").read()\nf_data_list = f_data.split()\njunk_block = \"\".join(f_data_list)\n\nBut then I'm giving more entity to each operation, which could be important in the flow of the code. I think it's important you are confortable and don't think that the code is difficult to understand in the future.\nDefinitly, the code will not be (at least, much) slower, as the only \"overload\" you're making is to asing the results to values.\n" ]
[ 21, 4, 3, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001951012_python.txt
Q: python gnutella programming I wanna learn how to build a p2p application in python that conforms to the gnutella protocol so it can tap-in the existing network like limewire, etc. Any body who knows something where to start or a ste-by-step guide? I've been reading the http://wiki.limewire.org/index.php?title=GDF but I need something with an example so I can easily follow. A: First of all: read the protocol specification carefully There are multiple python Gnutella implementations, I was able to find at least the following with quick googling: Quack, gnuppy. Check their source code for reference. The python modules you might find helpful with protocol packet decoding and message parsing are struct and re. You might also need to implement some sort of Finite State Machine to keep track of various exchanges.
python gnutella programming
I wanna learn how to build a p2p application in python that conforms to the gnutella protocol so it can tap-in the existing network like limewire, etc. Any body who knows something where to start or a ste-by-step guide? I've been reading the http://wiki.limewire.org/index.php?title=GDF but I need something with an example so I can easily follow.
[ "First of all: read the protocol specification carefully\nThere are multiple python Gnutella implementations, I was able to find at least the following with quick googling:\nQuack, gnuppy. Check their source code for reference.\nThe python modules you might find helpful with protocol packet decoding and message parsing are struct and re. You might also need to implement some sort of Finite State Machine to keep track of various exchanges.\n" ]
[ 4 ]
[]
[]
[ "p2p", "python" ]
stackoverflow_0001951113_p2p_python.txt
Q: How to read/write .sit files with Python in Linux How to read/write a .sit archive using Python in Linux? A: For dealing with older library formats I tend to fall back on command line utilities. You should be able to find sit manipulation tools such as this one: http://ctan.binkerton.com/ctan.readme.php?filename=tools/unstuff/unsit.c As to making them, I'd suggest using an alternative format. You probably have a specific purpose in mind, but it's a fairly outdated format and you'd be better off with ZIP or TAR.GZ.
How to read/write .sit files with Python in Linux
How to read/write a .sit archive using Python in Linux?
[ "For dealing with older library formats I tend to fall back on command line utilities. You should be able to find sit manipulation tools such as this one:\nhttp://ctan.binkerton.com/ctan.readme.php?filename=tools/unstuff/unsit.c\nAs to making them, I'd suggest using an alternative format. You probably have a specific purpose in mind, but it's a fairly outdated format and you'd be better off with ZIP or TAR.GZ.\n" ]
[ 0 ]
[]
[]
[ "extract", "file", "python" ]
stackoverflow_0001951419_extract_file_python.txt
Q: Who can call __get__, __set__ and __del__? This is my code. I don't know why it doesn't work. class a: def __get__(self): return 'xxx' def aa(self): print 'aaaa' b=a() print b.get('aa') Please try to answer in code, because my English is not very good. Thank you. class HideX(object): def __init__(self, x): self.x = x def get_x(self): return self.__x def set_x(self, x): self.__x = x+10 x = property(get_x, set_x) inst = HideX(20) print inst.x inst.x = 30 print inst.x A: I think you should read a bit more on Descriptors before you try to use them. A: You are calling obj.get, but there is no get function in class A, hence error, either rename __get__ to get or if you by chance are trying to use descriptors do something like this class A(object): def __get__(self, obj, klass): print "__get__", obj, klass return 'xxx' class X(object): a = A() x=X() print x.a
Who can call __get__, __set__ and __del__?
This is my code. I don't know why it doesn't work. class a: def __get__(self): return 'xxx' def aa(self): print 'aaaa' b=a() print b.get('aa') Please try to answer in code, because my English is not very good. Thank you. class HideX(object): def __init__(self, x): self.x = x def get_x(self): return self.__x def set_x(self, x): self.__x = x+10 x = property(get_x, set_x) inst = HideX(20) print inst.x inst.x = 30 print inst.x
[ "I think you should read a bit more on Descriptors before you try to use them.\n", "You are calling obj.get, but there is no get function in class A, hence error,\neither rename __get__ to get or if you by chance are trying to use descriptors do something like this\nclass A(object):\n def __get__(self, obj, klass):\n print \"__get__\", obj, klass\n return 'xxx'\n\nclass X(object):\n a = A()\n\nx=X()\nprint x.a\n\n" ]
[ 1, 1 ]
[]
[]
[ "descriptor", "python" ]
stackoverflow_0001951415_descriptor_python.txt
Q: Customize login in Google App Engine I need to add few more options for login and therefore need to customize create_login_url with some HTML code. Is there a way to add on your code in default login screen of Google? Environment: Python (Google App Engine) I want to continue having the default Google ext class Users behavior in place. A: You can't customize the login page. Allowing you to do so would introduce the possibility of XSS vulnerabilities, as well as making it harder for users to identify a legitimate login page. If you want to provide for federated login, you may want to simply redirect users to an interstitial page that allows them to pick standard Google login, or one of a number of other services. A: Nick Johnson recently released an alpha version of a WSGI middleware that you could use. The API is very similar to the standard Users API in app engine. It is a way to support auth via OpenID (something Alex Martelli suggested in his answer). Therefore you are able to support Google as Identity Provider as well as others. If you only want to support Google accounts for some reason, you could certainly only whitelist them though. Nick's blog announcement also lists some things to consider (these might be deal-breakers for you): Users are identified uniquely by their OpenID endpoint. You can't construct a User object without specifying an OpenID URL. Nicknames and email addresses are user-supplied, so they're not guaranteed unique or validated. is_current_user_admin() is not yet implemented. login: clauses in app.yaml are not affected by AEoid - they still authenticate using the regular Users API. A: You might consider OpenID, through any of the various open-source app engine projects for the purpose, such as this one for Django. You can't use the existing Users module with those (save perhaps with some serious hacking, but I have not attempted such feats and would not necessarily recommend them;-), but the various projects in question tend to offer usable replacements. Making your own login pages is also not too hard with these approaches, of course, since you start with all the sources to the "OpenID consumer" you choose to use. I don't know if all the domains you want to support are OpenID providers (though I don't see why any site supporting its own user logins wouldn't also be an OpenID provider -- it's easy and makes it more valuable for users to have logins on that site!-), but I hope this will take you some part of the way towards your goal!
Customize login in Google App Engine
I need to add few more options for login and therefore need to customize create_login_url with some HTML code. Is there a way to add on your code in default login screen of Google? Environment: Python (Google App Engine) I want to continue having the default Google ext class Users behavior in place.
[ "You can't customize the login page. Allowing you to do so would introduce the possibility of XSS vulnerabilities, as well as making it harder for users to identify a legitimate login page.\nIf you want to provide for federated login, you may want to simply redirect users to an interstitial page that allows them to pick standard Google login, or one of a number of other services.\n", "Nick Johnson recently released an alpha version of a WSGI middleware that you could use. The API is very similar to the standard Users API in app engine. It is a way to support auth via OpenID (something Alex Martelli suggested in his answer). Therefore you are able to support Google as Identity Provider as well as others. If you only want to support Google accounts for some reason, you could certainly only whitelist them though.\nNick's blog announcement also lists some things to consider (these might be deal-breakers for you):\n\nUsers are identified uniquely by their OpenID endpoint.\nYou can't construct a User object without specifying an OpenID URL.\nNicknames and email addresses are user-supplied, so they're not guaranteed unique or validated.\nis_current_user_admin() is not yet implemented.\nlogin: clauses in app.yaml are not affected by AEoid - they still authenticate using the regular Users API.\n\n", "You might consider OpenID, through any of the various open-source app engine projects for the purpose, such as this one for Django.\nYou can't use the existing Users module with those (save perhaps with some serious hacking, but I have not attempted such feats and would not necessarily recommend them;-), but the various projects in question tend to offer usable replacements.\nMaking your own login pages is also not too hard with these approaches, of course, since you start with all the sources to the \"OpenID consumer\" you choose to use.\nI don't know if all the domains you want to support are OpenID providers (though I don't see why any site supporting its own user logins wouldn't also be an OpenID provider -- it's easy and makes it more valuable for users to have logins on that site!-), but I hope this will take you some part of the way towards your goal!\n" ]
[ 2, 2, 1 ]
[]
[]
[ "authentication", "google_app_engine", "python", "registration" ]
stackoverflow_0000994965_authentication_google_app_engine_python_registration.txt
Q: How to change the default property on a set in python and Google AppEngine In the following code: class ClassA(db.Model): name = db.StringProperty() class ClassB(db.Model): name = db.StringProperty() deleted_flag = db.BooleanProperty() classA = db.ReferenceProperty(ClassA) ClassA will have a property called classb_set. When I call classb_set within code, I do not want it to return items that have the deleted_flag = true. How can I change the default filter on the classb_set query? My first instinct is to create another method in ClassA that does this filter, but is there a way that keeps the classb_set a property? A: You can always use a Python property to accomplish your goal: class ClassA(db.Model): name = db.StringProperty() def __get_classBdeleted(self): return self.classB_set.filter('deleted_flag =', 'True') classBdeleted = property(__get_classBdeleted) class ClassB(db.Model): name = db.StringProperty() deleted_flag = db.BooleanProperty() classA = db.ReferenceProperty(ClassA)
How to change the default property on a set in python and Google AppEngine
In the following code: class ClassA(db.Model): name = db.StringProperty() class ClassB(db.Model): name = db.StringProperty() deleted_flag = db.BooleanProperty() classA = db.ReferenceProperty(ClassA) ClassA will have a property called classb_set. When I call classb_set within code, I do not want it to return items that have the deleted_flag = true. How can I change the default filter on the classb_set query? My first instinct is to create another method in ClassA that does this filter, but is there a way that keeps the classb_set a property?
[ "You can always use a Python property to accomplish your goal:\nclass ClassA(db.Model):\n name = db.StringProperty()\n\n def __get_classBdeleted(self):\n return self.classB_set.filter('deleted_flag =', 'True')\n\n classBdeleted = property(__get_classBdeleted)\n\nclass ClassB(db.Model):\n name = db.StringProperty()\n deleted_flag = db.BooleanProperty()\n classA = db.ReferenceProperty(ClassA)\n\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001951379_google_app_engine_python.txt