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: does someone know how to show content on screen (covering up any window) using Ruby or Python? using Ruby or Python, does someone know how to draw on the screen, covering up any other window? Kind of like, press a key, and the program will show current weather or stock quote on the screen (using the whole screen as the canvas), and then press the key again, and everything restores to the same as before? (like Mac OS X's dash board). A: You could use the systems dashboard (desktop widgets, or whatever it's called) API. In order to do that you need bindings to it for Python or Ruby. Alternatively you could use some generic gui toolkit or application framework and just create a frameless window with transparent background. Then you need to be sure that the chosen toolkit supports 'always-on-top' options on your desired platform(s). A: If you are on windows you can directly draw to desktop dc(device context) using win32api e.g. just for fun try this :) >>> import win32ui >>> import win32gui >>> hdc = win32ui.CreateDCFromHandle( win32gui.GetDC( 0 ) ) >>> hdc.DrawText("Wow it works", (100, 100, 200, 200)) >>> hdc.LineTo(500,500) but that won't be very useful ,as not erasable best bet would be to use a transparent window or window with a cutout region (atleast on windows that is possible) or even if you can't draw transparent on some system you can grab the current screen and display it as background of you window that would give a transparent effect A: I would recommend PyGame.
does someone know how to show content on screen (covering up any window) using Ruby or Python?
using Ruby or Python, does someone know how to draw on the screen, covering up any other window? Kind of like, press a key, and the program will show current weather or stock quote on the screen (using the whole screen as the canvas), and then press the key again, and everything restores to the same as before? (like Mac OS X's dash board).
[ "You could use the systems dashboard (desktop widgets, or whatever it's called) API. In order to do that you need bindings to it for Python or Ruby.\nAlternatively you could use some generic gui toolkit or application framework and just create a frameless window with transparent background. Then you need to be sure that the chosen toolkit supports 'always-on-top' options on your desired platform(s).\n", "If you are on windows you can directly draw to desktop dc(device context) using win32api\ne.g. just for fun try this :)\n>>> import win32ui\n>>> import win32gui\n>>> hdc = win32ui.CreateDCFromHandle( win32gui.GetDC( 0 ) )\n>>> hdc.DrawText(\"Wow it works\", (100, 100, 200, 200))\n>>> hdc.LineTo(500,500)\n\nbut that won't be very useful ,as not erasable\nbest bet would be to use a transparent window or window with a cutout region (atleast on windows that is possible)\nor even if you can't draw transparent on some system you can grab the current screen and display it as background of you window that would give a transparent effect\n", "I would recommend PyGame.\n" ]
[ 4, 2, 1 ]
[]
[]
[ "python", "ruby", "user_interface" ]
stackoverflow_0000872737_python_ruby_user_interface.txt
Q: Python list of objects with random attributes (Edit: randrange is just random.randrange, I didn't write my own RNG) I'm trying to create a list of instances of a class I defined. Here's the entire class (by request): from random import randrange class Poly: points = [0] * 8 fill = 'red' alpha = 1.0 def __init__(self, width=100, height=100): for i in range(0, 8, 2): self.points[i] = randrange(width) self.points[i+1] = randrange(height) self.alpha = random() return Seems to work fine: >>> for i in range(5): Poly().points [28, 64, 93, 26, 15, 31, 44, 50] [24, 14, 47, 14, 35, 17, 63, 62] [99, 28, 90, 29, 56, 59, 57, 33] [62, 56, 48, 28, 40, 73, 70, 99] [99, 32, 27, 99, 42, 57, 86, 12] But if I try to create a list of these objects, I get separate instances (different memory addresses) but they all have the same random values: >>> p = [] >>> for i in range(5): p.append(Poly()) >>> p [<gen_image.Poly instance at 0x02D773C8>, <gen_image.Poly instance at 0x02D77FD0>, <gen_image.Poly instance at 0x0321D030>, <gen_image.Poly instance at 0x02D51E40>, <gen_image.Poly instance at 0x02D51DA0>] >>> for poly in p: print poly.points [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] What's going on here? And what's the right way to do what I'm trying to do? A: Move the creation of the array into the __init__ method. You're working with a shared array among all objects. The reason the first shows different is that you print the contents of that array before you construct a new Poly object and thus trample over the array contents. If you had kept them around and inspected them later they would all appear to have the same contents as the last one you generated. Oh, and try not to simplify code when posting questions. Always post complete, but short, programs that reproduce the problem. Here's a short, but complete, program that demonstrates the problem you're having: from random import randrange class Poly: points = [0]*8 def __init__(self, width=100, height=100): for i in range(0, 8, 2): self.points[i] = randrange(width) self.points[i+1] = randrange(height) return p1 = Poly() print "p1:", p1.points p2 = Poly() print "p2:", p2.points print "p1:", p1.points Sample output: [C:\Temp] test.py p1: [19, 5, 1, 46, 93, 18, 18, 57] p2: [92, 71, 42, 84, 54, 29, 27, 71] p1: [92, 71, 42, 84, 54, 29, 27, 71] Notice how p1 changed. The fixed code could be as simple as: from random import randrange class Poly: def __init__(self, width=100, height=100): self.points = [0]*8 for i in range(0, 8, 2): self.points[i] = randrange(width) self.points[i+1] = randrange(height) return although I prefer the append variant that @Doug posted here A: You have a class attribute Poly.points. In your __init__ method you do self.points[i] = .... Now this makes Python use Poly.points which is shared by all instances. But you want points to be an instance attribute. I'd suggest this: class Poly: # you don't need this here #points = [0] * 8 #fill = 'red' #alpha = 1.0 def __init__(self, width=100, height=100): self.points = [0]*8 self.fill = 'red' self.alpha = random() for i in range(0, 8, 2): self.points[i] = randrange(width) self.points[i+1] = randrange(height) A: The points lists are all being shared. It would appear that you're declaring points to be a list on the instance or class. This isn't the way of doing things in Python if you don't want to share the list between instances. Try: def __init__(self, width=100, height=100): self.points = [] #Create a new list for i in range(0, 8, 2): self.points.append(randrange(width)) self.points.append(randrange(height)) return
Python list of objects with random attributes
(Edit: randrange is just random.randrange, I didn't write my own RNG) I'm trying to create a list of instances of a class I defined. Here's the entire class (by request): from random import randrange class Poly: points = [0] * 8 fill = 'red' alpha = 1.0 def __init__(self, width=100, height=100): for i in range(0, 8, 2): self.points[i] = randrange(width) self.points[i+1] = randrange(height) self.alpha = random() return Seems to work fine: >>> for i in range(5): Poly().points [28, 64, 93, 26, 15, 31, 44, 50] [24, 14, 47, 14, 35, 17, 63, 62] [99, 28, 90, 29, 56, 59, 57, 33] [62, 56, 48, 28, 40, 73, 70, 99] [99, 32, 27, 99, 42, 57, 86, 12] But if I try to create a list of these objects, I get separate instances (different memory addresses) but they all have the same random values: >>> p = [] >>> for i in range(5): p.append(Poly()) >>> p [<gen_image.Poly instance at 0x02D773C8>, <gen_image.Poly instance at 0x02D77FD0>, <gen_image.Poly instance at 0x0321D030>, <gen_image.Poly instance at 0x02D51E40>, <gen_image.Poly instance at 0x02D51DA0>] >>> for poly in p: print poly.points [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] [75, 18, 5, 76, 6, 64, 95, 54] What's going on here? And what's the right way to do what I'm trying to do?
[ "Move the creation of the array into the __init__ method.\nYou're working with a shared array among all objects.\nThe reason the first shows different is that you print the contents of that array before you construct a new Poly object and thus trample over the array contents. If you had kept them around and inspected them later they would all appear to have the same contents as the last one you generated.\nOh, and try not to simplify code when posting questions. Always post complete, but short, programs that reproduce the problem.\nHere's a short, but complete, program that demonstrates the problem you're having:\nfrom random import randrange\nclass Poly:\n points = [0]*8\n\n def __init__(self, width=100, height=100):\n for i in range(0, 8, 2):\n self.points[i] = randrange(width)\n self.points[i+1] = randrange(height)\n return\n\np1 = Poly()\nprint \"p1:\", p1.points\np2 = Poly()\nprint \"p2:\", p2.points\nprint \"p1:\", p1.points\n\nSample output:\n[C:\\Temp] test.py\np1: [19, 5, 1, 46, 93, 18, 18, 57]\np2: [92, 71, 42, 84, 54, 29, 27, 71]\np1: [92, 71, 42, 84, 54, 29, 27, 71]\n\nNotice how p1 changed.\nThe fixed code could be as simple as:\nfrom random import randrange\nclass Poly:\n def __init__(self, width=100, height=100):\n self.points = [0]*8\n for i in range(0, 8, 2):\n self.points[i] = randrange(width)\n self.points[i+1] = randrange(height)\n return\n\nalthough I prefer the append variant that @Doug posted here\n", "You have a class attribute Poly.points. In your __init__ method you do self.points[i] = .... Now this makes Python use Poly.points which is shared by all instances. But you want points to be an instance attribute. I'd suggest this:\nclass Poly:\n # you don't need this here\n #points = [0] * 8\n #fill = 'red'\n #alpha = 1.0\n\n def __init__(self, width=100, height=100):\n self.points = [0]*8\n self.fill = 'red'\n self.alpha = random()\n for i in range(0, 8, 2):\n self.points[i] = randrange(width)\n self.points[i+1] = randrange(height)\n\n", "The points lists are all being shared. It would appear that you're declaring points to be a list on the instance or class. This isn't the way of doing things in Python if you don't want to share the list between instances. Try:\n\ndef __init__(self, width=100, height=100):\n self.points = [] #Create a new list\n for i in range(0, 8, 2):\n self.points.append(randrange(width))\n self.points.append(randrange(height))\n return\n\n\n" ]
[ 6, 4, 2 ]
[ "ok here is the culprit\npoints = [[0]] * 8\nit assigns same list ([0]) 8 times instead you should do something like\npoints = []\nfor i in range(8):\n points.append([])\n\n" ]
[ -1 ]
[ "python", "random" ]
stackoverflow_0000874121_python_random.txt
Q: Print space after each word what is an easy/effective way to combine an array of words together with a space in between, but no space before or after? I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though. Preferably code in Java, Python, or Ruby. A: Well, in Python it will be straightforward using join: values = ["this", "is", "your", "array"] result = " ".join(values) A: Yes, this is what join was made for. Here is the Ruby version: ["word", "another", "word"].join(" ") <flamebait> As you can see, Ruby makes join a method on Array instead of String, and is thus far more sensible. </flamebait> A: What you want is String.Join, but since just saying that probably won't help you, here are some Join implementations in Java. Here's a string utility that has a join for Java. A: Straight from one of my existing utilz classes C:\java\home\src\krc\utilz\Arrayz.java package krc.utilz; /** * A bunch of static helper methods for arrays of String's. * @See also krc.utilz.IntArrays for arrays of int's. */ public abstract class Arrayz { /** * Concetenates the values in the given array into a string, seperated by FS. * @param FS String - Field Seperator - Name borrowed from awk * @param Object[] a - array to be concatentated * @return a string representation of the given array. */ public static String join(String FS, Object[] a) { if (a==null||a.length==0) return ""; StringBuilder result = new StringBuilder(String.valueOf(a[0])); for(int i=1; i<a.length; i++) { result.append(FS); result.append(String.valueOf(a[i])); } return result.toString(); } .... } Cheers. Keith. EDIT Here's a quick & dirty performance comparison, using java.util.Arrays as a baseline. Note that hotspot cost is amortized over 100 iterations, and should be (more or less) the same for all three techniques... krc.utilz.RandomString and krc.utilz.Arrayz are both available upon request, just ask. package forums; import java.util.Arrays; import krc.utilz.Arrayz; import krc.utilz.RandomString; class ArrayToStringPerformanceTest { private static final int NS2MS = 1000000; // 1 millisecond (1/10^3) = 1,000,000 nanoseconds (1/10^9) public static void main(String[] args) { try { String[] array = randomStrings(100*1000, 16); long start, stop; String result; final int TIMES = 100; long time1=0L, time2=0L, time3=0L; for (int i=0; i<TIMES; i++) { start = System.nanoTime(); result = Arrays.toString(array); stop = System.nanoTime(); //System.out.println("Arrays.toString took "+(stop-start)+" ns"); time1 += (stop-start); start = System.nanoTime(); result = Arrayz.join(", ", array); stop = System.nanoTime(); //System.out.println("Arrayz.join took "+(stop-start)+" ns"); time2 += (stop-start); start = System.nanoTime(); result = arrayToString(array, ", "); stop = System.nanoTime(); //System.out.println("arrayToString took "+(stop-start)+" ns"); time3 += (stop-start); } System.out.format("java.util.Arrays.toString took "+(time1/TIMES/NS2MS)+" ms"); System.out.format("krc.utilz.Arrayz.join took "+(time2/TIMES/NS2MS)+" ms"); System.out.format("arrayToString took "+(time3/TIMES/NS2MS)+" ms"); } catch (Exception e) { e.printStackTrace(); } } public static String arrayToString(String[] array, String spacer) { StringBuffer result = new StringBuffer(); for ( int i=0; i<array.length; i++ ) { result.append( array[i] + ((i+1<array.length)?spacer:"") ); } return result.toString(); } private static String[] randomStrings(int howMany, int length) { RandomString random = new RandomString(); String[] a = new String[howMany]; for ( int i=0; i<howMany; i++) { a[i] = random.nextString(length); } return a; } } /* C:\Java\home\src\forums>"C:\Program Files\Java\jdk1.6.0_12\bin\java.exe" -Xms512m -Xmx1536m -enableassertions -cp C:\Java\home\classes forums.ArrayToStringPerformanceTest java.util.Arrays.toString took 26 ms krc.utilz.Arrayz.join took 32 ms arrayToString took 59 ms */ See also Doomspork's suggestion, and my comment thereon. Cheers. Keith. A: Java could be accomplished with something like this: public static String arrayToString(String[] array, String spacer) { StringBuffer result = new StringBuffer(); for(int i = 0 ; i < array.length ; i++) { result.append(array[i] + ((i + 1 < array.length) ? spacer : "")); } return result.toString(); } A: This will work in Ruby as well: ['a', 'list', 'of', 'words'] * " " A: Well, I know Python has a function like this, and I'm assuming Ruby does, and Java. The join function takes an array of strings (depending on the language, it can be other types) and joins them together with a character (or another string) that you choose. Python code: wordString = " ".join(["word", "another", "word"]) Otherwise, you can loop through, the array, adding the word and a space, and test if it is the last element. If it is, just add the word, and not the space. Python code again: (thanks to PTBNL for the suggestion) wordArray = ["word", "another", "word"] wordString = "" for i in range(0, len(wordArray) - 1): wordString += wordArray[i] + " " wordString += wordArray[len(wordArray) - 1] A: In Python, you ask the join string to join an iterable of strings: alist= ["array", "of", "strings"] output= " ".join(alist) If this notation seems weird to you, you can do the same thing in a different syntax: output= str.join(" ", alist) This works for any iterable (lists, tuples, dictionaries, generators, generator expressions…), as long as the items are all strings (or unicode strings). You can substitute unicode for str (or u' ' for ' ') if you want a unicode result.
Print space after each word
what is an easy/effective way to combine an array of words together with a space in between, but no space before or after? I suppose it is possible to remove the space after combining everything in a loop (something like sum += (term + " "))...I don't like it though. Preferably code in Java, Python, or Ruby.
[ "Well, in Python it will be straightforward using join:\nvalues = [\"this\", \"is\", \"your\", \"array\"]\nresult = \" \".join(values)\n\n", "Yes, this is what join was made for. Here is the Ruby version:\n[\"word\", \"another\", \"word\"].join(\" \")\n\n<flamebait> As you can see, Ruby makes join a method on Array instead of String, and is thus far more sensible. </flamebait>\n", "What you want is String.Join, but since just saying that probably won't help you, here are some Join implementations in Java. Here's a string utility that has a join for Java.\n", "Straight from one of my existing utilz classes \nC:\\java\\home\\src\\krc\\utilz\\Arrayz.java\npackage krc.utilz;\n\n/**\n * A bunch of static helper methods for arrays of String's.\n * @See also krc.utilz.IntArrays for arrays of int's.\n */\npublic abstract class Arrayz\n{\n /**\n * Concetenates the values in the given array into a string, seperated by FS.\n * @param FS String - Field Seperator - Name borrowed from awk\n * @param Object[] a - array to be concatentated\n * @return a string representation of the given array.\n */\n public static String join(String FS, Object[] a) {\n if (a==null||a.length==0) return \"\";\n StringBuilder result = new StringBuilder(String.valueOf(a[0]));\n for(int i=1; i<a.length; i++) {\n result.append(FS);\n result.append(String.valueOf(a[i]));\n }\n return result.toString();\n }\n\n ....\n\n}\n\nCheers. Keith.\n\nEDIT\nHere's a quick & dirty performance comparison, using java.util.Arrays as a baseline.\nNote that hotspot cost is amortized over 100 iterations, and should be (more or less) the same for all three techniques... krc.utilz.RandomString and krc.utilz.Arrayz are both available upon request, just ask.\npackage forums;\n\nimport java.util.Arrays;\nimport krc.utilz.Arrayz;\nimport krc.utilz.RandomString;\n\nclass ArrayToStringPerformanceTest\n{\n private static final int NS2MS = 1000000; // 1 millisecond (1/10^3) = 1,000,000 nanoseconds (1/10^9)\n\n public static void main(String[] args) {\n try {\n String[] array = randomStrings(100*1000, 16);\n long start, stop;\n String result;\n\n final int TIMES = 100;\n long time1=0L, time2=0L, time3=0L;\n\n for (int i=0; i<TIMES; i++) {\n\n start = System.nanoTime();\n result = Arrays.toString(array);\n stop = System.nanoTime();\n //System.out.println(\"Arrays.toString took \"+(stop-start)+\" ns\");\n time1 += (stop-start);\n\n start = System.nanoTime();\n result = Arrayz.join(\", \", array);\n stop = System.nanoTime();\n //System.out.println(\"Arrayz.join took \"+(stop-start)+\" ns\");\n time2 += (stop-start);\n\n start = System.nanoTime();\n result = arrayToString(array, \", \");\n stop = System.nanoTime();\n //System.out.println(\"arrayToString took \"+(stop-start)+\" ns\");\n time3 += (stop-start);\n\n }\n System.out.format(\"java.util.Arrays.toString took \"+(time1/TIMES/NS2MS)+\" ms\");\n System.out.format(\"krc.utilz.Arrayz.join took \"+(time2/TIMES/NS2MS)+\" ms\");\n System.out.format(\"arrayToString took \"+(time3/TIMES/NS2MS)+\" ms\");\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public static String arrayToString(String[] array, String spacer) {\n StringBuffer result = new StringBuffer();\n for ( int i=0; i<array.length; i++ ) {\n result.append( array[i] + ((i+1<array.length)?spacer:\"\") );\n }\n return result.toString();\n }\n\n private static String[] randomStrings(int howMany, int length) {\n RandomString random = new RandomString();\n String[] a = new String[howMany];\n for ( int i=0; i<howMany; i++) {\n a[i] = random.nextString(length);\n }\n return a;\n }\n\n}\n\n/*\nC:\\Java\\home\\src\\forums>\"C:\\Program Files\\Java\\jdk1.6.0_12\\bin\\java.exe\" -Xms512m -Xmx1536m -enableassertions -cp C:\\Java\\home\\classes forums.ArrayToStringPerformanceTest\n\njava.util.Arrays.toString took 26 ms\nkrc.utilz.Arrayz.join took 32 ms\narrayToString took 59 ms\n*/\n\nSee also Doomspork's suggestion, and my comment thereon.\nCheers. Keith.\n", "Java could be accomplished with something like this:\npublic static String arrayToString(String[] array, String spacer) {\n StringBuffer result = new StringBuffer();\n for(int i = 0 ; i < array.length ; i++) {\n result.append(array[i] + ((i + 1 < array.length) ? spacer : \"\"));\n }\n return result.toString();\n}\n\n", "This will work in Ruby as well:\n['a', 'list', 'of', 'words'] * \" \"\n\n", "Well, I know Python has a function like this, and I'm assuming Ruby does, and Java.\nThe join function takes an array of strings (depending on the language, it can be other types) and joins them together with a character (or another string) that you choose.\nPython code:\nwordString = \" \".join([\"word\", \"another\", \"word\"])\n\nOtherwise, you can loop through, the array, adding the word and a space, and test if it is the last element. If it is, just add the word, and not the space.\nPython code again: (thanks to PTBNL for the suggestion)\nwordArray = [\"word\", \"another\", \"word\"]\nwordString = \"\"\nfor i in range(0, len(wordArray) - 1):\n wordString += wordArray[i] + \" \"\nwordString += wordArray[len(wordArray) - 1]\n\n", "In Python, you ask the join string to join an iterable of strings:\nalist= [\"array\", \"of\", \"strings\"]\noutput= \" \".join(alist)\n\nIf this notation seems weird to you, you can do the same thing in a different syntax:\noutput= str.join(\" \", alist)\n\nThis works for any iterable (lists, tuples, dictionaries, generators, generator expressions…), as long as the items are all strings (or unicode strings).\nYou can substitute unicode for str (or u' ' for ' ') if you want a unicode result.\n" ]
[ 13, 7, 1, 1, 1, 1, 0, 0 ]
[ "Let's not forget the good old-fashioned\n for s in strArray do\n print s\n print \" \"\n\n" ]
[ -3 ]
[ "java", "python", "ruby", "string" ]
stackoverflow_0000873790_java_python_ruby_string.txt
Q: List of non-datastore types in AppEngine? I'm building an AppEngine model class. I need a simple list of tuples: class MyTuple(object): field1 = "string" field2 = 3 class MyModel(db.Model): the_list = db.ListProperty(MyTuple) This does not work, since AppEngine does not accept MyTuple as a valid field. Solutions I can think of: Make MyTuple extend db.Model. But doesn't that mean every entry in the list will be stored in a dedicated MyTuple table? Make it a list of strings, which are a "serialized" form of MyTuple; add parsing (unserializing) code. Yuck. Maintain two lists (one of strings, one of ints). Another yuck. Any other solution that I'm missing? A: In app-engine-patch there's a FakeModelListProperty and FakeModel (import both from ragendja.dbutils). Derive MyTuple from FakeModel and set fields = ('field1', 'field2'). Those fields will automatically get converted to JSON when stored in the list, so you could manually edit them in a textarea. Of course, this only works for primitive types (strings, integers, etc.). Take a look at the source if this doesn't suffice. http://code.google.com/p/app-engine-patch/
List of non-datastore types in AppEngine?
I'm building an AppEngine model class. I need a simple list of tuples: class MyTuple(object): field1 = "string" field2 = 3 class MyModel(db.Model): the_list = db.ListProperty(MyTuple) This does not work, since AppEngine does not accept MyTuple as a valid field. Solutions I can think of: Make MyTuple extend db.Model. But doesn't that mean every entry in the list will be stored in a dedicated MyTuple table? Make it a list of strings, which are a "serialized" form of MyTuple; add parsing (unserializing) code. Yuck. Maintain two lists (one of strings, one of ints). Another yuck. Any other solution that I'm missing?
[ "In app-engine-patch there's a FakeModelListProperty and FakeModel (import both from ragendja.dbutils). Derive MyTuple from FakeModel and set fields = ('field1', 'field2'). Those fields will automatically get converted to JSON when stored in the list, so you could manually edit them in a textarea. Of course, this only works for primitive types (strings, integers, etc.). Take a look at the source if this doesn't suffice.\nhttp://code.google.com/p/app-engine-patch/\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "orm", "python" ]
stackoverflow_0000874122_google_app_engine_orm_python.txt
Q: Python ctypes and function pointers This is related to my other question, but I felt like I should ask it in a new question. Basically FLAC uses function pointers for callbacks, and to implement callbacks with ctypes, you use CFUNCTYPE to prototype them, and then you use the prototype() function to create them. The problem I have with this is that I figured that I would create my callback function as such (I am not showing the structures that I have recreated, FLAC__Frame is a Structure): write_callback_prototype = CFUNCTYPE(c_int, c_void_p, POINTER(FLAC__Frame), POINTER(c_int32), v_void_p) The problem that I have is the implementation. FLAC__Frame is never instantiated by the programmer, it's only called from from the initialization function, and the processing functions.I have to write the callback function myself, but he problem is that I don't know how I would do this, so if anyone knows how I should do this, then some help would be greatly appreciated. A: According to the ctypes callback docs you can define python function def my_callback(a, p, frame, p1, p2) pass and then create a pointer to a C callable function like this: callback = write_callback_prototype(my_callback) This function pointer can then be passed into FLAC A: The problem that I have is the implementation. FLAC__Frame is never instantiated by the programmer, it's only called from from the initialization function, and the processing functions.I have to write the callback function myself, but he problem is that I don't know how I would do this, so if anyone knows how I should do this, then some help would be greatly appreciated. In that case, just use: import ctypes class FLAC__Frame(ctypes.Structure): pass and pretend that it is already defined, and do not care because you only need pointer to it, which is basically position in memory.
Python ctypes and function pointers
This is related to my other question, but I felt like I should ask it in a new question. Basically FLAC uses function pointers for callbacks, and to implement callbacks with ctypes, you use CFUNCTYPE to prototype them, and then you use the prototype() function to create them. The problem I have with this is that I figured that I would create my callback function as such (I am not showing the structures that I have recreated, FLAC__Frame is a Structure): write_callback_prototype = CFUNCTYPE(c_int, c_void_p, POINTER(FLAC__Frame), POINTER(c_int32), v_void_p) The problem that I have is the implementation. FLAC__Frame is never instantiated by the programmer, it's only called from from the initialization function, and the processing functions.I have to write the callback function myself, but he problem is that I don't know how I would do this, so if anyone knows how I should do this, then some help would be greatly appreciated.
[ "According to the ctypes callback docs you can define python function\ndef my_callback(a, p, frame, p1, p2)\n pass\n\nand then create a pointer to a C callable function like this:\ncallback = write_callback_prototype(my_callback)\n\nThis function pointer can then be passed into FLAC\n", "\nThe problem that I have is the implementation. FLAC__Frame is never instantiated by the programmer, it's only called from from the initialization function, and the processing functions.I have to write the callback function myself, but he problem is that I don't know how I would do this, so if anyone knows how I should do this, then some help would be greatly appreciated.\n\nIn that case, just use:\nimport ctypes\n\nclass FLAC__Frame(ctypes.Structure):\n pass\n\nand pretend that it is already defined, and do not care because you only need pointer to it, which is basically position in memory.\n" ]
[ 7, 1 ]
[]
[]
[ "ctypes", "function_pointers", "python" ]
stackoverflow_0000874245_ctypes_function_pointers_python.txt
Q: Python: load words from file into a set I have a simple text file with several thousands of words, each in its own line, e.g. aardvark hello piper I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose): my_set = set(open('filename.txt')) The above code produces a set with the following entries (each word is followed by a space and new-line character: ("aardvark \n", "hello \n", "piper \n") What's the simplest way to load the file into a set but get rid of the space and \n? Thanks A: The strip() method of strings removes whitespace from both ends. set(line.strip() for line in open('filename.txt')) A: Just load all file data and split it, it will take care of one word per line or multiple words per line separated by spaces, also it will be faster to load whole file at once unless your file is in GBs words = set(open('filename.txt').read().split()) A: my_set = set(map(str.strip, open('filename.txt'))) A: To remove only the right hand spaces. set(map(str.rstrip, open('filename.txt'))) A: with open("filename.txt") as f: mySet = map(str.rstrip, f) If you want to use this in Python 2.5, you need from __future__ import with_statement A: with open("filename.txt") as f: s = set([line.rstrip('\n') for line in f])
Python: load words from file into a set
I have a simple text file with several thousands of words, each in its own line, e.g. aardvark hello piper I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose): my_set = set(open('filename.txt')) The above code produces a set with the following entries (each word is followed by a space and new-line character: ("aardvark \n", "hello \n", "piper \n") What's the simplest way to load the file into a set but get rid of the space and \n? Thanks
[ "The strip() method of strings removes whitespace from both ends.\nset(line.strip() for line in open('filename.txt'))\n\n", "Just load all file data and split it, it will take care of one word per line or multiple words per line separated by spaces, also it will be faster to load whole file at once unless your file is in GBs\nwords = set(open('filename.txt').read().split())\n\n", "my_set = set(map(str.strip, open('filename.txt')))\n\n", "To remove only the right hand spaces.\nset(map(str.rstrip, open('filename.txt')))\n\n", "with open(\"filename.txt\") as f:\n mySet = map(str.rstrip, f)\n\nIf you want to use this in Python 2.5, you need\nfrom __future__ import with_statement\n\n", "with open(\"filename.txt\") as f:\n s = set([line.rstrip('\\n') for line in f])\n\n" ]
[ 75, 16, 4, 2, 1, 1 ]
[]
[]
[ "python", "text_files" ]
stackoverflow_0000874017_python_text_files.txt
Q: How do I put a scrollbar inside of a gtk.ComboBoxEntry? I have a Combobox with over a hundred of entries and it is very awkward to skim through with out a scrollbar. alt text http://img211.imageshack.us/img211/6972/screenshotprubapy.png I want to do exactly what is in the picture. With the scrollbar on the right so It'd be easier to move through the entries. I used gtk.Combo to make that example but the problem is that is deprecated. I need an example of how would you do what is exactly the picture. A: import pygtk import gtk import gobject def window_delete_event(*args): return False def window_destroy(*args): gtk.main_quit() if __name__ == '__main__': win = gtk.Window() # combo's model model = gtk.ListStore(gobject.TYPE_STRING) for n in xrange(100): model.append([str(n)]) # combo combo = gtk.ComboBoxEntry(model) win.add(combo) # combo's style style = gtk.rc_parse_string(''' style "my-style" { GtkComboBox::appears-as-list = 1 } widget "*.mycombo" style "my-style" ''') combo.set_name('mycombo') combo.set_style(style) win.show_all() win.connect('delete-event', window_delete_event) win.connect('destroy', window_destroy) gtk.main()
How do I put a scrollbar inside of a gtk.ComboBoxEntry?
I have a Combobox with over a hundred of entries and it is very awkward to skim through with out a scrollbar. alt text http://img211.imageshack.us/img211/6972/screenshotprubapy.png I want to do exactly what is in the picture. With the scrollbar on the right so It'd be easier to move through the entries. I used gtk.Combo to make that example but the problem is that is deprecated. I need an example of how would you do what is exactly the picture.
[ "import pygtk\nimport gtk\nimport gobject\n\ndef window_delete_event(*args):\n return False\n\ndef window_destroy(*args):\n gtk.main_quit()\n\nif __name__ == '__main__':\n win = gtk.Window()\n\n # combo's model\n model = gtk.ListStore(gobject.TYPE_STRING)\n for n in xrange(100):\n model.append([str(n)])\n\n # combo\n combo = gtk.ComboBoxEntry(model)\n win.add(combo)\n\n # combo's style\n style = gtk.rc_parse_string('''\n style \"my-style\" { GtkComboBox::appears-as-list = 1 }\n widget \"*.mycombo\" style \"my-style\"\n ''')\n combo.set_name('mycombo')\n combo.set_style(style)\n\n win.show_all()\n win.connect('delete-event', window_delete_event)\n win.connect('destroy', window_destroy)\n gtk.main()\n\n" ]
[ 2 ]
[]
[]
[ "pygtk", "python", "user_interface" ]
stackoverflow_0000873328_pygtk_python_user_interface.txt
Q: wxPython: Path problems when exporting a bitmap I have a module which starts a wxPython app, which loads a wx.Bitmap from file for use as a toolbar button. It looks like this: wx.Bitmap("images\\new.png", wx.BITMAP_TYPE_ANY). All works well when I run that module by itself, but when I try to import and run it from a different module which is in a different directory, wxPython raises an exception. (The exception is something internal regarding the toolbar, which I think just means it's not loading the bitmap right.) What should I do? A: "images\new.png" is a relative path, so when bitmap gets loaded it will depened what is the cur dir so either you set cur dir os.chdir("location to images folder") or have a function which loads relative to your program e.g. def getProgramFolder(): moduleFile = __file__ moduleDir = os.path.split(os.path.abspath(moduleFile))[0] programFolder = os.path.abspath(moduleDir) return programFolder bmpFilePath = os.path.join(getProgramFolder(), "images\\new.png") A: The wxPython FAQ recommends using a tool called img2py.py to embed icon files into a Python module. This tool comes with the wxPython distribution. Here is an example of embedding toolbar icons.
wxPython: Path problems when exporting a bitmap
I have a module which starts a wxPython app, which loads a wx.Bitmap from file for use as a toolbar button. It looks like this: wx.Bitmap("images\\new.png", wx.BITMAP_TYPE_ANY). All works well when I run that module by itself, but when I try to import and run it from a different module which is in a different directory, wxPython raises an exception. (The exception is something internal regarding the toolbar, which I think just means it's not loading the bitmap right.) What should I do?
[ "\"images\\new.png\" is a relative path, so when bitmap gets loaded it will depened what is the cur dir\nso either you set cur dir\nos.chdir(\"location to images folder\")\n\nor \nhave a function which loads relative to your program e.g.\ndef getProgramFolder():\n moduleFile = __file__\n moduleDir = os.path.split(os.path.abspath(moduleFile))[0]\n programFolder = os.path.abspath(moduleDir)\n return programFolder\n\nbmpFilePath = os.path.join(getProgramFolder(), \"images\\\\new.png\")\n\n", "The wxPython FAQ recommends using a tool called img2py.py to embed icon files into a Python module. This tool comes with the wxPython distribution.\nHere is an example of embedding toolbar icons.\n" ]
[ 2, 1 ]
[]
[]
[ "path", "python", "wxpython" ]
stackoverflow_0000874625_path_python_wxpython.txt
Q: wxPython launches my app twice when importing a sub-package I'm sorry for the verbal description. I have a wxPython app in a file called applicationwindow.py that resides in a package called garlicsimwx. When I launch the app by launching the aforementioned file, it all works well. However, I have created a file rundemo.py in a folder which contains the garlicsimwx package, which runs the app as well. When I use rundemo.py, the app launches, however, when the main wx.Frame imports a sub-package of garlicsimwx, namely simulations.life, for some reason a new instance of my application is created (i.e., a new identical window pops out.) I have tried stepping through the commands one-by-one, and although the bug happens only after importing the sub-package, the import statement doesn't directly cause it. Only when control returns to PyApp.MainLoop the second window opens. How do I stop this? A: I think you have code in one of your modules that looks like this: import wx class MyFrame(wx.Frame): def __init__(...): ... frame = MyFrame(...) The frame will be created when this module is first imported. To prevent that, use the common Python idiom: import wx class MyFrame(wx.Frame): def __init__(...): ... if __name__ == '__main__': frame = MyFrame(...) Did I guess correctly? A: You could create a global boolean variable like g_window_was_drawn and check it in the function that does the work of creating a window. The value would be false at the start of the program and would change to True when first creating a window. The function that creates the window would check if the g_window_was_drawn is already true, and if it is, it would throw an exception. Then You will have a nice stacktrace telling You who is responsible of executing this function. I hope that helps You find it. I'm sorry for the verbal solution ;) A: Got it: There was no if __name__=='__main__': in my rundemo file. It was actually a multiprocessing issue: The new window was opened in a separate process.
wxPython launches my app twice when importing a sub-package
I'm sorry for the verbal description. I have a wxPython app in a file called applicationwindow.py that resides in a package called garlicsimwx. When I launch the app by launching the aforementioned file, it all works well. However, I have created a file rundemo.py in a folder which contains the garlicsimwx package, which runs the app as well. When I use rundemo.py, the app launches, however, when the main wx.Frame imports a sub-package of garlicsimwx, namely simulations.life, for some reason a new instance of my application is created (i.e., a new identical window pops out.) I have tried stepping through the commands one-by-one, and although the bug happens only after importing the sub-package, the import statement doesn't directly cause it. Only when control returns to PyApp.MainLoop the second window opens. How do I stop this?
[ "I think you have code in one of your modules that looks like this:\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(...):\n ...\n\nframe = MyFrame(...)\n\nThe frame will be created when this module is first imported. To prevent that, use the common Python idiom:\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(...):\n ...\n\nif __name__ == '__main__':\n frame = MyFrame(...)\n\nDid I guess correctly?\n", "You could create a global boolean variable like g_window_was_drawn and check it in the function that does the work of creating a window. The value would be false at the start of the program and would change to True when first creating a window. The function that creates the window would check if the g_window_was_drawn is already true, and if it is, it would throw an exception. Then You will have a nice stacktrace telling You who is responsible of executing this function.\nI hope that helps You find it. I'm sorry for the verbal solution ;)\n", "Got it: There was no\nif __name__=='__main__':\n\nin my rundemo file. It was actually a multiprocessing issue: The new window was opened in a separate process.\n" ]
[ 4, 0, 0 ]
[]
[]
[ "import", "python", "wxpython" ]
stackoverflow_0000874856_import_python_wxpython.txt
Q: Receiving 16-bit integers in Python I'm reading 16-bit integers from a piece of hardware over the serial port. Using Python, how can I get the LSB and MSB right, and make Python understand that it is a 16 bit signed integer I'm fiddling with, and not just two bytes of data? A: Try using the struct module: import struct # read 2 bytes from hardware as a string s = hardware.readbytes(2) # h means signed short # < means "little-endian, standard size (16 bit)" # > means "big-endian, standard size (16 bit)" value = struct.unpack("<h", s) # hardware returns little-endian value = struct.unpack(">h", s) # hardware returns big-endian
Receiving 16-bit integers in Python
I'm reading 16-bit integers from a piece of hardware over the serial port. Using Python, how can I get the LSB and MSB right, and make Python understand that it is a 16 bit signed integer I'm fiddling with, and not just two bytes of data?
[ "Try using the struct module:\nimport struct\n# read 2 bytes from hardware as a string\ns = hardware.readbytes(2)\n# h means signed short\n# < means \"little-endian, standard size (16 bit)\"\n# > means \"big-endian, standard size (16 bit)\"\nvalue = struct.unpack(\"<h\", s) # hardware returns little-endian\nvalue = struct.unpack(\">h\", s) # hardware returns big-endian\n\n" ]
[ 24 ]
[]
[]
[ "integer", "python" ]
stackoverflow_0000875046_integer_python.txt
Q: How to print a list, dict or collection of objects, in Python I have written a class in python that implements __str__(self) but when I use print on a list containing instances of this class, I just get the default output <__main__.DSequence instance at 0x4b8c10>. Is there another magic function I need to implement to get this to work, or do I have to write a custom print function? Here's the class: class DSequence: def __init__(self, sid, seq): """Sequence object for a dummy dna string""" self.sid = sid self.seq = seq def __iter__(self): return self def __str__(self): return '[' + str(self.sid) + '] -> [' + str(self.seq) + ']' def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.seq[self.index] A: Yes, you need to use __repr__. A quick example of its behavior: >>> class Foo: ... def __str__(self): ... return '__str__' ... def __repr__(self): ... return '__repr__' ... >>> bar = Foo() >>> bar __repr__ >>> print bar __str__ >>> repr(bar) '__repr__' >>> str(bar) '__str__' However, if you don't define a __str__, it falls back to __repr__, although this isn't recommended: >>> class Foo: ... def __repr__(self): ... return '__repr__' ... >>> bar = Foo() >>> bar __repr__ >>> print bar __repr__ All things considered, as the manual recommends, __repr__ is used for debugging and should return something representative of the object. A: Just a little enhancement avoiding the + for concatenating: def __str__(self): return '[%s] -> [%s]' % (self.sid, self.seq)
How to print a list, dict or collection of objects, in Python
I have written a class in python that implements __str__(self) but when I use print on a list containing instances of this class, I just get the default output <__main__.DSequence instance at 0x4b8c10>. Is there another magic function I need to implement to get this to work, or do I have to write a custom print function? Here's the class: class DSequence: def __init__(self, sid, seq): """Sequence object for a dummy dna string""" self.sid = sid self.seq = seq def __iter__(self): return self def __str__(self): return '[' + str(self.sid) + '] -> [' + str(self.seq) + ']' def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.seq[self.index]
[ "Yes, you need to use __repr__. A quick example of its behavior:\n>>> class Foo:\n... def __str__(self):\n... return '__str__'\n... def __repr__(self):\n... return '__repr__'\n...\n>>> bar = Foo()\n>>> bar \n__repr__\n>>> print bar \n__str__\n>>> repr(bar)\n'__repr__'\n>>> str(bar)\n'__str__'\n\nHowever, if you don't define a __str__, it falls back to __repr__, although this isn't recommended:\n>>> class Foo:\n... def __repr__(self):\n... return '__repr__'\n...\n>>> bar = Foo()\n>>> bar\n__repr__\n>>> print bar\n__repr__\n\nAll things considered, as the manual recommends, __repr__ is used for debugging and should return something representative of the object.\n", "Just a little enhancement avoiding the + for concatenating:\ndef __str__(self):\n return '[%s] -> [%s]' % (self.sid, self.seq)\n\n" ]
[ 24, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0000875074_list_python.txt
Q: Timesheet Program to Track Days/Hours worked? Say I make a program that keeps track of the days I worked and the hours I worked, would I use a dictionary? And how would I differentiate from a Monday on week 1 from a Monday on week 2? How do I get it to store this information after I close the program? (Python Language) A: A dictionary is a good way to store the data while your program is running. There are a number of ways to add some data permanence (so it's around after you close the program). The Python modules pickle and shelve are useful and easy to use. One issue with these is that you can't easily inspect the data outside of a Python program. There are also modules to read and write text files in the JSON and XML formats, and JSON is particularly easy to read in a text editor. If you aren't already proficient, the databases like MySQL are way more than you need for a personal program like you mention and unless you want to invest some time into learning how to use them, you should go with a simpler solution. As for the Monday on week 1 vs week 2, you have many options. You could use the actual date (this seems like a good idea to me), or you could key the dictionary with tuples, like ("Monday", 1). The main rule is that dictionary keys must be immutable (ints, strings, tuples -- that contain only immutable objects, etc), but not (dictionaries, lists, etc). A: I would probably create a timesheet object for each week, or pay period. Each timesheet object might have a collection of days, with hours worked or times clocked in and out. For persistent storage for a web site, I'd use a database like mysql. For an application running on a single machine I'd maybe use pickle, or a flat file system maybe. A: I took the opposite approach when designing this application for my own use. In my experience, the biggest problem with timekeeping applications is data entry. So I decided to make my app use the simplest and most flexible data entry tool available: a text editor. I keep notes in a text file and intermingle timekeeping entries in them, so an excerpt looks like this: Monday 5/10/09 release script ok this week open a case on the whole code-table-foreign-key thing - CUS1 2.0 Generate and release version 1.0.45. need to get dma to spec out the RESPRB configuration, see case 810 MH section complete - one to go! - CUS2 4.0 Configure and test Mental Health section. Tuesday 5/11/09 ... and so on I'm consistent in starting each day with the proper heading, and the format of actual timekeeping entries, as you can see, is pretty simple. A simple scanner and state machine is all it takes to extract the data - basically, I just look for lines that begin with a weekday or a hyphen, and ignore everything else. So that the program doesn't get too slow when parsing the notes files, I create a new notes file every year. (Even at the end of December the parsing process doesn't take more than 1/16 of a second.) I wouldn't do it this way if I had to process hundreds of peoples' timekeeping entries, because the user does have to have a bit of a clue, and the parsing time would begin to add up after a while. On the other hand, keeping this data in a human-readable text file that I can store other stuff in (and keep under version control, and diff, and so on) is just incredibly useful.
Timesheet Program to Track Days/Hours worked?
Say I make a program that keeps track of the days I worked and the hours I worked, would I use a dictionary? And how would I differentiate from a Monday on week 1 from a Monday on week 2? How do I get it to store this information after I close the program? (Python Language)
[ "A dictionary is a good way to store the data while your program is running.\nThere are a number of ways to add some data permanence (so it's around after you close the program). The Python modules pickle and shelve are useful and easy to use. One issue with these is that you can't easily inspect the data outside of a Python program. There are also modules to read and write text files in the JSON and XML formats, and JSON is particularly easy to read in a text editor. If you aren't already proficient, the databases like MySQL are way more than you need for a personal program like you mention and unless you want to invest some time into learning how to use them, you should go with a simpler solution.\nAs for the Monday on week 1 vs week 2, you have many options. You could use the actual date (this seems like a good idea to me), or you could key the dictionary with tuples, like (\"Monday\", 1). The main rule is that dictionary keys must be immutable (ints, strings, tuples -- that contain only immutable objects, etc), but not (dictionaries, lists, etc).\n", "I would probably create a timesheet object for each week, or pay period. Each timesheet object might have a collection of days, with hours worked or times clocked in and out. \nFor persistent storage for a web site, I'd use a database like mysql. For an application running on a single machine I'd maybe use pickle, or a flat file system maybe.\n", "I took the opposite approach when designing this application for my own use.\nIn my experience, the biggest problem with timekeeping applications is data entry. So I decided to make my app use the simplest and most flexible data entry tool available: a text editor. I keep notes in a text file and intermingle timekeeping entries in them, so an excerpt looks like this:\nMonday 5/10/09\n\nrelease script ok this week\nopen a case on the whole code-table-foreign-key thing\n\n- CUS1 2.0 Generate and release version 1.0.45.\n\nneed to get dma to spec out the RESPRB configuration, see case 810\nMH section complete - one to go!\n\n- CUS2 4.0 Configure and test Mental Health section.\n\nTuesday 5/11/09\n\n... and so on\n\nI'm consistent in starting each day with the proper heading, and the format of actual timekeeping entries, as you can see, is pretty simple. A simple scanner and state machine is all it takes to extract the data - basically, I just look for lines that begin with a weekday or a hyphen, and ignore everything else.\nSo that the program doesn't get too slow when parsing the notes files, I create a new notes file every year. (Even at the end of December the parsing process doesn't take more than 1/16 of a second.)\nI wouldn't do it this way if I had to process hundreds of peoples' timekeeping entries, because the user does have to have a bit of a clue, and the parsing time would begin to add up after a while. On the other hand, keeping this data in a human-readable text file that I can store other stuff in (and keep under version control, and diff, and so on) is just incredibly useful.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000873564_python.txt
Q: Admin privileges for script how can i check admin-privileges for my script during running? A: The concept of "admin-privileges" in our day of fine grained privilege control is becoming hard to define. If you are running on unix with "traditional" access control model, getting the effective user id (available in os module) and checking that against root (0) could be what you are looking for. If you know accessing a file on the system requires the privileges you want your script to have, you can use the os.access() to check if you are privileged enough. Unfortunately there is no easy nor portable method to give. You need to find out or define the security model used, what system provided APIs are available to query and set privileges and try to locate (or possibly implement yourself) the appropriate python modules that can be used to access the API. The classic question, why do you need to find out? What if your script tries to do what it needs to do and "just" catches and properly handles failures? A: On Unix you can check whether you are root using the os.getuid function: os.getuid() == 0 and "root" or "not root" A: If you're just trying to see if you have access to a certain file that requires administrative rights, a good way to check would be: import os print os.access("/path/to/file", os.W_OK) #replace W_OK with R_OK to test for read permissions On the other hand, if you really need to know if a user is an administrative account, you can also use this code on Windows 2000 and higher: import ctypes print ctypes.windll.shell32.IsUserAnAdmin() Therefore, a better, cross-platform way to find out if an user is an administrator is: import ctypes, os try: is_admin = os.getuid() == 0 except: is_admin = ctypes.windll.shell32.IsUserAnAdmin() print is_admin Of course, this method will only detect if the user is root on Unix, or is a member of the Administrators group on Windows. However, this is sufficient for most purposes, in my opinion. Also note that this will fail on Windows versions below 2000, as well as Windows ME, since those are DOS-based versions of Windows and don't have any notion of permissions.
Admin privileges for script
how can i check admin-privileges for my script during running?
[ "The concept of \"admin-privileges\" in our day of fine grained privilege control is becoming hard to define. If you are running on unix with \"traditional\" access control model, getting the effective user id (available in os module) and checking that against root (0) could be what you are looking for. If you know accessing a file on the system requires the privileges you want your script to have, you can use the os.access() to check if you are privileged enough.\nUnfortunately there is no easy nor portable method to give. You need to find out or define the security model used, what system provided APIs are available to query and set privileges and try to locate (or possibly implement yourself) the appropriate python modules that can be used to access the API.\nThe classic question, why do you need to find out? What if your script tries to do what it needs to do and \"just\" catches and properly handles failures?\n", "On Unix you can check whether you are root using the os.getuid function:\nos.getuid() == 0 and \"root\" or \"not root\"\n\n", "If you're just trying to see if you have access to a certain file that requires administrative rights, a good way to check would be:\nimport os\nprint os.access(\"/path/to/file\", os.W_OK) \n#replace W_OK with R_OK to test for read permissions\n\nOn the other hand, if you really need to know if a user is an administrative account, you can also use this code on Windows 2000 and higher:\nimport ctypes\nprint ctypes.windll.shell32.IsUserAnAdmin()\n\nTherefore, a better, cross-platform way to find out if an user is an administrator is:\nimport ctypes, os\ntry:\n is_admin = os.getuid() == 0\nexcept:\n is_admin = ctypes.windll.shell32.IsUserAnAdmin()\n\nprint is_admin\n\nOf course, this method will only detect if the user is root on Unix, or is a member of the Administrators group on Windows. However, this is sufficient for most purposes, in my opinion.\nAlso note that this will fail on Windows versions below 2000, as well as Windows ME, since those are DOS-based versions of Windows and don't have any notion of permissions.\n" ]
[ 7, 5, 3 ]
[]
[]
[ "python", "root", "sudo", "unix" ]
stackoverflow_0000874476_python_root_sudo_unix.txt
Q: Daemon python wrapper "subprocess I/O timed out", need some directions I am not very familiar with the way of creating a daemon in Python, therefore wheb trying to install and run a third party open source TeX Python Wrapper i got bite by an error i do nor really understand. I added some print to help debugging. The faulty one is called texdp.py When i run mathrand which calls texdp server start, i get the following error output_fds {8: 'dvi', 5: 'log', 6: 'logfile', 7: 'err'} input_fds 3 readable, writable [] [3] outflds, inputflds: [8, 5, 6, 7] [3] pointer len_str: 0 63 folder fd: 7 readable, writable [5] [] outflds, inputflds: [8, 5, 6, 7] [] pointer len_str: 63 63 folder fd: 7 readable, writable [5] [] outflds, inputflds: [8, 5, 6, 7] [] pointer len_str: 63 63 folder fd: 5 readable, writable [] [] outflds, inputflds: [8, 5, 6, 7] [] pointer len_str: 63 63 folder fd: 5 SUB IO ERROR: readable [] pointer == len_str: 63 , 63 Traceback (most recent call last): File "/usr/local/bin/mathtrand", line 18, in <module> server.start() File "/usr/local/lib/python2.6/dist-packages/mathtran/server.py", line 71, in start self.secplain.start() File "/usr/local/lib/python2.6/dist-packages/tex/texdp.py", line 159, in start self.process(self._params.start) File "/usr/local/lib/python2.6/dist-packages/tex/texdp.py", line 175, in process value = self._process(str + self._params.done, self._params.done_str) File "/usr/local/lib/python2.6/dist-packages/tex/texdp.py", line 210, in _process raise SubprocessError, 'subprocess I/O timed out' The part of the code responsible is attached and located around line 200 in the method def _process. I have no idea of where to start looking, and what does this error really means. Any help is more than welcome. https://texd.svn.sourceforge.net/svnroot/texd/trunk/py/tex/texdp.py # Copyright: (c) 2007 The Open University, Milton Keynes, UK # License: GPL version 2 or (at your option) any later version. # Author: Jonathan Fine <[email protected]>, <[email protected]> """Wrapper around TeX process, to handle input and output. Further comments to go here. """ __version__ = '$Revision: 116 $'[11:-2] # $Source$ # TODO: Move interface instances to elsewhere. # TODO: error recovery, e.g. undefined control sequence. # TODO: Abnormal exit is leaving orphaned processes. # TODO: Refactor _process into tex.util, share with metapostdp. import os # Create directories and fifos from select import select # Helps handle i/o to TeX process from tex.util import make_nonblocking # For non-blocking file descriptor from tex.util import DaemonSubprocess from tex.dviopcode import FNT_DEF1, FNT_DEF4 import signal class SubprocessError(EnvironmentError): pass # TODO: This belongs elsewhere. class Interface(object): """Stores useful, but format specific, constants.""" def __init__(self, **kwargs): # TODO: Be more specific about the parameters. self.__dict__ = kwargs # TeX knows about these fonts, but Python does not yet know. # This list created by command: $tex --ini '&plain' \\dump preloaded_fonts = ( 'cmr10', 'cmr9', 'cmr8', 'cmr7', 'cmr6', 'cmr5', 'cmmi10', 'cmmi9', 'cmmi8', 'cmmi7', 'cmmi6', 'cmmi5', 'cmsy10', 'cmsy9', 'cmsy8', 'cmsy7', 'cmsy6', 'cmsy5', 'cmex10', 'cmss10', 'cmssq8', 'cmssi10', 'cmssqi8', 'cmbx10', 'cmbx9', 'cmbx8', 'cmbx7', 'cmbx6', 'cmbx5', 'cmtt10', 'cmtt9', 'cmtt8', 'cmsltt10', 'cmsl10', 'cmsl9', 'cmsl8', 'cmti10', 'cmti9', 'cmti8', 'cmti7', 'cmu10', 'cmmib10', 'cmbsy10', 'cmcsc10', 'cmssbx10', 'cmdunh10', 'cmr7 scaled 2074', 'cmtt10 scaled 1440', 'cmssbx10 scaled 1440', 'manfnt', ) # Ship out a page that starts with a font def. load_font_template = \ r'''%% \begingroup \hoffset 0sp \voffset 0sp \setbox0\hbox{\font\tmp %s\relax\tmp M}%% \ht0 0sp \shipout\box 0 \endgroup ''' secplain_load_font_template = \ r'''%% \_begingroup \_hoffset 0sp \_voffset 0sp \_setbox0\_hbox{\_font\_tmp %s\_relax\_tmp M}%% \_ht0 0sp \_shipout\_box 0 \_endgroup ''' plain = Interface(format='plain', start = r'\shipout\hbox{}' '\n', done = '\n' r'\immediate\write16{DONE}\read-1to\temp ' '\n', done_str = 'DONE\n', stop = '\end' '\n', preloaded_fonts = preloaded_fonts, load_font_template = load_font_template, ) secplain = Interface(format='secplain', start = r'\_shipout\_hbox{}' '\n', done = '\n' r'\_immediate\_write16{DONE}\_read-1to\_temp ' '\n', done_str = 'DONE\n', stop = '\_end' '\n', preloaded_fonts = preloaded_fonts, load_font_template = secplain_load_font_template, ) class Texdp(DaemonSubprocess): """Wrapper around TeX process that handles input and output. More comments go here. """ _fifos = ('texput.tex', 'texput.log', 'texput.dvi') def _make_args(self): # Don Knuth created plain.fmt, renamed by some to tex.fmt. fmt = self._params.format if fmt == 'plain' or fmt == 'tex': fmt = '' else: fmt = '--fmt=' + fmt # Build up the arguments list. args = ('tex', '--ipc',) args += ('--output-comment=""',) # Don't record time of run. if fmt: args += (fmt,) args += ('texput.tex',) return args def start(self): super(Texdp, self).start() # Start the TeX process. # We will now initialise TeX, and conprocessnect to file descriptors. # We need to do some low-level input/output, in order to # manage long input strings. Therefore, we use file # descriptors rather than file objects. # We map output fds to what will be a dictionary key. ofd = self._output_fd_dict = {} cwd = self._cwd # Shorthand. child = self._child # For us, stdin and stdout are special. self._stdin = child.stdin.fileno() self._stdout = child.stdout.fileno() # Read stdout and stderr to 'log' and 'err' respectively. ofd[self._stdout] = 'log' ofd[child.stderr.fileno()] = 'err' # Open 'texput.tex', and block until it is available, which is # when TeX has started. Then make 'texput.tex' non-blocking, # in case of a long write. self._texin = os.open(os.path.join(cwd, 'texput.tex'), os.O_WRONLY) make_nonblocking(self._texin) # Read 'texput.log' and 'texput.dvi' to 'logfile' and 'dvi'. for src, tgt in (('texput.log', 'logfile'), ('texput.dvi', 'dvi')): fd = os.open(os.path.join(cwd, src), os.O_RDONLY|os.O_NONBLOCK) ofd[fd] = tgt # Ship out blank page, and initialise preloaded fonts. self.process(self._params.start) self._fontdefs = [] for font_spec in self._params.preloaded_fonts: self.load_new_font(font_spec) def process(self, str): "Return dictionary with log, dvi, logfile and err entries." # TeX will read the data, following by the 'done' command. # The 'done' command will cause TeX to write the 'done_str', # which signals the end of the process. It will also pause # TeX for input. # TODO: I do not know why the pause is required, but it is. # Remove it here and in the _params, and the program hangs. value = self._process(str + self._params.done, self._params.done_str) self._child.stdin.write('\n') # TeX is paused for input. return value def _process(self, str, done_str): # Write str, and read output, until we are done. Then gather # up the accumulated output, and return as a dictionary. The # input string might be long. Later, we might allow writing to # stdin, in response to errors. # Initialisation. print "output_fds ", self._output_fd_dict output_fds = self._output_fd_dict.keys() print "input_fds ", self._texin input_fds = [self._texin] accumulator = {} for fd in output_fds: accumulator[fd] = [] pointer, len_str = 0, len(str) # The main input/ouput loop. # TOD0: magic number, timeout. done = False while not done: readable, writable = select(output_fds, input_fds, [], 0.1)[0:2] print "readable, writable", readable, writable, " outflds, inputflds: ", output_fds, input_fds print "pointer len_str: ", pointer, len_str print "folder fd: ", fd if not readable and pointer == len_str: print "SUB IO ERROR: readable", readable, " pointer == len_str:", pointer, ",", len_str os.kill(self._child.pid, signal.SIGKILL) self._child.wait() raise SubprocessError, 'subprocess I/O timed out' if pointer != len_str and writable: written = os.write(self._texin, str[pointer:pointer+4096]) pointer += written if pointer == len_str: input_fds = [] for fd in readable: if self._child.poll() is not None: raise SubprocessError, 'read from terminated subprocess' tmp = os.read(fd, 4096) if fd == self._stdout: if tmp.endswith(done_str): tmp = tmp[:-len(done_str)] done = True accumulator[fd].append(tmp) if pointer != len_str: raise SystemError, "TeX said 'done' before end of input." # Join accumulated output, create and return ouput dictionary. value = {} for fd, name in self._output_fd_dict.items(): value[name] = ''.join(accumulator[fd]) return value def load_new_font(self, font_spec): """Tell both TeX and Python about a new font. Raises an exception if the font is not new. """ # Ask TeX to load font, and ship out page that uses it. command mathtran= self._params.load_font_template % font_spec dvi = self.process(command)['dvi'] bytes = dvi[45:-1] # Page body. opcode = ord(bytes[0]) # First opcode. # The first opcode should be a fontdef, which we extract. if FNT_DEF1 <= opcode <= FNT_DEF4: body_len = (2 + (opcode - FNT_DEF1) + 12 # Checksum, scale, design size. + 2) # Length of 'area' and font name. name_len = ord(bytes[body_len - 2]) \ + ord(bytes[body_len - 1]) fontdef = bytes[:body_len + name_len] self._fontdefs.append(fontdef) return else: raise ValueError, "font '%s' not new or not found" % font_spec A: The timeout is based on the select call readable, writable = select(output_fds, input_fds, [], 0.1)[0:2] The timeout is 0.1 seconds. Is this appropriate? The variable names are murky ("pointer" makes little sense in Python). However, it appears that if nothing happens on 0.1 seconds, a "timeout" is raised. Weirdly, this program opens files to communicate with a subprocess. That's very odd to be "sharing" a file with a subprocess. Usually we do one of two things -- use pipes to communicate actively with a subprocess or use files to leave the subprocess run on its own. Here's a simpler design. Put the input into the input file. Run the Tex daemon subprocess until it finishes or you're tired of waiting for it. If you're tired of waiting for it, kill it. Else Look at the status from the wait function Read the output file. That's pretty much all you need. And there will be no mysterious "pause", no low-level I/O, no non-blocking I/O. If, for some reason you need to communicate with the subprocess, then you should look at replacing the files with pipes (which aren't shared and are probably a better for for whatever you're doing.)
Daemon python wrapper "subprocess I/O timed out", need some directions
I am not very familiar with the way of creating a daemon in Python, therefore wheb trying to install and run a third party open source TeX Python Wrapper i got bite by an error i do nor really understand. I added some print to help debugging. The faulty one is called texdp.py When i run mathrand which calls texdp server start, i get the following error output_fds {8: 'dvi', 5: 'log', 6: 'logfile', 7: 'err'} input_fds 3 readable, writable [] [3] outflds, inputflds: [8, 5, 6, 7] [3] pointer len_str: 0 63 folder fd: 7 readable, writable [5] [] outflds, inputflds: [8, 5, 6, 7] [] pointer len_str: 63 63 folder fd: 7 readable, writable [5] [] outflds, inputflds: [8, 5, 6, 7] [] pointer len_str: 63 63 folder fd: 5 readable, writable [] [] outflds, inputflds: [8, 5, 6, 7] [] pointer len_str: 63 63 folder fd: 5 SUB IO ERROR: readable [] pointer == len_str: 63 , 63 Traceback (most recent call last): File "/usr/local/bin/mathtrand", line 18, in <module> server.start() File "/usr/local/lib/python2.6/dist-packages/mathtran/server.py", line 71, in start self.secplain.start() File "/usr/local/lib/python2.6/dist-packages/tex/texdp.py", line 159, in start self.process(self._params.start) File "/usr/local/lib/python2.6/dist-packages/tex/texdp.py", line 175, in process value = self._process(str + self._params.done, self._params.done_str) File "/usr/local/lib/python2.6/dist-packages/tex/texdp.py", line 210, in _process raise SubprocessError, 'subprocess I/O timed out' The part of the code responsible is attached and located around line 200 in the method def _process. I have no idea of where to start looking, and what does this error really means. Any help is more than welcome. https://texd.svn.sourceforge.net/svnroot/texd/trunk/py/tex/texdp.py # Copyright: (c) 2007 The Open University, Milton Keynes, UK # License: GPL version 2 or (at your option) any later version. # Author: Jonathan Fine <[email protected]>, <[email protected]> """Wrapper around TeX process, to handle input and output. Further comments to go here. """ __version__ = '$Revision: 116 $'[11:-2] # $Source$ # TODO: Move interface instances to elsewhere. # TODO: error recovery, e.g. undefined control sequence. # TODO: Abnormal exit is leaving orphaned processes. # TODO: Refactor _process into tex.util, share with metapostdp. import os # Create directories and fifos from select import select # Helps handle i/o to TeX process from tex.util import make_nonblocking # For non-blocking file descriptor from tex.util import DaemonSubprocess from tex.dviopcode import FNT_DEF1, FNT_DEF4 import signal class SubprocessError(EnvironmentError): pass # TODO: This belongs elsewhere. class Interface(object): """Stores useful, but format specific, constants.""" def __init__(self, **kwargs): # TODO: Be more specific about the parameters. self.__dict__ = kwargs # TeX knows about these fonts, but Python does not yet know. # This list created by command: $tex --ini '&plain' \\dump preloaded_fonts = ( 'cmr10', 'cmr9', 'cmr8', 'cmr7', 'cmr6', 'cmr5', 'cmmi10', 'cmmi9', 'cmmi8', 'cmmi7', 'cmmi6', 'cmmi5', 'cmsy10', 'cmsy9', 'cmsy8', 'cmsy7', 'cmsy6', 'cmsy5', 'cmex10', 'cmss10', 'cmssq8', 'cmssi10', 'cmssqi8', 'cmbx10', 'cmbx9', 'cmbx8', 'cmbx7', 'cmbx6', 'cmbx5', 'cmtt10', 'cmtt9', 'cmtt8', 'cmsltt10', 'cmsl10', 'cmsl9', 'cmsl8', 'cmti10', 'cmti9', 'cmti8', 'cmti7', 'cmu10', 'cmmib10', 'cmbsy10', 'cmcsc10', 'cmssbx10', 'cmdunh10', 'cmr7 scaled 2074', 'cmtt10 scaled 1440', 'cmssbx10 scaled 1440', 'manfnt', ) # Ship out a page that starts with a font def. load_font_template = \ r'''%% \begingroup \hoffset 0sp \voffset 0sp \setbox0\hbox{\font\tmp %s\relax\tmp M}%% \ht0 0sp \shipout\box 0 \endgroup ''' secplain_load_font_template = \ r'''%% \_begingroup \_hoffset 0sp \_voffset 0sp \_setbox0\_hbox{\_font\_tmp %s\_relax\_tmp M}%% \_ht0 0sp \_shipout\_box 0 \_endgroup ''' plain = Interface(format='plain', start = r'\shipout\hbox{}' '\n', done = '\n' r'\immediate\write16{DONE}\read-1to\temp ' '\n', done_str = 'DONE\n', stop = '\end' '\n', preloaded_fonts = preloaded_fonts, load_font_template = load_font_template, ) secplain = Interface(format='secplain', start = r'\_shipout\_hbox{}' '\n', done = '\n' r'\_immediate\_write16{DONE}\_read-1to\_temp ' '\n', done_str = 'DONE\n', stop = '\_end' '\n', preloaded_fonts = preloaded_fonts, load_font_template = secplain_load_font_template, ) class Texdp(DaemonSubprocess): """Wrapper around TeX process that handles input and output. More comments go here. """ _fifos = ('texput.tex', 'texput.log', 'texput.dvi') def _make_args(self): # Don Knuth created plain.fmt, renamed by some to tex.fmt. fmt = self._params.format if fmt == 'plain' or fmt == 'tex': fmt = '' else: fmt = '--fmt=' + fmt # Build up the arguments list. args = ('tex', '--ipc',) args += ('--output-comment=""',) # Don't record time of run. if fmt: args += (fmt,) args += ('texput.tex',) return args def start(self): super(Texdp, self).start() # Start the TeX process. # We will now initialise TeX, and conprocessnect to file descriptors. # We need to do some low-level input/output, in order to # manage long input strings. Therefore, we use file # descriptors rather than file objects. # We map output fds to what will be a dictionary key. ofd = self._output_fd_dict = {} cwd = self._cwd # Shorthand. child = self._child # For us, stdin and stdout are special. self._stdin = child.stdin.fileno() self._stdout = child.stdout.fileno() # Read stdout and stderr to 'log' and 'err' respectively. ofd[self._stdout] = 'log' ofd[child.stderr.fileno()] = 'err' # Open 'texput.tex', and block until it is available, which is # when TeX has started. Then make 'texput.tex' non-blocking, # in case of a long write. self._texin = os.open(os.path.join(cwd, 'texput.tex'), os.O_WRONLY) make_nonblocking(self._texin) # Read 'texput.log' and 'texput.dvi' to 'logfile' and 'dvi'. for src, tgt in (('texput.log', 'logfile'), ('texput.dvi', 'dvi')): fd = os.open(os.path.join(cwd, src), os.O_RDONLY|os.O_NONBLOCK) ofd[fd] = tgt # Ship out blank page, and initialise preloaded fonts. self.process(self._params.start) self._fontdefs = [] for font_spec in self._params.preloaded_fonts: self.load_new_font(font_spec) def process(self, str): "Return dictionary with log, dvi, logfile and err entries." # TeX will read the data, following by the 'done' command. # The 'done' command will cause TeX to write the 'done_str', # which signals the end of the process. It will also pause # TeX for input. # TODO: I do not know why the pause is required, but it is. # Remove it here and in the _params, and the program hangs. value = self._process(str + self._params.done, self._params.done_str) self._child.stdin.write('\n') # TeX is paused for input. return value def _process(self, str, done_str): # Write str, and read output, until we are done. Then gather # up the accumulated output, and return as a dictionary. The # input string might be long. Later, we might allow writing to # stdin, in response to errors. # Initialisation. print "output_fds ", self._output_fd_dict output_fds = self._output_fd_dict.keys() print "input_fds ", self._texin input_fds = [self._texin] accumulator = {} for fd in output_fds: accumulator[fd] = [] pointer, len_str = 0, len(str) # The main input/ouput loop. # TOD0: magic number, timeout. done = False while not done: readable, writable = select(output_fds, input_fds, [], 0.1)[0:2] print "readable, writable", readable, writable, " outflds, inputflds: ", output_fds, input_fds print "pointer len_str: ", pointer, len_str print "folder fd: ", fd if not readable and pointer == len_str: print "SUB IO ERROR: readable", readable, " pointer == len_str:", pointer, ",", len_str os.kill(self._child.pid, signal.SIGKILL) self._child.wait() raise SubprocessError, 'subprocess I/O timed out' if pointer != len_str and writable: written = os.write(self._texin, str[pointer:pointer+4096]) pointer += written if pointer == len_str: input_fds = [] for fd in readable: if self._child.poll() is not None: raise SubprocessError, 'read from terminated subprocess' tmp = os.read(fd, 4096) if fd == self._stdout: if tmp.endswith(done_str): tmp = tmp[:-len(done_str)] done = True accumulator[fd].append(tmp) if pointer != len_str: raise SystemError, "TeX said 'done' before end of input." # Join accumulated output, create and return ouput dictionary. value = {} for fd, name in self._output_fd_dict.items(): value[name] = ''.join(accumulator[fd]) return value def load_new_font(self, font_spec): """Tell both TeX and Python about a new font. Raises an exception if the font is not new. """ # Ask TeX to load font, and ship out page that uses it. command mathtran= self._params.load_font_template % font_spec dvi = self.process(command)['dvi'] bytes = dvi[45:-1] # Page body. opcode = ord(bytes[0]) # First opcode. # The first opcode should be a fontdef, which we extract. if FNT_DEF1 <= opcode <= FNT_DEF4: body_len = (2 + (opcode - FNT_DEF1) + 12 # Checksum, scale, design size. + 2) # Length of 'area' and font name. name_len = ord(bytes[body_len - 2]) \ + ord(bytes[body_len - 1]) fontdef = bytes[:body_len + name_len] self._fontdefs.append(fontdef) return else: raise ValueError, "font '%s' not new or not found" % font_spec
[ "The timeout is based on the select call \nreadable, writable = select(output_fds, input_fds, [], 0.1)[0:2]\n\nThe timeout is 0.1 seconds. Is this appropriate? \nThe variable names are murky (\"pointer\" makes little sense in Python). However, it appears that if nothing happens on 0.1 seconds, a \"timeout\" is raised.\n\nWeirdly, this program opens files to communicate with a subprocess. That's very odd to be \"sharing\" a file with a subprocess.\nUsually we do one of two things -- use pipes to communicate actively with a subprocess or use files to leave the subprocess run on its own.\nHere's a simpler design. \n\nPut the input into the input file.\nRun the Tex daemon subprocess until it finishes or you're tired of waiting for it.\nIf you're tired of waiting for it, kill it.\nElse\n\nLook at the status from the wait function\nRead the output file.\n\n\nThat's pretty much all you need. And there will be no mysterious \"pause\", no low-level I/O, no non-blocking I/O.\nIf, for some reason you need to communicate with the subprocess, then you should look at replacing the files with pipes (which aren't shared and are probably a better for for whatever you're doing.)\n" ]
[ 2 ]
[]
[]
[ "daemon", "python", "tex" ]
stackoverflow_0000875190_daemon_python_tex.txt
Q: PyQt: splash screen while loading "heavy" libraries My PyQt application that uses matplotlib takes several seconds to load for the first time, even on a fast machine (the second load time is much shorter as the DLLs are kept in memory by Windows). I'm wondering whether it's feasible to show a splash screen while the matplotlib library is being loaded. Where does the actual loading take place - is it when the from line is executed? If so, how can I make this line execute during the splash screen and still be able to use the module throughout the code? A related dilemma is how to test this - can I ask Windows to load the DLLs for every execution and not cache them? A: Yes, loading the module takes place at the line where the import statement is. If you create your QApplication and show your splash screen before that, you should be able to do what you want -- also you need to call QApplication.processEvents() whenever you need the splash screen to update with a new message.
PyQt: splash screen while loading "heavy" libraries
My PyQt application that uses matplotlib takes several seconds to load for the first time, even on a fast machine (the second load time is much shorter as the DLLs are kept in memory by Windows). I'm wondering whether it's feasible to show a splash screen while the matplotlib library is being loaded. Where does the actual loading take place - is it when the from line is executed? If so, how can I make this line execute during the splash screen and still be able to use the module throughout the code? A related dilemma is how to test this - can I ask Windows to load the DLLs for every execution and not cache them?
[ "Yes, loading the module takes place at the line where the import statement is. If you create your QApplication and show your splash screen before that, you should be able to do what you want -- also you need to call QApplication.processEvents() whenever you need the splash screen to update with a new message.\n" ]
[ 4 ]
[]
[]
[ "matplotlib", "performance", "pyqt", "python" ]
stackoverflow_0000876107_matplotlib_performance_pyqt_python.txt
Q: is there any AES encryption python library that will work well with python 3.0? I want to know is there any python 3.0 supported library for encryption. To encrypt files of 128 bits of data?? A: I suggest my open-source project slowaes, http://code.google.com/p/slowaes/ -- should be trivial to adapt if it doesn't work out of the box, as it's pure-Python (and for 128 bits of data, the "slow" part shouldn't matter). A: To properly encrypt data, you need more than just an encryption algorithm. It's probably best you find a complete library with documentation showing how to do things properly, if you absolutely must do it yourself. Encryption alone is not sufficient. How are you generating keys? What mode of operation are you using? Are you using a MAC on the data? Straight AES in ECB mode leaks information. Without a MAC, even though the data is encrypted, an attacker can still tamper with your data.
is there any AES encryption python library that will work well with python 3.0?
I want to know is there any python 3.0 supported library for encryption. To encrypt files of 128 bits of data??
[ "I suggest my open-source project slowaes, http://code.google.com/p/slowaes/ -- should be trivial to adapt if it doesn't work out of the box, as it's pure-Python (and for 128 bits of data, the \"slow\" part shouldn't matter).\n", "To properly encrypt data, you need more than just an encryption algorithm. It's probably best you find a complete library with documentation showing how to do things properly, if you absolutely must do it yourself. \nEncryption alone is not sufficient. How are you generating keys? What mode of operation are you using? Are you using a MAC on the data? \nStraight AES in ECB mode leaks information. Without a MAC, even though the data is encrypted, an attacker can still tamper with your data. \n" ]
[ 3, 0 ]
[]
[]
[ "aes", "encryption", "python" ]
stackoverflow_0000876258_aes_encryption_python.txt
Q: How to remove symbols from a string with Python? I'm a beginner with both Python and RegEx, and I would like to know how to make a string that takes symbols and replaces them with spaces. Any help is great. For example: how much for the maple syrup? $20.99? That's ricidulous!!! into: how much for the maple syrup 20 99 That s ridiculous A: One way, using regular expressions: >>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!" >>> re.sub(r'[^\w]', ' ', s) 'how much for the maple syrup 20 99 That s ridiculous ' \w will match alphanumeric characters and underscores [^\w] will match anything that's not alphanumeric or underscore A: Sometimes it takes longer to figure out the regex than to just write it out in python: import string s = "how much for the maple syrup? $20.99? That's ricidulous!!!" for char in string.punctuation: s = s.replace(char, ' ') If you need other characters you can change it to use a white-list or extend your black-list. Sample white-list: whitelist = string.letters + string.digits + ' ' new_s = '' for char in s: if char in whitelist: new_s += char else: new_s += ' ' Sample white-list using a generator-expression: whitelist = string.letters + string.digits + ' ' new_s = ''.join(c for c in s if c in whitelist) A: I often just open the console and look for the solution in the objects methods. Quite often it's already there: >>> a = "hello ' s" >>> dir(a) [ (....) 'partition', 'replace' (....)] >>> a.replace("'", " ") 'hello s' Short answer: Use string.replace().
How to remove symbols from a string with Python?
I'm a beginner with both Python and RegEx, and I would like to know how to make a string that takes symbols and replaces them with spaces. Any help is great. For example: how much for the maple syrup? $20.99? That's ricidulous!!! into: how much for the maple syrup 20 99 That s ridiculous
[ "One way, using regular expressions:\n>>> s = \"how much for the maple syrup? $20.99? That's ridiculous!!!\"\n>>> re.sub(r'[^\\w]', ' ', s)\n'how much for the maple syrup 20 99 That s ridiculous '\n\n\n\\w will match alphanumeric characters and underscores\n[^\\w] will match anything that's not alphanumeric or underscore\n\n", "Sometimes it takes longer to figure out the regex than to just write it out in python:\nimport string\ns = \"how much for the maple syrup? $20.99? That's ricidulous!!!\"\nfor char in string.punctuation:\n s = s.replace(char, ' ')\n\nIf you need other characters you can change it to use a white-list or extend your black-list.\nSample white-list:\nwhitelist = string.letters + string.digits + ' '\nnew_s = ''\nfor char in s:\n if char in whitelist:\n new_s += char\n else:\n new_s += ' '\n\nSample white-list using a generator-expression:\nwhitelist = string.letters + string.digits + ' '\nnew_s = ''.join(c for c in s if c in whitelist)\n\n", "I often just open the console and look for the solution in the objects methods. Quite often it's already there:\n>>> a = \"hello ' s\"\n>>> dir(a)\n[ (....) 'partition', 'replace' (....)]\n>>> a.replace(\"'\", \" \")\n'hello s'\n\nShort answer: Use string.replace().\n" ]
[ 196, 36, 12 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0000875968_python_regex_string.txt
Q: Django reusable app for like functionality as in friendfeed I am looking to implement "like" functionallity a bit similar as they do in friendfeed. Is there a django reusable app that already does this? Thanks! Nick. A: This sort of thing you should just write yourself from scratch. A 'like' in its most basic form is going to be an object with relations to a user and some other object. Look at the contenttypes framework docs to see how to use generic foreign keys for this. The only other thing you need to worry about is to make the create view idempotent. If you're new to django this is probably a fun little exercise to familiarise yourself with contenttypes. If you're not new, the whole app should take you less than an hour. I wouldn't go searching for a pluggable app either way. A: You could put your own together using parts of Pinax. There isn't one app that would do this for you as it's too specific and reusable Django apps are supposed to be very focussed. A: Search http://djangoplugables.com/
Django reusable app for like functionality as in friendfeed
I am looking to implement "like" functionallity a bit similar as they do in friendfeed. Is there a django reusable app that already does this? Thanks! Nick.
[ "This sort of thing you should just write yourself from scratch. A 'like' in its most basic form is going to be an object with relations to a user and some other object. Look at the contenttypes framework docs to see how to use generic foreign keys for this. The only other thing you need to worry about is to make the create view idempotent. \nIf you're new to django this is probably a fun little exercise to familiarise yourself with contenttypes. If you're not new, the whole app should take you less than an hour. I wouldn't go searching for a pluggable app either way.\n", "You could put your own together using parts of Pinax.\nThere isn't one app that would do this for you as it's too specific and reusable Django apps are supposed to be very focussed.\n", "Search http://djangoplugables.com/ \n" ]
[ 4, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000876898_django_python.txt
Q: Scripts to documents (Matlab's publish functionality in python) Matlab has this great tool called publish. This tool converts a regular matlab script with minimal formatting stuff into structured, nice looking reports (HTML, LateX, RTF). It is capable of handling graphics, mathematical formulae etc. Is there a similar tool for Python? A: There's pyreport. It captures the "captures its output, compiling it to a pretty report in a pdf or an html file". With this, you can write scripts that print out your source, getting a nice report in the end.
Scripts to documents (Matlab's publish functionality in python)
Matlab has this great tool called publish. This tool converts a regular matlab script with minimal formatting stuff into structured, nice looking reports (HTML, LateX, RTF). It is capable of handling graphics, mathematical formulae etc. Is there a similar tool for Python?
[ "There's pyreport. It captures the \"captures its output, compiling it to a pretty report in a pdf or an html file\". With this, you can write scripts that print out your source, getting a nice report in the end.\n" ]
[ 5 ]
[]
[]
[ "matlab", "python", "report", "reporting" ]
stackoverflow_0000877145_matlab_python_report_reporting.txt
Q: try... except... except... : how to avoid repeating code I'd like to avoid writting errorCount += 1 in more than one place. I'm looking for a better way than success = False try: ... else: success = True finally: if success: storage.store.commit() else: storage.store.rollback() I'm trying to avoid store.rollback() in every except clause. Any idea on how to do this? count = 0 successCount = 0 errorCount = 0 for row in rows: success = False count += 1 newOrder = storage.RepeatedOrder() storage.store.add(newOrder) try: try: newOrder.customer = customers[row.customer_id] except KeyError: raise CustomerNotFoundError, (row.customer_id,) newOrder.nextDate = dates[row.weekday] _fillOrder(newOrder, row.id) except CustomerNotFoundError as e: errorCount += 1 print u"Error: Customer not found. order_id: {0}, customer_id: {1}".format(row.id, e.id) except ProductNotFoundError as e: errorCount += 1 print u"Error: Product not found. order_id: {0}, product_id: {1}".format(row.id, e.id) else: success = True successCount += 1 finally: if success: storage.store.commit() else: storage.store.rollback() print u"{0} of {1} repeated orders imported. {2} error(s).".format(successCount, count, errorCount) A: This look like a possible application of Python's new with statement. It allows to to unwind operations and release resources securely no matter what outcome a block of code had. Read about it in PEP 343 A: My suggestion would to write an logError() method that increments errorCount (make it a member variable) and prints the error. Since your exception code is similar, you could also shorten your code by doing this: try: # something except (CustomerNotFoundError, ProductNotFoundError), e: logError(e) You can print whatever you want based on e. Also, you don't need to track succeses: successCount = len(rows) - errorCount A: You could simply wrap up your exception implementation inside an exception specific container class, that way you could also avoid all these explicit print calls (which may come in handy once you change your interface, e.g. when supporting a GUI), instead you would have a method like error(msg), which in turn could internally increase the error count accordingly. In other words, simply set up an external helper class that manages your exception handling stuff. A: If you like cumulate the errors why you don't cumulate the errors? If you put the error messages on a list the size of the list gives the information you need. You can even postprocess something. You can decide easy if an error occured and print is called only at a single place A: Well, according to this page, part 7.4: http://docs.python.org/reference/compound_stmts.html This is possible with python ver. >= 2.6. I mean try..except..finally construction.
try... except... except... : how to avoid repeating code
I'd like to avoid writting errorCount += 1 in more than one place. I'm looking for a better way than success = False try: ... else: success = True finally: if success: storage.store.commit() else: storage.store.rollback() I'm trying to avoid store.rollback() in every except clause. Any idea on how to do this? count = 0 successCount = 0 errorCount = 0 for row in rows: success = False count += 1 newOrder = storage.RepeatedOrder() storage.store.add(newOrder) try: try: newOrder.customer = customers[row.customer_id] except KeyError: raise CustomerNotFoundError, (row.customer_id,) newOrder.nextDate = dates[row.weekday] _fillOrder(newOrder, row.id) except CustomerNotFoundError as e: errorCount += 1 print u"Error: Customer not found. order_id: {0}, customer_id: {1}".format(row.id, e.id) except ProductNotFoundError as e: errorCount += 1 print u"Error: Product not found. order_id: {0}, product_id: {1}".format(row.id, e.id) else: success = True successCount += 1 finally: if success: storage.store.commit() else: storage.store.rollback() print u"{0} of {1} repeated orders imported. {2} error(s).".format(successCount, count, errorCount)
[ "This look like a possible application of Python's new with statement. It allows to to unwind operations and release resources securely no matter what outcome a block of code had.\nRead about it in PEP 343\n", "My suggestion would to write an logError() method that increments errorCount (make it a member variable) and prints the error. Since your exception code is similar, you could also shorten your code by doing this:\ntry:\n # something\nexcept (CustomerNotFoundError, ProductNotFoundError), e:\n logError(e)\n\nYou can print whatever you want based on e.\nAlso, you don't need to track succeses: successCount = len(rows) - errorCount\n", "You could simply wrap up your exception implementation inside an exception specific container class, that way you could also avoid all these explicit print calls (which may come in handy once you change your interface, e.g. when supporting a GUI), instead you would have a method like error(msg), which in turn could internally increase the error count accordingly. In other words, simply set up an external helper class that manages your exception handling stuff.\n", "If you like cumulate the errors why you don't cumulate the errors? If you put the error messages on a list the size of the list gives the information you need. You can even postprocess something. You can decide easy if an error occured and print is called only at a single place\n", "Well, according to this page, part 7.4:\nhttp://docs.python.org/reference/compound_stmts.html\nThis is possible with python ver. >= 2.6. I mean try..except..finally construction.\n" ]
[ 8, 3, 2, 0, 0 ]
[]
[]
[ "dry", "python", "try_catch" ]
stackoverflow_0000877440_dry_python_try_catch.txt
Q: Find the number of 1s in the same position in two arrays I have two lists: A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] I want to find the number of 1s in the same position in both lists. The answer for these arrays would be 2. A: A little shorter and hopefully more pythonic way: >>> A=[0,0,0,1,0,1] >>> B=[0,0,1,1,1,1] x = sum(1 for a,b in zip(A,B) if (a==b==1)) >>> x 2 A: I'm not an expert of Python, but what is wrong with a simple loop from start to end of first array? In C# I would do something like: int match=0; for (int cnt=0; cnt< A.Count;cnt++) { if ((A[cnt]==B[cnt]==1)) match++; } Would that be possible in your language? A: Motivated by brief need to be perverse, I offer the following solution: A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] print len(set(i for i, n in enumerate(A) if n == 1) & set(i for i, n in enumerate(B) if n == 1)) (Drakosha's suggestion is a far more reasonable way to solve this problem. This just demonstrates that one can often look at the same problem in different ways.) A: With SciPy: >>> from scipy import array >>> A=array([0,0,0,1,0,1]) >>> B=array([0,0,1,1,1,1]) >>> A==B array([ True, True, False, True, False, True], dtype=bool) >>> sum(A==B) 4 >>> A!=B array([False, False, True, False, True, False], dtype=bool) >>> sum(A!=B) 2 A: Here comes another method which exploits the fact that the array just contains zeros and ones. The scalar product of two vectors x and y is sum( x(i)*y(i) ) the only situation yielding a non zero result is if x(i)==y(i)==1 thus using numpy for instance from numpy import * x = array([0,0,0,1,0,1]) y = array([0,0,1,1,1,1]) print dot(x,y) simple and nice. This method does n multiplications and adds n-1 times, however there are fast implementations using SSE, GPGPU, vectorisation, (add your fancy word here) for dot products (scalar products) I timed the numpy-method against this method: sum(1 for a,b in zip(x,y) if (a==b==1)) and found that for 1000000 loops the numpy-version did it in 2121ms and the zip-method did it in 9502ms thus the numpy-version is a lot faster I did a better analysis of the efectivness and found that for n element(s) in the array the zip method took t1 ms and the dot product took t2 ms for one itteration elements zip dot 1 0.0030 0.0207 10 0.0063 0.0230 100 0.0393 0.0476 1000 0.3696 0.2932 10000 7.6144 2.7781 100000 115.8824 30.1305 From this data one could draw the conclusion that if the number of elements in the array is expected to (in mean) be more than 350 (or say 1000) one should consider to use the dot-product method instead. A: [A[i]+B[i] for i in range(min([len(A), len(B)]))].count(2) Basically this just creates a new list which has all the elements of the other two added together. You know there were two 1's if the sum is 2 (assuming only 0's and 1's in the list). Therefore just perform the count operation on 2.
Find the number of 1s in the same position in two arrays
I have two lists: A = [0,0,0,1,0,1] B = [0,0,1,1,1,1] I want to find the number of 1s in the same position in both lists. The answer for these arrays would be 2.
[ "A little shorter and hopefully more pythonic way:\n>>> A=[0,0,0,1,0,1]\n>>> B=[0,0,1,1,1,1]\n\nx = sum(1 for a,b in zip(A,B) if (a==b==1))\n>>> x\n2\n\n", "I'm not an expert of Python, but what is wrong with a simple loop from start to end of first array? \nIn C# I would do something like:\nint match=0;\n\nfor (int cnt=0; cnt< A.Count;cnt++)\n{\n if ((A[cnt]==B[cnt]==1)) match++;\n}\n\nWould that be possible in your language?\n", "Motivated by brief need to be perverse, I offer the following solution:\nA = [0,0,0,1,0,1]\nB = [0,0,1,1,1,1]\n\nprint len(set(i for i, n in enumerate(A) if n == 1) &\n set(i for i, n in enumerate(B) if n == 1))\n\n(Drakosha's suggestion is a far more reasonable way to solve this problem. This just demonstrates that one can often look at the same problem in different ways.)\n", "With SciPy:\n>>> from scipy import array\n>>> A=array([0,0,0,1,0,1])\n>>> B=array([0,0,1,1,1,1])\n\n>>> A==B\narray([ True, True, False, True, False, True], dtype=bool)\n>>> sum(A==B)\n4\n\n>>> A!=B\narray([False, False, True, False, True, False], dtype=bool)\n>>> sum(A!=B)\n2\n\n", "Here comes another method which exploits the fact that the array just contains zeros and ones.\nThe scalar product of two vectors x and y is sum( x(i)*y(i) ) the only situation yielding a non zero result is if x(i)==y(i)==1 thus using numpy for instance\nfrom numpy import *\nx = array([0,0,0,1,0,1])\ny = array([0,0,1,1,1,1])\nprint dot(x,y)\n\nsimple and nice. This method does n multiplications and adds n-1 times, however there are fast implementations using SSE, GPGPU, vectorisation, (add your fancy word here) for dot products (scalar products)\nI timed the numpy-method against this method:\nsum(1 for a,b in zip(x,y) if (a==b==1))\n\nand found that for 1000000 loops the numpy-version did it in 2121ms and the zip-method did it in 9502ms thus the numpy-version is a lot faster\nI did a better analysis of the efectivness and found that\nfor n element(s) in the array the zip method took t1 ms and the dot product took t2 ms for one itteration\n\nelements zip dot\n1 0.0030 0.0207\n10 0.0063 0.0230\n100 0.0393 0.0476\n1000 0.3696 0.2932\n10000 7.6144 2.7781\n100000 115.8824 30.1305\n\nFrom this data one could draw the conclusion that if the number of elements in the array is expected to (in mean) be more than 350 (or say 1000) one should consider to use the dot-product method instead.\n", "[A[i]+B[i] for i in range(min([len(A), len(B)]))].count(2)\n\nBasically this just creates a new list which has all the elements of the other two added together. You know there were two 1's if the sum is 2 (assuming only 0's and 1's in the list). Therefore just perform the count operation on 2.\n" ]
[ 19, 1, 1, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0000877059_list_python.txt
Q: How should I return interesting values from a with-statement? Is there a better way than using globals to get interesting values from a context manager? @contextmanager def transaction(): global successCount global errorCount try: yield except: storage.store.rollback() errorCount += 1 else: storage.store.commit() successCount += 1 Other possibilities: singletons sort of globals... tuple as an argument to the context manager makes the function more specific to a problem /less reusable instance that holds the specific attributes as an argument to the context manager same problems as the tuple, but more legible raise an exception at the end of the context manager holding the values. really bad idea A: See http://docs.python.org/reference/datamodel.html#context-managers Create a class which holds the success and error counts, and which implements the __enter__ and __exit__ methods. A: I still think you should be creating a class to hold you error/success counts, as I said in you last question. I'm guessing you have your own class, so just add something like this to it: class transaction: def __init__(self): self.errorCount = 0 self.successCount = 0 def __enter__(*args): pass def __exit__(self, type, value, traceback): if type: storage.store.rollback() self.errorCount += 1 else: storage.store.commit() self.successCount += 1 (type is None if there are no exceptions once invoking the contextmanager) And then you probably are already using this somewhere, which will invoke the contextmanager and run your __exit__() code. Edit: As Eli commented, only create a new transaction instance when you want to reset the coutners. t = transaction() for q in queries: with t: t.execute(q) A: "tuple as an argument to the context manager makes the function more specific to a problem /less reusable" False. This makes the context manager retain state. If you don't implement anything more than this, it will be reusable. However, you can't actually use a tuple because it's immutable. You need some mutable collection. Dictionaries and class definitions come to mind. Consequently, the recommended implementation is "instance that holds the specific attributes as an argument to the context manager" A simple class definition with two attributes is all you need. However, your transaction status is stateful and you need to retain state somewhere. class Counters(dict): SUCCEED= 0 FAIL= 1 def __init__( self ): self[ self.SUCCEED ]= 0 self[ self.FAIL ]= 0 def increment( self, status ): self[status] += 1 class Transaction(object): def __init__( self, worker, counters ): self.worker= worker self.counters= counters def __enter__( self ): self.counters.status= None def process( self, *args, **kw ): status= self.worker.execute( *args, **kw ) self.counters.increment( status ) def __exit__( self ): pass counts= Counters() for q in queryList: with Transaction(execQuery,counts) as t: t.process( q ) print counts
How should I return interesting values from a with-statement?
Is there a better way than using globals to get interesting values from a context manager? @contextmanager def transaction(): global successCount global errorCount try: yield except: storage.store.rollback() errorCount += 1 else: storage.store.commit() successCount += 1 Other possibilities: singletons sort of globals... tuple as an argument to the context manager makes the function more specific to a problem /less reusable instance that holds the specific attributes as an argument to the context manager same problems as the tuple, but more legible raise an exception at the end of the context manager holding the values. really bad idea
[ "See http://docs.python.org/reference/datamodel.html#context-managers\nCreate a class which holds the success and error counts, and which implements the __enter__ and __exit__ methods.\n", "I still think you should be creating a class to hold you error/success counts, as I said in you last question. I'm guessing you have your own class, so just add something like this to it:\nclass transaction:\n def __init__(self):\n self.errorCount = 0\n self.successCount = 0 \n\n def __enter__(*args):\n pass \n\n def __exit__(self, type, value, traceback):\n if type:\n storage.store.rollback()\n self.errorCount += 1\n else:\n storage.store.commit()\n self.successCount += 1\n\n(type is None if there are no exceptions once invoking the contextmanager)\nAnd then you probably are already using this somewhere, which will invoke the contextmanager and run your __exit__() code. Edit: As Eli commented, only create a new transaction instance when you want to reset the coutners.\nt = transaction()\nfor q in queries:\n with t:\n t.execute(q)\n\n", "\"tuple as an argument to the context manager\nmakes the function more specific to a problem /less reusable\"\nFalse.\nThis makes the context manager retain state.\nIf you don't implement anything more than this, it will be reusable.\nHowever, you can't actually use a tuple because it's immutable. You need some mutable collection. Dictionaries and class definitions come to mind.\nConsequently, the recommended implementation is\n\"instance that holds the specific attributes as an argument to the context manager\"\nA simple class definition with two attributes is all you need. However, your transaction status is stateful and you need to retain state somewhere.\nclass Counters(dict):\n SUCCEED= 0\n FAIL= 1\n def __init__( self ):\n self[ self.SUCCEED ]= 0\n self[ self.FAIL ]= 0 \n def increment( self, status ):\n self[status] += 1\n\nclass Transaction(object):\n def __init__( self, worker, counters ):\n self.worker= worker\n self.counters= counters\n def __enter__( self ):\n self.counters.status= None\n def process( self, *args, **kw ):\n status= self.worker.execute( *args, **kw )\n self.counters.increment( status )\n def __exit__( self ):\n pass\n\ncounts= Counters()\nfor q in queryList:\n with Transaction(execQuery,counts) as t:\n t.process( q )\nprint counts\n\n" ]
[ 9, 5, 0 ]
[]
[]
[ "contextmanager", "python", "with_statement" ]
stackoverflow_0000877709_contextmanager_python_with_statement.txt
Q: python-fastcgi extension There's not much documentation surrounding the python-fastcgi C library, so I'm wondering if someone could provide a simple example on how to make a simple FastCGI server with it. A "Hello World" example would be great. A: Edit: I misread the question. Ooops. Jon's Python modules is a collection of useful modules and includes a great FastCGI module: http://jonpy.sourceforge.net/fcgi.html Here's the example from the page: import jon.cgi as cgi import jon.fcgi as fcgi class Handler(cgi.Handler): def process(self, req): req.set_header("Content-Type", "text/plain") req.write("Hello, world!\n") fcgi.Server({fcgi.FCGI_RESPONDER: Handler}).run() A: I would recommend using a fastcgi WSGI wrapper such as this one, so you aren't tied in to the fastcgi approach from the start. And then a simple test.fgi file like such: #!/usr/bin/env python from fcgi import WSGIServer def app(env, start): start('200 OK', [('Content-Type', 'text/plain')]) yield 'Hello, World!\n' yield '\n' yield 'Your environment is:\n' for k, v in sorted(env.items()): yield '\t%s: %r\n' % (k, v) WSGIServer(app).run()
python-fastcgi extension
There's not much documentation surrounding the python-fastcgi C library, so I'm wondering if someone could provide a simple example on how to make a simple FastCGI server with it. A "Hello World" example would be great.
[ "Edit: I misread the question. Ooops.\nJon's Python modules is a collection of useful modules and includes a great FastCGI module: http://jonpy.sourceforge.net/fcgi.html\nHere's the example from the page:\nimport jon.cgi as cgi \nimport jon.fcgi as fcgi\n\nclass Handler(cgi.Handler):\n def process(self, req):\n req.set_header(\"Content-Type\", \"text/plain\")\n req.write(\"Hello, world!\\n\")\n\nfcgi.Server({fcgi.FCGI_RESPONDER: Handler}).run()\n\n", "I would recommend using a fastcgi WSGI wrapper such as this one, so you aren't tied in to the fastcgi approach from the start.\nAnd then a simple test.fgi file like such:\n#!/usr/bin/env python\n\nfrom fcgi import WSGIServer\n\ndef app(env, start):\n\n start('200 OK', [('Content-Type', 'text/plain')])\n yield 'Hello, World!\\n'\n yield '\\n'\n\n yield 'Your environment is:\\n'\n for k, v in sorted(env.items()):\n yield '\\t%s: %r\\n' % (k, v)\n\nWSGIServer(app).run()\n\n" ]
[ 4, 3 ]
[]
[]
[ "fastcgi", "python" ]
stackoverflow_0000875713_fastcgi_python.txt
Q: Letting users upload Python scripts for execution I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I either need a solution to ensure a user couldn't compromise any other files or inject malicious code via their uploaded script or a solution for client-side execution of the game. Any suggestions? (I'm looking for a solution that will work with my Python scripts) A: I am in no way associated with this site and I'm only linking it because it tries to achieve what you are getting after: jailing of python. The site is code pad. According to the about page it is ran under geordi and traps all sys calls with ptrace. In addition to be chroot'ed they are on a virtual machine with firewalls in place to disallow outbound connections. Consider it a starting point but I do have to chime in on the whole danger thing. Gotta CYA myself. :) A: Using PyPy you can create a python sandbox. The sandbox is a separate and supposedly secure python environment where you can execute their scripts. More info here http://codespeak.net/pypy/dist/pypy/doc/sandbox.html "In theory it's impossible to do anything bad or read a random file on the machine from this prompt." "This is safe to do even if script.py comes from some random untrusted source, e.g. if it is done by an HTTP server." A: Along with other safeguards, you can also incorporate human review of the code. Assuming part of the experience is reviewing other members' solutions, and everyone is a python developer, don't allow new code to be activated until a certain number of members vote for it. Your users aren't going to approve malicious code. A: Yes. Allow them to script their client, not your server. A: PyPy is probably a decent bet on the server side as suggested, but I'd look into having your python backend provide well defined APIs and data formats and have the users implement the AI and logic in Javascript so it can run in their browser. So the interaction would look like: For each match/turn/etc, pass data to the browser in a well defined format, provide a javascript template that receives the data and can implement logic, and provide web APIs that can be invoked by the client (browser) to take the desired actions. That way you don't have to worry about security or server power. A: Have an extensive API for the users and strip all other calls upon upload (such as import statements). Also, strip everything that has anything to do with file i/o. (You might want to do multiple passes to ensure that you didn't miss anything.)
Letting users upload Python scripts for execution
I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I either need a solution to ensure a user couldn't compromise any other files or inject malicious code via their uploaded script or a solution for client-side execution of the game. Any suggestions? (I'm looking for a solution that will work with my Python scripts)
[ "I am in no way associated with this site and I'm only linking it because it tries to achieve what you are getting after: jailing of python. The site is code pad.\nAccording to the about page it is ran under geordi and traps all sys calls with ptrace. In addition to be chroot'ed they are on a virtual machine with firewalls in place to disallow outbound connections.\nConsider it a starting point but I do have to chime in on the whole danger thing. Gotta CYA myself. :)\n", "Using PyPy you can create a python sandbox. The sandbox is a separate and supposedly secure python environment where you can execute their scripts. More info here\nhttp://codespeak.net/pypy/dist/pypy/doc/sandbox.html\n\"In theory it's impossible to do anything bad or read a random file on the machine from this prompt.\"\n\"This is safe to do even if script.py comes from some random untrusted source, e.g. if it is done by an HTTP server.\"\n", "Along with other safeguards, you can also incorporate human review of the code. Assuming part of the experience is reviewing other members' solutions, and everyone is a python developer, don't allow new code to be activated until a certain number of members vote for it. Your users aren't going to approve malicious code. \n", "Yes.\nAllow them to script their client, not your server.\n", "PyPy is probably a decent bet on the server side as suggested, but I'd look into having your python backend provide well defined APIs and data formats and have the users implement the AI and logic in Javascript so it can run in their browser. So the interaction would look like: For each match/turn/etc, pass data to the browser in a well defined format, provide a javascript template that receives the data and can implement logic, and provide web APIs that can be invoked by the client (browser) to take the desired actions. That way you don't have to worry about security or server power.\n", "Have an extensive API for the users and strip all other calls upon upload (such as import statements). Also, strip everything that has anything to do with file i/o.\n(You might want to do multiple passes to ensure that you didn't miss anything.)\n" ]
[ 8, 8, 4, 3, 1, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000818402_cgi_python.txt
Q: Learning threading concepts I have started threading in C and also Python recently and would like to know any good tutorials available for it. A: C - Recommended Books Unix: Butenhof, David R. - Programming with POSIX(R) Threads (Addison-Wesley Professional Computing Series) Windows: Hart, Johnson M. - Windows System Programming (3rd Edition) Python - Online Tutorial on Threads Programming with Python (PDF) A: You could write the threading yourself, it could be hard but doing that, you will learn more about threading. Or you could use a preexisting threading library. It will let you implement threading faster in your application, but you may not learn as much as to what goes on "under the hood". From your question, I cant see which path you want to take. For the latter, I suggest boosts threading library. The other answers hold great links if you prefer the former path. Good luck. :) A: I have found Interprocess Communications in Linux: The Nooks and Crannies to be extremely useful for IPC (and threading) in C.
Learning threading concepts
I have started threading in C and also Python recently and would like to know any good tutorials available for it.
[ "C - Recommended Books\nUnix: Butenhof, David R. - Programming with POSIX(R) Threads (Addison-Wesley Professional Computing Series)\nWindows: Hart, Johnson M. - Windows System Programming (3rd Edition)\nPython - Online\nTutorial on Threads Programming with Python (PDF)\n", "You could write the threading yourself, it could be hard but doing that, you will learn more about threading.\nOr you could use a preexisting threading library. It will let you implement threading faster in your application, but you may not learn as much as to what goes on \"under the hood\".\nFrom your question, I cant see which path you want to take. For the latter, I suggest boosts threading library. The other answers hold great links if you prefer the former path. \nGood luck. :)\n", "I have found Interprocess Communications in Linux: The Nooks and Crannies to be extremely useful for IPC (and threading) in C.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "c", "multithreading", "python" ]
stackoverflow_0000877068_c_multithreading_python.txt
Q: Zlib in database - Django When I try to put a zlibbed string in models.TextField >>> f = VCFile(head = 'blahblah'.encode('zlib')) >>> f.save() it fails: ... raise DjangoUnicodeDecodeError(s, *e.args) DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 1: unexpected code byte. You passed in 'x\x9cK\xcaI\xccH\x02b\x00\x0eP\x03/' (<type 'str'>) Is there any way to fix this (apart from escaping the string - it has to be space-efficent)? A: Like Marcus says, you'll have to use BLOB if you want to keep it in binary format. If you're OK with encoding it, you can use base64 encoding: from base64 import binascii f = VCFile(head = binascii.b2a_base64('blahblah'.encode('zlib'))) In my very basic tests with 33k characters, the zlib string was 28% the size of the original string, the base64 encoded zlib string was 37% the size of the original string. Not quite as good on compression, but still a big improvement. A: If you don't want to encode it, you have to store it as a binary object (BLOB), not a string. Django doesn't seem to support BlobFields out of the box, so go find it on the net or hack something together.
Zlib in database - Django
When I try to put a zlibbed string in models.TextField >>> f = VCFile(head = 'blahblah'.encode('zlib')) >>> f.save() it fails: ... raise DjangoUnicodeDecodeError(s, *e.args) DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 1: unexpected code byte. You passed in 'x\x9cK\xcaI\xccH\x02b\x00\x0eP\x03/' (<type 'str'>) Is there any way to fix this (apart from escaping the string - it has to be space-efficent)?
[ "Like Marcus says, you'll have to use BLOB if you want to keep it in binary format. If you're OK with encoding it, you can use base64 encoding:\nfrom base64 import binascii\n\nf = VCFile(head = binascii.b2a_base64('blahblah'.encode('zlib')))\n\nIn my very basic tests with 33k characters, the zlib string was 28% the size of the original string, the base64 encoded zlib string was 37% the size of the original string. Not quite as good on compression, but still a big improvement.\n", "If you don't want to encode it, you have to store it as a binary object (BLOB), not a string. Django doesn't seem to support BlobFields out of the box, so go find it on the net or hack something together.\n" ]
[ 2, 0 ]
[]
[]
[ "database", "django", "django_models", "python", "zlib" ]
stackoverflow_0000875122_database_django_django_models_python_zlib.txt
Q: PyImport_Import vs import I've tried to replace PyRun_SimpleString("import Pootle"); with PyObject *obj = PyString_FromString("Pootle"); PyImport_Import(obj); Py_DECREF(obj); after initialising the module Pootle in some C code. The first seems to make the name Pootle available to subsequent PyRun_SimpleString calls, but the second doesn't. Could someone please explain the difference to me? Is there a way to do what the first does with C API calls? Thanks A: All the PyImport_Import call does is return a reference to the module -- it doesn't make such a reference available to other parts of the program. So, if you want PyRun_SimpleString to see your new imported module, you need to add it manually. PyRun_SimpleString works automatically in the __main__ module namespace. Without paying a lot of attention to error checking (be wary of NULL returns!), this is a general outline: PyObject *main = PyImport_AddModule("__main__"); PyObject *obj = PyString_FromString("Pootle"); PyObject *pootle = PyImport_Import(obj); PyObject_SetAttrString(main, "Pootle", pootle); Py_DECREF(obj); Py_XDECREF(pootle);
PyImport_Import vs import
I've tried to replace PyRun_SimpleString("import Pootle"); with PyObject *obj = PyString_FromString("Pootle"); PyImport_Import(obj); Py_DECREF(obj); after initialising the module Pootle in some C code. The first seems to make the name Pootle available to subsequent PyRun_SimpleString calls, but the second doesn't. Could someone please explain the difference to me? Is there a way to do what the first does with C API calls? Thanks
[ "All the PyImport_Import call does is return a reference to the module -- it doesn't make such a reference available to other parts of the program. So, if you want PyRun_SimpleString to see your new imported module, you need to add it manually.\nPyRun_SimpleString works automatically in the __main__ module namespace. Without paying a lot of attention to error checking (be wary of NULL returns!), this is a general outline: \nPyObject *main = PyImport_AddModule(\"__main__\"); \nPyObject *obj = PyString_FromString(\"Pootle\");\nPyObject *pootle = PyImport_Import(obj); \nPyObject_SetAttrString(main, \"Pootle\", pootle); \n\nPy_DECREF(obj);\nPy_XDECREF(pootle);\n\n" ]
[ 4 ]
[]
[]
[ "c", "import", "python" ]
stackoverflow_0000878439_c_import_python.txt
Q: What is the Python equivalent to JDBC DatabaseMetaData? What is the Python equivalent to DatabaseMetaData A: This is not a python-specific answer; in fact I don't know if Python data drivers have this sort of thing. But maybe this info will help. The ANSI SQL-92 and SQL-99 Standard requires the INFORMATION_SCHEMA schema, which stores information regarding the tables in a catalog. The metadata you seek can be retrieved with a query on views in that schema. for example: select column_name, is_nullable, data_type, character_maximum_length as maxlen from information_schema.columns where table_name = 'Products' Not all databases implement that part of the standard. Oracle, for example, does not. Fortunately, there are also database-specific tables that store that kind of info. While Microsoft SQL Server supports the Information_Schema thing, there are also SQL Server-specific tables that give more metadata information. These are [CatalogName].dbo.sysobjects and [CatalogName].dbo.sysolumns. Similar queries on these tables will give you the metadata you seek. Example: select * from [CatalogName].dbo.syscolumns where id = (Select id from [CatalogName].dbo.sysobjects where name = 'Products') In Oracle, the ALL_TAB_COLUMNS table can give you the information: select column_name, data_type, data_length, data_precision, data_scale from ALL_TAB_COLUMNS where table_name = 'EMP'; Whether you query the standard views or the db-specific views, you don't need ODBC to do these queries - you can use whatever db connection you have available for operational data, subject to security approvals of course. A: If your willing to use ODBC for data access then you could use pyodbc, http://code.google.com/p/pyodbc/wiki/Features. Pyodbc allows you to call functions like SQLTables, which is equivalent to the JDBC getTables function. The JDBC and ODBC functions to get to metadata are extremely similar.
What is the Python equivalent to JDBC DatabaseMetaData?
What is the Python equivalent to DatabaseMetaData
[ "This is not a python-specific answer; in fact I don't know if Python data drivers have this sort of thing. But maybe this info will help. \nThe ANSI SQL-92 and SQL-99 Standard requires the INFORMATION_SCHEMA schema, which stores information regarding the tables in a catalog. \nThe metadata you seek can be retrieved with a query on views in that schema. \nfor example:\nselect column_name, is_nullable, data_type, character_maximum_length as maxlen \nfrom information_schema.columns \nwhere table_name = 'Products'\n\nNot all databases implement that part of the standard. Oracle, for example, does not. \nFortunately, there are also database-specific tables that store that kind of info. \nWhile Microsoft SQL Server supports the Information_Schema thing, there are also SQL Server-specific tables that give more metadata information. These are [CatalogName].dbo.sysobjects and [CatalogName].dbo.sysolumns. Similar queries on these tables will give you the metadata you seek. Example:\nselect * from [CatalogName].dbo.syscolumns \nwhere id = \n (Select id from [CatalogName].dbo.sysobjects where name = 'Products')\n\nIn Oracle, the ALL_TAB_COLUMNS table can give you the information: \nselect column_name, data_type, data_length, data_precision, data_scale\nfrom ALL_TAB_COLUMNS\nwhere table_name = 'EMP';\n\nWhether you query the standard views or the db-specific views, you don't need ODBC to do these queries - you can use whatever db connection you have available for operational data, subject to security approvals of course.\n", "If your willing to use ODBC for data access then you could use pyodbc, http://code.google.com/p/pyodbc/wiki/Features. Pyodbc allows you to call functions like SQLTables, which is equivalent to the JDBC getTables function. The JDBC and ODBC functions to get to metadata are extremely similar.\n" ]
[ 7, 0 ]
[]
[]
[ "database_metadata", "jdbc", "python" ]
stackoverflow_0000878737_database_metadata_jdbc_python.txt
Q: Is there a value in using map() vs for? Does map() iterate through the list like "for" would? Is there a value in using map vs for? If so, right now my code looks like this: for item in items: item.my_func() If it makes sense, I would like to make it map(). Is that possible? What is an example like? A: You could use map instead of the for loop you've shown, but since you do not appear to use the result of item.my_func(), this is not recommended. map should be used if you want to apply a function without side-effects to all elements of a list. In all other situations, use an explicit for-loop. Also, as of Python 3.0 map returns a generator, so in that case map will not behave the same (unless you explicitly evaluate all elements returned by the generator, e.g. by calling list on it). Edit: kibibu asks in the comments for a clarification on why map's first argument should not be a function with side effects. I'll give answering that question a shot: map is meant to be passed a function f in the mathematical sense. Under such circumstances it does not matter in which order f is applied to the elements of the second argument (as long as they are returned in their original order, of course). More importantly, under those circumstances map(g, map(f, l)) is semantically equivalent to map(lambda x: g(f(x)), l), regardless of the order in which f and g are applied to their respective inputs. E.g., it doesn't matter whether map returns and iterator or a full list at once. However, if f and/or g cause side effects, then this equivalence is only guaranteed if the semantics of map(g, map(f, l)) are such that at any stage g is applied to the first n elements returned by map(f, l) before map(f, l) applies f to the (n + 1)​st element of l. (Meaning that map must perform the laziest possible iteration---which it does in Python 3, but not in Python 2!) Going one step further: even if we assume the Python 3 implementation of map, the semantic equivalence may easily break down if the output of map(f, l) is e.g. passed through itertools.tee before being supplied to the outer map call. The above discussion may seem of a theoretic nature, but as programs become more complex, they become more difficult to reason about and therefore harder to debug. Ensuring that some things are invariant alleviates that problem somewhat, and may in fact prevent a whole class of bugs. Lastly, map reminds many people of its truly functional counterpart in various (purely) functional languages. Passing it a "function" with side effects will confuse those people. Therefore, seeing as the alternative (i.e., using an explicit loop) is not harder to implement than a call to map, it is highly recommended that one restricts use of map to those cases in which the function to be applied does not cause side effects. A: You can write this using map like this: map(cls.my_func, items) replacing cls with the class of the items you are iterating over. As mentioned by Stephan202, this is not recommended in this case. As a rule, if you want to create a new list by applying some function to each item in the list, use map. This has the implied meaning that the function has no side effect, and thus you could (potentially) run the map in parallel. If you don't want to create a new list, or if the function has side effects, use a for loop. This is the case in your example. A: There is a slight semantic difference, which is probably closed in python language spec. The map is explicitly parallelizable, while for only in special situations. Code can break out from for, but only escape with exception from map. In my opinion map shouldn't also guarantee order of function application while for must. AFAIK no python implementation is currently able to do this auto-parallelization. A: You can switch Your map to some cool threaded OR multiprocessing OR distributed computing framework if You need to. Disco is an example of distributed, resistant to failures erlang-and-python based framework. I configured it on 2 boxes of 8 cores and now my program runs 16 times faster, thanks to the Disco cluster, however I had to rewrite my program from list comprehensions and for loops to map/reduce. It's the same deal to write a program using for loops and list comprehensions and map/reduce, but when You need it to run on a cluster, You can do it almost for free if You used map/reduce. If You didn't, well, You will have to rewrite. Beware: as far as I know, python 2.x returns a list instead of an iterator from map. I've heard this can be bypassed by using iter.imap() (never used it though). A: Use an explicit for-loop when you don't need a list of results back (eg. functions with side-effects). Use a list comprehension when you do need a list of results back (eg. functions that return a value based directly on the input). Use map() when you're trying to convince Lisp users that Python is worth using. ;) A: The main advantage of map is when you want to get the result of some calculation on every element in a list. For example, this snippet doubles every value in a list: map(lambda x: x * 2, [1,2,3,4]) #=> [2, 4, 6, 8] It is important to note that map returns a new list with the results. It does not modify the original list in place. To do the same thing with for, you would have to create an empty list and add an extra line to the for body to add the result of each calculation to the new list. The map version is more concise and functional. A: Map can sometimes be faster for built-in functions than manually coding a for loop. Try timing map(str, range(1000000)) vs. a similar for loop.
Is there a value in using map() vs for?
Does map() iterate through the list like "for" would? Is there a value in using map vs for? If so, right now my code looks like this: for item in items: item.my_func() If it makes sense, I would like to make it map(). Is that possible? What is an example like?
[ "You could use map instead of the for loop you've shown, but since you do not appear to use the result of item.my_func(), this is not recommended. map should be used if you want to apply a function without side-effects to all elements of a list. In all other situations, use an explicit for-loop.\nAlso, as of Python 3.0 map returns a generator, so in that case map will not behave the same (unless you explicitly evaluate all elements returned by the generator, e.g. by calling list on it).\n\nEdit: kibibu asks in the comments for a clarification on why map's first argument should not be a function with side effects. I'll give answering that question a shot:\nmap is meant to be passed a function f in the mathematical sense. Under such circumstances it does not matter in which order f is applied to the elements of the second argument (as long as they are returned in their original order, of course). More importantly, under those circumstances map(g, map(f, l)) is semantically equivalent to map(lambda x: g(f(x)), l), regardless of the order in which f and g are applied to their respective inputs.\nE.g., it doesn't matter whether map returns and iterator or a full list at once. However, if f and/or g cause side effects, then this equivalence is only guaranteed if the semantics of map(g, map(f, l)) are such that at any stage g is applied to the first n elements returned by map(f, l) before map(f, l) applies f to the (n + 1)​st element of l. (Meaning that map must perform the laziest possible iteration---which it does in Python 3, but not in Python 2!)\nGoing one step further: even if we assume the Python 3 implementation of map, the semantic equivalence may easily break down if the output of map(f, l) is e.g. passed through itertools.tee before being supplied to the outer map call. \nThe above discussion may seem of a theoretic nature, but as programs become more complex, they become more difficult to reason about and therefore harder to debug. Ensuring that some things are invariant alleviates that problem somewhat, and may in fact prevent a whole class of bugs.\nLastly, map reminds many people of its truly functional counterpart in various (purely) functional languages. Passing it a \"function\" with side effects will confuse those people. Therefore, seeing as the alternative (i.e., using an explicit loop) is not harder to implement than a call to map, it is highly recommended that one restricts use of map to those cases in which the function to be applied does not cause side effects.\n", "You can write this using map like this:\nmap(cls.my_func, items)\n\nreplacing cls with the class of the items you are iterating over.\nAs mentioned by Stephan202, this is not recommended in this case.\nAs a rule, if you want to create a new list by applying some function to each item in the list, use map. This has the implied meaning that the function has no side effect, and thus you could (potentially) run the map in parallel.\nIf you don't want to create a new list, or if the function has side effects, use a for loop. This is the case in your example.\n", "There is a slight semantic difference, which is probably closed in python language spec. The map is explicitly parallelizable, while for only in special situations. Code can break out from for, but only escape with exception from map.\nIn my opinion map shouldn't also guarantee order of function application while for must. AFAIK no python implementation is currently able to do this auto-parallelization.\n", "You can switch Your map to some cool threaded OR multiprocessing OR distributed computing framework if You need to. Disco is an example of distributed, resistant to failures erlang-and-python based framework. I configured it on 2 boxes of 8 cores and now my program runs 16 times faster, thanks to the Disco cluster, however I had to rewrite my program from list comprehensions and for loops to map/reduce.\nIt's the same deal to write a program using for loops and list comprehensions and map/reduce, but when You need it to run on a cluster, You can do it almost for free if You used map/reduce. If You didn't, well, You will have to rewrite.\nBeware: as far as I know, python 2.x returns a list instead of an iterator from map. I've heard this can be bypassed by using iter.imap() (never used it though).\n", "Use an explicit for-loop when you don't need a list of results back (eg. functions with side-effects).\nUse a list comprehension when you do need a list of results back (eg. functions that return a value based directly on the input).\nUse map() when you're trying to convince Lisp users that Python is worth using. ;)\n", "The main advantage of map is when you want to get the result of some calculation on every element in a list. For example, this snippet doubles every value in a list:\nmap(lambda x: x * 2, [1,2,3,4]) #=> [2, 4, 6, 8]\n\nIt is important to note that map returns a new list with the results. It does not modify the original list in place.\nTo do the same thing with for, you would have to create an empty list and add an extra line to the for body to add the result of each calculation to the new list. The map version is more concise and functional.\n", "Map can sometimes be faster for built-in functions than manually coding a for loop. Try timing map(str, range(1000000)) vs. a similar for loop.\n" ]
[ 24, 5, 2, 2, 2, 1, 0 ]
[ "map(lambda item: item.my_func(), items)\n\n" ]
[ -3 ]
[ "for_loop", "map_function", "python" ]
stackoverflow_0000875337_for_loop_map_function_python.txt
Q: Python Django: Handling URL with Google App Engine - Post then Get I have something like this set up: class CategoryPage (webapp.RequestHandler): def get(self): ** DO SOMETHING HERE ** def post(self): ** DO SOMETHING HERE ** ** RENDER THE SAME AS get(self) The question is, after I process the posted data, how would I be able to display the same information as the get(self) function? A: A redirect, as others suggest, does have some advantage, but it's something of a "heavy" approach. As an alternative, consider refactoring the rendering part into a separate auxiliary method def _Render(self): and just ending both the get and post methods with a call to self.Render(). A: Call self.redirect(url) to redirect the user back to the same page over GET. That way, they won't accidentally re-submit the form if they hit refresh. A: create_object(request, form_class=FormClass, post_save_redirect=reverse('-get-url-handler-', kwargs=dict(key='%(key)s'))) I use the above django shortcut from generic views where you can specify post save redirect , get in your case . There are few more examples in this snippet . Btw, I assumed that you are using django ( helper or patch) with app engine , based on the title of the question. If you are using app engine patch , check out the views.py in "myapp" app sample add_person handler does what you are looking for. A: That's generally not a good idea as it'll cause confusion. You should really do whatever it is you want to do and then redirect them to the get method. A: Actually, your code isn't Django, but webapp (Google's mini-"framework"). Please read the Django documentation: http://docs.djangoproject.com/ Django's generic views are only available with app-engine-patch. The helper doesn't support them. You could take a look at the app-engine-patch sample project to learn more about Django on App Engine: http://code.google.com/p/app-engine-patch/
Python Django: Handling URL with Google App Engine - Post then Get
I have something like this set up: class CategoryPage (webapp.RequestHandler): def get(self): ** DO SOMETHING HERE ** def post(self): ** DO SOMETHING HERE ** ** RENDER THE SAME AS get(self) The question is, after I process the posted data, how would I be able to display the same information as the get(self) function?
[ "A redirect, as others suggest, does have some advantage, but it's something of a \"heavy\" approach. As an alternative, consider refactoring the rendering part into a separate auxiliary method def _Render(self): and just ending both the get and post methods with a call to self.Render().\n", "Call self.redirect(url) to redirect the user back to the same page over GET. That way, they won't accidentally re-submit the form if they hit refresh.\n", "create_object(request, form_class=FormClass,\n post_save_redirect=reverse('-get-url-handler-',\n kwargs=dict(key='%(key)s')))\n\nI use the above django shortcut from generic views where you can specify post save redirect , get in your case .\nThere are few more examples in this snippet .\nBtw, I assumed that you are using django ( helper or patch) with app engine , based on the title of the question.\nIf you are using app engine patch , check out the views.py in \"myapp\" app sample add_person handler does what you are looking for.\n", "That's generally not a good idea as it'll cause confusion. You should really do whatever it is you want to do and then redirect them to the get method.\n", "Actually, your code isn't Django, but webapp (Google's mini-\"framework\"). Please read the Django documentation: http://docs.djangoproject.com/\nDjango's generic views are only available with app-engine-patch. The helper doesn't support them. You could take a look at the app-engine-patch sample project to learn more about Django on App Engine: http://code.google.com/p/app-engine-patch/\n" ]
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000873966_google_app_engine_python.txt
Q: How can I color certain things in Emacs? I program Django/Python in emacs, and I would like things like {% comment %} FOO {% endcomment %} to turn orange. How can I set up some colors for important Django template tags? A: You could use dedicated modes like django-mode or MuMaMo. If you want something very basic, and assuming you're editing in html-mode, you could try the following: (defun django-highlight-comments () (interactive "p") (highlight-regexp "{%.*?%}" 'hi-orange)) (add-hook 'html-mode-hook 'django-highlight-comments) (Just add the above lines to your .emacs or init.el, and eval it or restart emacs). A: Here's what I do. It's a little more general than the code above, and it uses the built-in font-lock mechanisms. (defvar django-tag-face (make-face 'django-tag-face)) (defvar django-variable-face (make-face 'django-variable-face)) (set-face-background 'django-tag-face "Aquamarine") (set-face-foreground 'django-tag-face "Black") (set-face-background 'django-variable-face "Plum") (set-face-foreground 'django-variable-face "Black") (font-lock-add-keywords 'html-mode '(("\\({%[^%]*%}\\)" 1 django-tag-face prepend) ("\\({{[^}]*}}\\)" 1 django-variable-face prepend))) A: Here are some links. I found them on the Google. It seems there is no one fully-complete and "official" solution to this problem, but a number of possibly quite usable substitutes avaliable.
How can I color certain things in Emacs?
I program Django/Python in emacs, and I would like things like {% comment %} FOO {% endcomment %} to turn orange. How can I set up some colors for important Django template tags?
[ "You could use dedicated modes like django-mode or MuMaMo.\nIf you want something very basic, and assuming you're editing in html-mode, you could try the following:\n(defun django-highlight-comments ()\n (interactive \"p\")\n (highlight-regexp \"{%.*?%}\" 'hi-orange))\n(add-hook 'html-mode-hook 'django-highlight-comments)\n\n(Just add the above lines to your .emacs or init.el, and eval it or restart emacs).\n", "Here's what I do. It's a little more general than the code above, and it uses the built-in font-lock mechanisms.\n(defvar django-tag-face (make-face 'django-tag-face))\n(defvar django-variable-face (make-face 'django-variable-face))\n(set-face-background 'django-tag-face \"Aquamarine\")\n(set-face-foreground 'django-tag-face \"Black\")\n(set-face-background 'django-variable-face \"Plum\")\n(set-face-foreground 'django-variable-face \"Black\")\n\n\n(font-lock-add-keywords\n 'html-mode\n '((\"\\\\({%[^%]*%}\\\\)\" 1 django-tag-face prepend)\n (\"\\\\({{[^}]*}}\\\\)\" 1 django-variable-face prepend)))\n\n", "Here are some links. I found them on the Google. It seems there is no one fully-complete and \"official\" solution to this problem, but a number of possibly quite usable substitutes avaliable.\n" ]
[ 6, 3, 1 ]
[]
[]
[ "django", "emacs", "python", "syntax_highlighting" ]
stackoverflow_0000875543_django_emacs_python_syntax_highlighting.txt
Q: Should I implement the mixed use of BeautifulSoup and REGEXs or rely solely on BS I have some data I need to extract from a collection of html files. I am not sure if the data resides in a div element, a table element or a combined element (where the div tag is an element of a table. I have seen all three cases. My files are large-as big as 2 mb and I have tens of thousands of them. So far I have looked at the td elements in the tables and looked at the lonely div elements. It seems to me that the longest time is taking the file to be souped, upwards of 30 seconds. I played around with creating a regular expression to find the data I am looking for and then looking for the next close tag-table,tr,td,or div to determine what type of structure my text is contained in. finding the matching open tag, snipping that section and then wrapping it all in open and close HTML tags stuff <div> stuff mytext stuff </div> so I create a string that looks like: s='<div>stuffmyTextstuff</div>' I then wrap the string def stringWrapper(s): newString='<HTML>'+s+'</HTML>' return newString And then use BeautifulSoup littleSoup=BeautifulSoup(newString) I can then access the power of BeautifulSoup to do what I want with newString. This is running much faster than the alternative which is first test all the cell contents of all of the tables until I find my text and if I can't find it there test all the div contents. Am I missing something here? A: Have you tried lxml? BeautifulSoup is good but not super-fast, and I believe lxml can offer the same quality but often better performance. A: BeautifulSoup uses regex internally (it's what separates it from other XML parsers) so you'll likely find yourself just repeating what it does. If you want a faster option then use try/catch to attempt an lxml or etree parse first then try BeautifulSoup and/or tidylib to parse broken HTML if the parser fails. It seems for what you are doing you really want to be using XPath or XSLT to find and retrieve your data, lxml can do both. Finally, given the size of your files you should probably parse using a path or file handle so the source can be read incrementally rather than held in memory for the parse. A: I don't quite understand what you are trying to do. But I do know that you don't need to enclose your div string with < html> tags. BS will parse that just fine. A: I've found that even if lxml is faster than BeautifulSoup, for documents that size it's usually best to try to reduce the size to a few kB via regex (or direct stripping) and load that into BS, as you are doing now.
Should I implement the mixed use of BeautifulSoup and REGEXs or rely solely on BS
I have some data I need to extract from a collection of html files. I am not sure if the data resides in a div element, a table element or a combined element (where the div tag is an element of a table. I have seen all three cases. My files are large-as big as 2 mb and I have tens of thousands of them. So far I have looked at the td elements in the tables and looked at the lonely div elements. It seems to me that the longest time is taking the file to be souped, upwards of 30 seconds. I played around with creating a regular expression to find the data I am looking for and then looking for the next close tag-table,tr,td,or div to determine what type of structure my text is contained in. finding the matching open tag, snipping that section and then wrapping it all in open and close HTML tags stuff <div> stuff mytext stuff </div> so I create a string that looks like: s='<div>stuffmyTextstuff</div>' I then wrap the string def stringWrapper(s): newString='<HTML>'+s+'</HTML>' return newString And then use BeautifulSoup littleSoup=BeautifulSoup(newString) I can then access the power of BeautifulSoup to do what I want with newString. This is running much faster than the alternative which is first test all the cell contents of all of the tables until I find my text and if I can't find it there test all the div contents. Am I missing something here?
[ "Have you tried lxml? BeautifulSoup is good but not super-fast, and I believe lxml can offer the same quality but often better performance.\n", "BeautifulSoup uses regex internally (it's what separates it from other XML parsers) so you'll likely find yourself just repeating what it does. If you want a faster option then use try/catch to attempt an lxml or etree parse first then try BeautifulSoup and/or tidylib to parse broken HTML if the parser fails.\nIt seems for what you are doing you really want to be using XPath or XSLT to find and retrieve your data, lxml can do both.\nFinally, given the size of your files you should probably parse using a path or file handle so the source can be read incrementally rather than held in memory for the parse.\n", "I don't quite understand what you are trying to do. But I do know that you don't need to enclose your div string with < html> tags. BS will parse that just fine.\n", "I've found that even if lxml is faster than BeautifulSoup, for documents that size it's usually best to try to reduce the size to a few kB via regex (or direct stripping) and load that into BS, as you are doing now.\n" ]
[ 3, 3, 1, 1 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0000880687_beautifulsoup_python_regex.txt
Q: Applications of Python What are some applications for Python that relative amateur programmers can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python? Thanks. A: Google App Engine has excellent support for developing -- and especially for deploying -- web applications in Python (with several possible frameworks, of which Django may be the most suitable one for "relative amateurs"). Apart from web apps, Blender lets you use Python for 3D graphics, Poser for apps involving moving human-like figures, SPSS for statistics, scipy and many other tools included in Enthought's distribution support Python use in scientific programming and advanced visualization, etc, etc -- the sky's the limit. A: You can build web applications in Python. See the Django framework. Besides that, here's a nice list. Not particularly relevant, but interesting, is the fact that NASA uses Python. A: "cool" is a state of mind. Hence cool applications depends on your definition of cool. A Ant colony simulation is cool, if you want to implement the theory. Python, with its own and 3rd party libraries (batteries) has been applied in possibly all domains of day to day programming. My advise is, decide on the cool app you want to write and then see, what Python has to offer in that domain. If you are sufficiently satisfied, you can start coding. Good Luck! A: I wasn't a programming amateur at the time, but using pygame was my first intro to Python. A: Python is a general purpose programming language much like Ruby. It can be used for systems programming, embedded programming, desktop programming, and web programming. In short, it has about as much potential for "cool" projects as any other general purpose language. A: I like: Django, for web development PyQt4 for GUI programming pygame for games, input management etc PIL - python imaging library, it's not huge application, but really helpful and library imo also, Blender is an application scriptable in Python, so if you'd be into some 3D graphics, here you got it. If you're making applications for windows and want to ship them easily, you can also look at stuff like py2exe. A: One of the first bits of Python programming I ever did was to hack on the nicotine client for the Soulseek peer-to-peer network to add a '/g [query]' chat command to open the default browser and search Google. A: Probably not the most general purpose example, but I learned Python when AutoDesk Maya adopted it as a secondary programming language to complement MEL (Maya Expression Language). By comparison, it was a god-sent.
Applications of Python
What are some applications for Python that relative amateur programmers can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python? Thanks.
[ "Google App Engine has excellent support for developing -- and especially for deploying -- web applications in Python (with several possible frameworks, of which Django may be the most suitable one for \"relative amateurs\"). Apart from web apps, Blender lets you use Python for 3D graphics, Poser for apps involving moving human-like figures, SPSS for statistics, scipy and many other tools included in Enthought's distribution support Python use in scientific programming and advanced visualization, etc, etc -- the sky's the limit.\n", "You can build web applications in Python. See the Django framework.\nBesides that, here's a nice list.\nNot particularly relevant, but interesting, is the fact that NASA uses Python.\n", "\"cool\" is a state of mind. Hence cool applications depends on your definition of cool. A Ant colony simulation is cool, if you want to implement the theory.\nPython, with its own and 3rd party libraries (batteries) has been applied in possibly all domains of day to day programming. My advise is, decide on the cool app you want to write and then see, what Python has to offer in that domain. If you are sufficiently satisfied, you can start coding. Good Luck!\n", "I wasn't a programming amateur at the time, but using pygame was my first intro to Python.\n", "Python is a general purpose programming language much like Ruby. It can be used for systems programming, embedded programming, desktop programming, and web programming. In short, it has about as much potential for \"cool\" projects as any other general purpose language.\n", "I like:\n\nDjango, for web development\nPyQt4 for GUI programming\npygame for games, input management etc\nPIL - python imaging library, it's not huge application, but really helpful and library imo\nalso, Blender is an application scriptable in Python, so if you'd be into some 3D graphics, here you got it.\n\nIf you're making applications for windows and want to ship them easily, you can also look at stuff like py2exe.\n", "One of the first bits of Python programming I ever did was to hack on the nicotine client for the Soulseek peer-to-peer network to add a '/g [query]' chat command to open the default browser and search Google.\n", "Probably not the most general purpose example, but I learned Python when AutoDesk Maya adopted it as a secondary programming language to complement MEL (Maya Expression Language). By comparison, it was a god-sent.\n" ]
[ 15, 5, 5, 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000880917_python.txt
Q: Google App Engine self.redirect post I have a form that POSTs information to one of my handlers. My handler verifies the information and then needs to POST this information to a third party AND redirect the user to that page. Example of the class ExampleHandler(BaseRequestHandler): """DocString here... """ def post(self): day = int(self.request.get('day')) checked_day = CheckDay(day) if checked_day: #Here is where I would like to redirect the user to the 3rd party -- but via a post as I will be submitting a form based on data in checked_day on their behalf. else: # Otherwise no post redirect is needed -- just a simple self.redirect. self.redirect('/example') Do you have any advice on how I can redirect the user to the page where I have submitted a form? I would ideally like a self.redirect() that allowed POSTs to 3rd party sites but I don't believe this is an option. My goal is to check the data provided before sending them along to the 3rd party. Are their other options I am missing? A: You can POST the form and redirect the user to a page, but they'll have to be separate operations. The urlfetch.fetch() method lets you set the method to POST like so: import urllib form_fields = { "first_name": "Albert", "last_name": "Johnson", "email_address": "[email protected]" } form_data = urllib.urlencode(form_fields) headers = {'Content-Type': 'application/x-www-form-urlencoded'} result = urlfetch.fetch(url=url, payload=form_data, method=urlfetch.POST, headers=headers) The above example is from the URL Fetch Python API Overview.
Google App Engine self.redirect post
I have a form that POSTs information to one of my handlers. My handler verifies the information and then needs to POST this information to a third party AND redirect the user to that page. Example of the class ExampleHandler(BaseRequestHandler): """DocString here... """ def post(self): day = int(self.request.get('day')) checked_day = CheckDay(day) if checked_day: #Here is where I would like to redirect the user to the 3rd party -- but via a post as I will be submitting a form based on data in checked_day on their behalf. else: # Otherwise no post redirect is needed -- just a simple self.redirect. self.redirect('/example') Do you have any advice on how I can redirect the user to the page where I have submitted a form? I would ideally like a self.redirect() that allowed POSTs to 3rd party sites but I don't believe this is an option. My goal is to check the data provided before sending them along to the 3rd party. Are their other options I am missing?
[ "You can POST the form and redirect the user to a page, but they'll have to be separate operations.\nThe urlfetch.fetch() method lets you set the method to POST like so:\nimport urllib\n\nform_fields = {\n \"first_name\": \"Albert\",\n \"last_name\": \"Johnson\",\n \"email_address\": \"[email protected]\"\n}\nform_data = urllib.urlencode(form_fields)\nheaders = {'Content-Type': 'application/x-www-form-urlencoded'}\nresult = urlfetch.fetch(url=url,\n payload=form_data,\n method=urlfetch.POST,\n headers=headers)\n\nThe above example is from the URL Fetch Python API Overview.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000881086_google_app_engine_python.txt
Q: Pythonic URL Parsing There are a number of questions about how to parse a URL in Python, this question is about the best or most Pythonic way to do it. In my parsing I need 4 parts: the network location, the first part of the URL, the path and the filename and querystring parts. http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123 should parse into: netloc = 'www.somesite.com' baseURL = 'base' path = '/first/second/third/fourth/' file = 'foo.html?abc=123' The code below produces the correct result, but is there are better way to do this in Python? url = "http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123" file= url.rpartition('/')[2] netloc = urlparse(url)[1] pathParts = path.split('/') baseURL = pathParts[1] partCount = len(pathParts) - 1 path = "/" for i in range(2, partCount): path += pathParts[i] + "/" print 'baseURL= ' + baseURL print 'path= ' + path print 'file= ' + file print 'netloc= ' + netloc A: Since your requirements on what parts you want are different from what urlparse gives you, that's as good as it's going to get. You could, however, replace this: partCount = len(pathParts) - 1 path = "/" for i in range(2, partCount): path += pathParts[i] + "/" With this: path = '/'.join(pathParts[2:-1]) A: I'd be inclined to start out with urlparse. Also, you can use rsplit, and the maxsplit parameter of split and rsplit to simplify things a bit: _, netloc, path, _, q, _ = urlparse(url) _, base, path = path.split('/', 2) # 1st component will always be empty path, file = path.rsplit('/', 1) if q: file += '?' + q
Pythonic URL Parsing
There are a number of questions about how to parse a URL in Python, this question is about the best or most Pythonic way to do it. In my parsing I need 4 parts: the network location, the first part of the URL, the path and the filename and querystring parts. http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123 should parse into: netloc = 'www.somesite.com' baseURL = 'base' path = '/first/second/third/fourth/' file = 'foo.html?abc=123' The code below produces the correct result, but is there are better way to do this in Python? url = "http://www.somesite.com/base/first/second/third/fourth/foo.html?abc=123" file= url.rpartition('/')[2] netloc = urlparse(url)[1] pathParts = path.split('/') baseURL = pathParts[1] partCount = len(pathParts) - 1 path = "/" for i in range(2, partCount): path += pathParts[i] + "/" print 'baseURL= ' + baseURL print 'path= ' + path print 'file= ' + file print 'netloc= ' + netloc
[ "Since your requirements on what parts you want are different from what urlparse gives you, that's as good as it's going to get. You could, however, replace this:\npartCount = len(pathParts) - 1\n\npath = \"/\"\nfor i in range(2, partCount):\n path += pathParts[i] + \"/\"\n\nWith this:\npath = '/'.join(pathParts[2:-1])\n\n", "I'd be inclined to start out with urlparse. Also, you can use rsplit, and the maxsplit parameter of split and rsplit to simplify things a bit:\n_, netloc, path, _, q, _ = urlparse(url)\n_, base, path = path.split('/', 2) # 1st component will always be empty\npath, file = path.rsplit('/', 1)\nif q: file += '?' + q\n\n" ]
[ 6, 2 ]
[]
[]
[ "python", "url" ]
stackoverflow_0000880988_python_url.txt
Q: how to send email in python import smtplib SERVER = "localhost" FROM = "[email protected]" TO = ["[email protected]"] SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() This is giving the error: '**The debugged program raised the exception unhandled AttributeError "'module' object has no attribute 'SMTP'" File: /home/an/Desktop/email.py, Line: 13**' A: Rename your file to something other than email.py. Also get rid of any email.pyc file left over. Problem solved. A: This happens because email is a built-in library that comes standard with python. If you rename your program to something else (as suggested above), that should do the trick.
how to send email in python
import smtplib SERVER = "localhost" FROM = "[email protected]" TO = ["[email protected]"] SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() This is giving the error: '**The debugged program raised the exception unhandled AttributeError "'module' object has no attribute 'SMTP'" File: /home/an/Desktop/email.py, Line: 13**'
[ "Rename your file to something other than email.py. Also get rid of any email.pyc file left over. Problem solved.\n", "This happens because email is a built-in library that comes standard with python. If you rename your program to something else (as suggested above), that should do the trick.\n" ]
[ 12, 5 ]
[]
[]
[ "python" ]
stackoverflow_0000881184_python.txt
Q: "OSERROR -10000 Apple event handler failed" when trying to change desktop wallpaper on Mac I have written the following really simple python script to change the desktop wallpaper on my mac (based on this thread): from appscript import app, mactypes import sys fileName = sys.argv[1:] app('Finder').desktop_picture.set(mactypes.File(fileName)) However when I run it I get the following output: Traceback (most recent call last): File "../Source/SetWallPaper2.py", line 6, in app('Finder').desktop_picture.set(mactypes.File(fileName)) File "/Library/Python/2.5/site-packages/appscript-0.19.0-py2.5-macosx-10.5-i386.egg/appscript/reference.py", line 513, in call appscript.reference.CommandError: Command failed: OSERROR: -10000 MESSAGE: Apple event handler failed. COMMAND: app(u'/System/Library/CoreServices/Finder.app').desktop_picture.set(mactypes.File(u"/Users/Daniel/Pictures/['test.jpg']")) I've done some web searching but I can't find anything to help me figure out what OSERROR -10000 means or how to resolve the issue. A: fileName = sys.argv[1] instead of fileName = sys.argv[1:] mactypes.File(u"/Users/Daniel/Pictures/['test.jpg']") See the square brackets and quotes around the filename?
"OSERROR -10000 Apple event handler failed" when trying to change desktop wallpaper on Mac
I have written the following really simple python script to change the desktop wallpaper on my mac (based on this thread): from appscript import app, mactypes import sys fileName = sys.argv[1:] app('Finder').desktop_picture.set(mactypes.File(fileName)) However when I run it I get the following output: Traceback (most recent call last): File "../Source/SetWallPaper2.py", line 6, in app('Finder').desktop_picture.set(mactypes.File(fileName)) File "/Library/Python/2.5/site-packages/appscript-0.19.0-py2.5-macosx-10.5-i386.egg/appscript/reference.py", line 513, in call appscript.reference.CommandError: Command failed: OSERROR: -10000 MESSAGE: Apple event handler failed. COMMAND: app(u'/System/Library/CoreServices/Finder.app').desktop_picture.set(mactypes.File(u"/Users/Daniel/Pictures/['test.jpg']")) I've done some web searching but I can't find anything to help me figure out what OSERROR -10000 means or how to resolve the issue.
[ "fileName = sys.argv[1]\ninstead of\nfileName = sys.argv[1:]\nmactypes.File(u\"/Users/Daniel/Pictures/['test.jpg']\")\nSee the square brackets and quotes around the filename?\n" ]
[ 2 ]
[]
[]
[ "debugging", "macos", "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0000881041_debugging_macos_py_appscript_python_sourceforge_appscript.txt
Q: Error occurs when I connect with socket in Python Nice to meet you. A socket makes a program in Python by Linux (the transmission of a message) ⇒ Windows (the reception), b ut the following errors occur and cannot connect now. Linux, Windows are network connection together, and there is the authority to cut. socket.error: (111, 'Connection refused') Could you help me!? A: 111 means the listener is down/not accepting connections - restart the Windows app that should be listening for connections, or disconnect any already-bound clients.
Error occurs when I connect with socket in Python
Nice to meet you. A socket makes a program in Python by Linux (the transmission of a message) ⇒ Windows (the reception), b ut the following errors occur and cannot connect now. Linux, Windows are network connection together, and there is the authority to cut. socket.error: (111, 'Connection refused') Could you help me!?
[ "111 means the listener is down/not accepting connections - restart the Windows app that should be listening for connections, or disconnect any already-bound clients.\n" ]
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0000881332_python_sockets.txt
Q: In print statements, what determines whether python shell prints null character or waits for input Recently I was trying some practice programs in python and I came across this small problem. when I typed print "" in IDLE, the python shell printed a null character. If I typed print """""" in IDLE, the python shell printed a null character. but the python shell waits for input if I type print """" Why is this behaviour observed. As far as my knowledge goes, it should print null character for this print """" also. A: In python you can have strings enclosed with either 1 or 3 quotes. print "a" print """a""" In your case, the interpreter is waiting for the last triple quote. A: I suspect you mean that python printed an empty line -- this is not the same as a null character. When you print """""", python finds an empty, triple-quoted string. When you print """", python finds the start of a triple-quoted string, and waits for you to input the rest (ending with """). A triple-qouted string can include other qoutes, linebreaks, etc.
In print statements, what determines whether python shell prints null character or waits for input
Recently I was trying some practice programs in python and I came across this small problem. when I typed print "" in IDLE, the python shell printed a null character. If I typed print """""" in IDLE, the python shell printed a null character. but the python shell waits for input if I type print """" Why is this behaviour observed. As far as my knowledge goes, it should print null character for this print """" also.
[ "In python you can have strings enclosed with either 1 or 3 quotes.\nprint \"a\"\nprint \"\"\"a\"\"\"\n\nIn your case, the interpreter is waiting for the last triple quote.\n", "I suspect you mean that python printed an empty line -- this is not the same as a null character.\nWhen you print \"\"\"\"\"\", python finds an empty, triple-quoted string.\nWhen you print \"\"\"\", python finds the start of a triple-quoted string, and waits for you to input the rest (ending with \"\"\").\nA triple-qouted string can include other qoutes, linebreaks, etc.\n" ]
[ 11, 4 ]
[]
[]
[ "python" ]
stackoverflow_0000881564_python.txt
Q: Cross-platform gui toolkit for deploying Python applications Building on: http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/ Merits: 1 - ease of design / integration - learning curve 2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web 3 - pythonic API 4 - quality of documentation - I want to do something a bit more complicated, now what? 5 - light weight packaging so it's not necessary to include a full installer (py2exe, py2app would ideally work as-is and not generate a gazillion MBs file) 6 - licensing 7 - others? (specify) Contenders: 1 - tkinter, as currently supported (as of 2.6, 3.0) 2 - pyttk library 3 - pyGTK 4 - pyQt 5 - wxPython 6 - HTML-CGI via Python-based framework (Django, Turbogears, web.py, Pylons...) or Paste 7 - others? (specify) A: Please don't hesitate to expand this answer. Tkinter Tkinter is the toolkit that comes with python. That means you already have everything you need to write a GUI. What that also means is that if you choose to distribute your program, most likely everyone else already has what they need to run your program. Tkinter is mature and stable, and is (at least arguably) quite easy to use.I found it easier to use than wxPython, but obviously that's somewhat subjective. Tkinter gets a bad rap for looking ugly and out of date. While it's true that it's easy to create ugly GUIs with Tkinter, it's also pretty easy to create nice looking GUIs. Tkinter doesn't hold your hand, but it doesn't much get in the way, either. Tkinter looks best on the Mac and Windows since it uses native widgets there, but it looks OK on linux, too. The other point about the look of Tkinter is that, for the most part, look isn't as important as people make it out to be. Most applications written with toolkits such as Tkinter, wxPython, PyQT, etc are special-purpose applications. For the types of applications these toolkits are used for, usability trumps looks. If the look of the application is important, it's easy enough to polish up a Tkinter application. Tkinter has some features that other toolkits don't come close to matching. Variable traces, named fonts, geometry (layout) managers, and the way Tkinter processes events are still the standard to which other toolkits should be judged. On the downside, Tkinter is a wrapper around a Tcl interpreter that runs inside python. This is mostly invisible to anyone developing with Tkinter, but it sometimes results in error messages that expose this architecture. You'll get an error complaining about a widget with a name like ".1245485.67345" which will make almost no sense to anyone unless you're also familiar with how Tcl/tk works. Another downside is that Tkinter doesn't have as many pre-built widgets as wxPython. The hierarchical tree widget in Tkinter is a little weak, for example, and there's no built-in table widget. On the other hand, Tkinter's canvas and text widgets are extremely powerful and easy to use. For most types of applications you will write, however, you'll have everything you need. Just don't expect to replicate Microsoft Word or Photoshop with Tkinter. I don't know what the license is for Tkinter, I assume the same as for python as a whole. Tcl/tk has a BSD-style license. PyQt It's build on top of Qt, a C++ framework. It's quite advanced and has some good tools like the Qt Designer to design your applications. You should be aware though, that it doesn't feel like Python 100%, but close to it. The documentation is excellent This framework is really good. It's being actively developed by Trolltech, who is owned by Nokia. The bindings for Python are developed by Riverbank. PyQt is available under the GPL license or a commercial one. The price of a riverbank PyQt license is about 400 euro per developer. Qt is not only a GUI-framework but has a lot of other classes too, one can create an application by just using Qt classes. (Like SQL, networking, scripting, …) Qt used to emulate GUI elements on every platform but now uses native styles of the platforms (although not native GUI toolkits): see the documentation for Mac OS X and the windows XP style Packaging is as simple as running py2exe or pyInstaller. The content of my PyQt app looks like this on windows (I have used InnoSetup on top of it for proper installation): pyticroque.exe PyQt4.QtGui.pyd unicodedata.pyd MSVCP71.dll PyQt4._qt.pyd unins000.dat MSVCR71.dll python25.dll unins000.exe PyQt4.QtCore.pyd sip.pyd _socket.pyd QT comes with a widget designer and even in recent versions with an IDE to help design Qt software. PySide PySide is a LGPL binding to Qt. It's developed by nokia as a replacement for the GPL PyQt. Although based on a different technology than the existing GPL-licensed PyQt bindings, PySide will initially aim to be API-compatible with them. In addition to the PyQt-compatible API, a more Pythonic API will be provided in the future. wxPython wxPython is a binding for Python using the wxWidgets-Framework. This framework is under the LGPL licence and is developed by the open source community. What I'm really missing is a good tool to design the interface, they have about 3 but none of them is usable. One thing I should mention is that I found a bug in the tab-view despite the fact that I didn't use anything advanced. (Only on Mac OS X) I think wxWidgets isn't as polished as Qt. wxPython is really only about the GUI-classes, there isn't much else. wxWidgets uses native GUI elements. An advantage wxPython has over Tkinter is that wxPython has a much larger library of widgets from which to choose from. Others I haven't got any experience with other GUI frameworks, maybe someone else has. A: I'm just weighing in to say that TKinter sucks. It sadly seems that it is packed with Python because of backwards compatibility. The documentation is horrible. It looks horrible. I have run into some bizarre bugs that will actually crash Python. A: Jython. Jython is an implementation of the high-level, dynamic, object-oriented language Python written in 100% Pure Java, and seamlessly integrated with the Java platform. It thus allows you to run Python on any Java platform. You can use either Swing, Applet, or other GUI frameworks available to Java platform. See Java Tutorials for Graphical User Interfaces and 2D Graphics. There are plenty of books and documentation such as API reference. Here's a Hello world Swing application from An Introduction to Jython. from javax.swing import * frame = JFrame("Hello Jython") label = JLabel("Hello Jython!", JLabel.CENTER) frame.add(label) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(300, 300) frame.show() Here's a Jython applet by Todd Ditchendorf that demonstrates multi-threaded particle drawing (60 lines). from __future__ import nested_scopes import java.lang as lang import java.util as util import java.awt as awt import javax.swing as swing class Particle: def __init__(self,initX,initY): self.x = initX self.y = initY self.rng = util.Random() def move(self): self.x += self.rng.nextInt(10) - 5 self.y += self.rng.nextInt(20) - 10 def draw(self,g2): g2.drawRect(self.x,self.y,10,10) class ParticleCanvas(awt.Canvas): def __init__(self,newSize): awt.Canvas.__init__(self,size=(newSize,newSize)) def paint(self,g2): for p in self.particles: p.draw(g2) class ParticleApplet(swing.JApplet): def init(self): self.canvas = ParticleCanvas(self.getWidth()) self.contentPane.add(self.canvas) def start(self): n = 10 particles = [] for i in range(n): particles.append(Particle(150,150)) self.canvas.particles = particles self.threads = [] for i in range(n): self.threads.append(self.makeThread(particles[i])) self.threads[i].start() def makeThread(self,p): class MyRunnable(lang.Runnable): def run(this): try: while 1: p.move() self.canvas.repaint() lang.Thread.sleep(100) except lang.InterruptedException: return return lang.Thread(MyRunnable()) If you are just interested in drawing lines and circles you can probably cut it down to half. A: I would definitely appreciate it if anyone knows of something better than what's commonly discussed; I see to have headaches finding something appropriate... Qt is great, but PyQt doesn't seem to have the same development resources. It seems to have some clever way to generate bindings, but isn't complete (e.g. PyKDE terminal kpart) and there is a dearth of documentation (as the developers admit). Compatibility with Qt's UI designer is nice. wxpython - controls aren't as nice looking, widget library isn't as large as KDE. OpenGL - doesn't even support fonts by default... pygame is okay, but opengl being a state machine is too annoying (object oriented models prevent making the a call in the wrong state). XUL - neat idea, I wish it worked. The pyxulrunner tutorial didn't work for me, though -- first I had to add the xulrunner /usr/lib path to LD_LIBRARY_PATH, then it still had problems with "from xpcom import components"... my wishlist for a ui library would be Python integration (i.e. uses builtins like unicode, modules like threading, and language features like closures) good intermediate representation (like XUL instead of generating hundreds of lines looking like "listbox91.addChild(label28)") simple mutlithreaded support (automatic locks or event posting so e.g. elt.setText can be called from any thread; let the designer manage locking with Python locks if necessary) user-centric features as well - scripting of a sequence of UI events, ability to keybind anything (KDE has dcop, but afaik binding isn't done automatically by the UI library), and intercept events. potential for a large, easy-to-contribute standard library. documentation, though if the library was well designed and generated enough interest, this would be a given. In my experience, html is so much easier to get something good-looking up than UI libraries. edit - after working with PyQt 4 for a while, it gets the job done for simple UI's. I'm currently not developing for end users, so looks don't matter. The QTextBrowser is very useful for displaying basic HTML tables and generating HTML links. A: Pro wxPython Lots of tutorials wxGlade as an Editor: not perfect yet, but usable.
Cross-platform gui toolkit for deploying Python applications
Building on: http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/ Merits: 1 - ease of design / integration - learning curve 2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web 3 - pythonic API 4 - quality of documentation - I want to do something a bit more complicated, now what? 5 - light weight packaging so it's not necessary to include a full installer (py2exe, py2app would ideally work as-is and not generate a gazillion MBs file) 6 - licensing 7 - others? (specify) Contenders: 1 - tkinter, as currently supported (as of 2.6, 3.0) 2 - pyttk library 3 - pyGTK 4 - pyQt 5 - wxPython 6 - HTML-CGI via Python-based framework (Django, Turbogears, web.py, Pylons...) or Paste 7 - others? (specify)
[ "Please don't hesitate to expand this answer.\nTkinter\nTkinter is the toolkit that comes with python. That means you already have everything you need to write a GUI. What that also means is that if you choose to distribute your program, most likely everyone else already has what they need to run your program.\nTkinter is mature and stable, and is (at least arguably) quite easy to use.I found it easier to use than wxPython, but obviously that's somewhat subjective. \nTkinter gets a bad rap for looking ugly and out of date. While it's true that it's easy to create ugly GUIs with Tkinter, it's also pretty easy to create nice looking GUIs. Tkinter doesn't hold your hand, but it doesn't much get in the way, either. Tkinter looks best on the Mac and Windows since it uses native widgets there, but it looks OK on linux, too. \nThe other point about the look of Tkinter is that, for the most part, look isn't as important as people make it out to be. Most applications written with toolkits such as Tkinter, wxPython, PyQT, etc are special-purpose applications. For the types of applications these toolkits are used for, usability trumps looks. If the look of the application is important, it's easy enough to polish up a Tkinter application.\nTkinter has some features that other toolkits don't come close to matching. Variable traces, named fonts, geometry (layout) managers, and the way Tkinter processes events are still the standard to which other toolkits should be judged. \nOn the downside, Tkinter is a wrapper around a Tcl interpreter that runs inside python. This is mostly invisible to anyone developing with Tkinter, but it sometimes results in error messages that expose this architecture. You'll get an error complaining about a widget with a name like \".1245485.67345\" which will make almost no sense to anyone unless you're also familiar with how Tcl/tk works.\nAnother downside is that Tkinter doesn't have as many pre-built widgets as wxPython. The hierarchical tree widget in Tkinter is a little weak, for example, and there's no built-in table widget. On the other hand, Tkinter's canvas and text widgets are extremely powerful and easy to use. For most types of applications you will write, however, you'll have everything you need. Just don't expect to replicate Microsoft Word or Photoshop with Tkinter. \nI don't know what the license is for Tkinter, I assume the same as for python as a whole. Tcl/tk has a BSD-style license. \nPyQt\nIt's build on top of Qt, a C++ framework. It's quite advanced and has some good tools like the Qt Designer to design your applications. You should be aware though, that it doesn't feel like Python 100%, but close to it. The documentation is excellent\nThis framework is really good. It's being actively developed by Trolltech, who is owned by Nokia. The bindings for Python are developed by Riverbank.\nPyQt is available under the GPL license or a commercial one. The price of a riverbank PyQt license is about 400 euro per developer.\nQt is not only a GUI-framework but has a lot of other classes too, one can create an application by just using Qt classes. (Like SQL, networking, scripting, …)\nQt used to emulate GUI elements on every platform but now uses native styles of the platforms (although not native GUI toolkits): see the documentation for Mac OS X and the windows XP style\nPackaging is as simple as running py2exe or pyInstaller. The content of my PyQt app looks like this on windows (I have used InnoSetup on top of it for proper installation):\n\npyticroque.exe PyQt4.QtGui.pyd unicodedata.pyd\nMSVCP71.dll PyQt4._qt.pyd unins000.dat\nMSVCR71.dll python25.dll unins000.exe\nPyQt4.QtCore.pyd sip.pyd _socket.pyd\n\nQT comes with a widget designer and even in recent versions with an IDE to help design Qt software.\nPySide\nPySide is a LGPL binding to Qt. It's developed by nokia as a replacement for the GPL PyQt.\n\nAlthough based on a different\n technology than the existing\n GPL-licensed PyQt bindings, PySide\n will initially aim to be\n API-compatible with them. In addition\n to the PyQt-compatible API, a more\n Pythonic API will be provided in the\n future.\n\nwxPython\nwxPython is a binding for Python using the wxWidgets-Framework. This framework is under the LGPL licence and is developed by the open source community.\nWhat I'm really missing is a good tool to design the interface, they have about 3 but none of them is usable.\nOne thing I should mention is that I found a bug in the tab-view despite the fact that I didn't use anything advanced. (Only on Mac OS X) I think wxWidgets isn't as polished as Qt.\nwxPython is really only about the GUI-classes, there isn't much else.\nwxWidgets uses native GUI elements.\nAn advantage wxPython has over Tkinter is that wxPython has a much larger library of widgets from which to choose from. \nOthers\nI haven't got any experience with other GUI frameworks, maybe someone else has.\n", "I'm just weighing in to say that TKinter sucks. It sadly seems that it is packed with Python because of backwards compatibility. \nThe documentation is horrible. It looks horrible. I have run into some bizarre bugs that will actually crash Python.\n", "Jython.\n\nJython is an implementation of the\n high-level, dynamic, object-oriented\n language Python written in 100% Pure\n Java, and seamlessly integrated with\n the Java platform. It thus allows you\n to run Python on any Java platform.\n\nYou can use either Swing, Applet, or other GUI frameworks available to Java platform. See Java Tutorials for Graphical User Interfaces and 2D Graphics. There are plenty of books and documentation such as API reference.\nHere's a Hello world Swing application from An Introduction to Jython.\nfrom javax.swing import *\n\nframe = JFrame(\"Hello Jython\")\nlabel = JLabel(\"Hello Jython!\", JLabel.CENTER)\nframe.add(label)\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setSize(300, 300)\nframe.show()\n\nHere's a Jython applet by Todd Ditchendorf that demonstrates multi-threaded particle drawing (60 lines).\nfrom __future__ import nested_scopes\nimport java.lang as lang\nimport java.util as util\nimport java.awt as awt\nimport javax.swing as swing\n\nclass Particle:\n\n def __init__(self,initX,initY):\n self.x = initX\n self.y = initY\n self.rng = util.Random()\n\n def move(self):\n self.x += self.rng.nextInt(10) - 5\n self.y += self.rng.nextInt(20) - 10\n\n def draw(self,g2):\n g2.drawRect(self.x,self.y,10,10)\n\nclass ParticleCanvas(awt.Canvas):\n\n def __init__(self,newSize):\n awt.Canvas.__init__(self,size=(newSize,newSize))\n\n def paint(self,g2):\n for p in self.particles:\n p.draw(g2)\n\nclass ParticleApplet(swing.JApplet):\n\n def init(self):\n self.canvas = ParticleCanvas(self.getWidth())\n self.contentPane.add(self.canvas)\n\n def start(self):\n n = 10\n particles = []\n for i in range(n):\n particles.append(Particle(150,150))\n self.canvas.particles = particles\n\n self.threads = []\n for i in range(n):\n self.threads.append(self.makeThread(particles[i]))\n self.threads[i].start()\n\n def makeThread(self,p):\n\n class MyRunnable(lang.Runnable):\n def run(this):\n try:\n while 1:\n p.move()\n self.canvas.repaint()\n lang.Thread.sleep(100)\n except lang.InterruptedException:\n return\n\n return lang.Thread(MyRunnable())\n\nIf you are just interested in drawing lines and circles you can probably cut it down to half.\n", "I would definitely appreciate it if anyone knows of something better than what's commonly discussed; I see to have headaches finding something appropriate...\nQt is great, but PyQt doesn't seem to have the same development resources. It seems to have some clever way to generate bindings, but isn't complete (e.g. PyKDE terminal kpart) and there is a dearth of documentation (as the developers admit). Compatibility with Qt's UI designer is nice.\nwxpython - controls aren't as nice looking, widget library isn't as large as KDE.\nOpenGL - doesn't even support fonts by default... pygame is okay, but opengl being a state machine is too annoying (object oriented models prevent making the a call in the wrong state).\nXUL - neat idea, I wish it worked. The pyxulrunner tutorial didn't work for me, though -- first I had to add the xulrunner /usr/lib path to LD_LIBRARY_PATH, then it still had problems with \"from xpcom import components\"...\nmy wishlist for a ui library would be\n\nPython integration (i.e. uses builtins like unicode, modules like threading, and language features like closures)\ngood intermediate representation (like XUL instead of generating hundreds of lines looking like \"listbox91.addChild(label28)\")\nsimple mutlithreaded support (automatic locks or event posting so e.g. elt.setText can be called from any thread; let the designer manage locking with Python locks if necessary)\nuser-centric features as well - scripting of a sequence of UI events, ability to keybind anything (KDE has dcop, but afaik binding isn't done automatically by the UI library), and intercept events.\npotential for a large, easy-to-contribute standard library.\ndocumentation, though if the library was well designed and generated enough interest, this would be a given.\n\nIn my experience, html is so much easier to get something good-looking up than UI libraries.\nedit - after working with PyQt 4 for a while, it gets the job done for simple UI's. I'm currently not developing for end users, so looks don't matter. The QTextBrowser is very useful for displaying basic HTML tables and generating HTML links.\n", "Pro wxPython\n\nLots of tutorials\nwxGlade as an Editor: not perfect yet, but usable.\n\n" ]
[ 50, 7, 6, 5, 0 ]
[]
[]
[ "cross_platform", "python", "user_interface" ]
stackoverflow_0000520015_cross_platform_python_user_interface.txt
Q: How to tell if a class is descended from another class I have a function that accepts a class (not an instance) and, depending on whether or not it's a specific class or a subclass of that, I need to pass it in to one of two other (third-party) factory functions. (To forestall any objections, I'm aware this is not very Pythonic, but I'm dependent on what the third-party library accepts.) issubclass only works for instances, not class objects themselves. I suppose I could instantiate the class, do issubclass and throw away the instance, but that seems a bit wasteful. Here's what I'm doing at the moment, relying on the built-in mro attribute to tell if a certain class is in the list of ancestors of my class. Is this safe, and is there any better way of doing it? if GenericClass in myclass.__mro__: result = generic_factory(myclass) else: result = other_factory(myclass) A: issubclass only works for instances, not class objects themselves. It works fine for me: >>> class test(object):pass ... >>> issubclass(test,object) True
How to tell if a class is descended from another class
I have a function that accepts a class (not an instance) and, depending on whether or not it's a specific class or a subclass of that, I need to pass it in to one of two other (third-party) factory functions. (To forestall any objections, I'm aware this is not very Pythonic, but I'm dependent on what the third-party library accepts.) issubclass only works for instances, not class objects themselves. I suppose I could instantiate the class, do issubclass and throw away the instance, but that seems a bit wasteful. Here's what I'm doing at the moment, relying on the built-in mro attribute to tell if a certain class is in the list of ancestors of my class. Is this safe, and is there any better way of doing it? if GenericClass in myclass.__mro__: result = generic_factory(myclass) else: result = other_factory(myclass)
[ "\nissubclass only works for instances, not class objects themselves.\n\nIt works fine for me:\n>>> class test(object):pass\n...\n>>> issubclass(test,object)\nTrue\n\n" ]
[ 30 ]
[]
[]
[ "python" ]
stackoverflow_0000881676_python.txt
Q: How to use dynamic foreignkey in Django? I want to connect a single ForeignKey to two different models. For example: I have two models named Casts and Articles, and a third model, Faves, for favoriting either of the other models. How can I make the ForeignKey dynamic? class Articles(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Casts(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Faves(models.Model): post = models.ForeignKey(**---CASTS-OR-ARTICLES---**) user = models.ForeignKey(User,unique=True) Is this possible? A: Here is how I do it: from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import fields class Photo(models.Model): picture = models.ImageField(null=True, upload_to='./images/') caption = models.CharField(_("Optional caption"),max_length=100,null=True, blank=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = fields.GenericForeignKey('content_type', 'object_id') class Article(models.Model): .... images = fields.GenericRelation(Photo) You would add something like content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = fields.GenericForeignKey('content_type', 'object_id') to Faves and fields.GenericRelation(Faves) to Article and Cast contenttypes docs A: Here's an approach. (Note that the models are singular, Django automatically pluralizes for you.) class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Cast(models.Model): title = models.CharField(max_length=100) body = models.TextField() FAVE_CHOICES = ( ('A','Article'), ('C','Cast'), ) class Fave(models.Model): type_of_fave = models.CharField( max_length=1, choices=FAVE_CHOICES ) cast = models.ForeignKey(Casts,null=True) article= models.ForeigKey(Articles,null=True) user = models.ForeignKey(User,unique=True) This rarely presents profound problems. It may require some clever class methods, depending on your use cases.
How to use dynamic foreignkey in Django?
I want to connect a single ForeignKey to two different models. For example: I have two models named Casts and Articles, and a third model, Faves, for favoriting either of the other models. How can I make the ForeignKey dynamic? class Articles(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Casts(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Faves(models.Model): post = models.ForeignKey(**---CASTS-OR-ARTICLES---**) user = models.ForeignKey(User,unique=True) Is this possible?
[ "Here is how I do it:\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import fields\n\n\nclass Photo(models.Model):\n picture = models.ImageField(null=True, upload_to='./images/')\n caption = models.CharField(_(\"Optional caption\"),max_length=100,null=True, blank=True)\n\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n content_object = fields.GenericForeignKey('content_type', 'object_id')\n\nclass Article(models.Model):\n ....\n images = fields.GenericRelation(Photo)\n\nYou would add something like \n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n content_object = fields.GenericForeignKey('content_type', 'object_id')\n\nto Faves\nand \n fields.GenericRelation(Faves)\n\nto Article and Cast\ncontenttypes docs\n", "Here's an approach. (Note that the models are singular, Django automatically pluralizes for you.)\nclass Article(models.Model):\n title = models.CharField(max_length=100)\n body = models.TextField()\n\nclass Cast(models.Model):\n title = models.CharField(max_length=100)\n body = models.TextField()\n\nFAVE_CHOICES = ( \n ('A','Article'),\n ('C','Cast'),\n)\nclass Fave(models.Model):\n type_of_fave = models.CharField( max_length=1, choices=FAVE_CHOICES )\n cast = models.ForeignKey(Casts,null=True)\n article= models.ForeigKey(Articles,null=True)\n user = models.ForeignKey(User,unique=True)\n\nThis rarely presents profound problems. It may require some clever class methods, depending on your use cases.\n" ]
[ 64, 22 ]
[]
[]
[ "django", "foreign_keys", "python" ]
stackoverflow_0000881792_django_foreign_keys_python.txt
Q: How to hide "cgi-bin", ".py", etc from my URLs? Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py" But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never have the messy details showing the script that was used to run them. They're clean of cgi-bin, .py, etc. extensions. How do I do that? EDIT: Thanks for responses, every single one helpful, lots to learn. I'm going with URL Rewriting for now; example in the docs looks extremely close to what I actually want to do. But I'm committed to python, so will have to look at WSGI down the road. A: The python way of writing web applications is not cgi-bin. It is by using WSGI. WSGI is a standard interface between web servers and Python web applications or frameworks. The PEP 0333 defines it. There are no disadvantages in using it instead of CGI. And you'll gain a lot. Beautiful URLs is just one of the neat things you can do easily. Also, writing a WSGI application means you can deploy on any web server that supports the WSGI interface. Apache does so by using mod_wsgi. You can configure it in apache like that: WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.py Then all requests on http://myserver.domain/myapp will go to myapp.py's application callable, including http://myserver.domain/myapp/something/here. example myapp.py: def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return ['Hello World!'] A: I think you can do this by rewriting URL through Apache configuration. You can see the Apache documentation for rewriting here. A: You have to use URL Rewriting. It is not a noob question, it can be quite tricky :) http://httpd.apache.org/docs/2.0/misc/rewriteguide.html Hope you find it helpful A: this is an excerpt from a .htaccess that I use to achieve such a thing, this for example redirects all requests that were not to index.php to that file, of course you then have to check the server-variables within the file you redirect to to see, what was requested. Or you simply make a rewrite rule, where you use a RegExp like ^.*\/cgi-bin\/.*\.py$ to determine when and what to rewrite. Such a RegExp must be crafted very carefully, so that rewriting only takes place when desired. <IfModule mod_rewrite.c> RewriteEngine On #activate rewriting RewriteBase / #url base for rewriting RewriteCond %{REQUEST_FILENAME} !index.php #requested file is not index.php RewriteCond %{REQUEST_FILENAME} !^.*\.gif$ #requested file is no .gif RewriteCond %{REQUEST_FILENAME} !^.*\.jpg$ #requested file is no .jpg RewriteCond %{REQUEST_FILENAME} !-d #is not a directory RewriteRule . /index.php [L] #send it all to index.php </IfModule> The above Example uses RewriteConditions to determine when to rewrite ( .gif's, .jpeg's and index.php are excluded ). Hmm, so thats a long text already. Hope it was a bit helpful, but you won't be able to avoid learning the syntax of the Apache RewriteEngine. A: You'll find the ScriptAlias directive helpful. Using ScriptAlias /urlpath /your/cgi-bin/script.py you can access your script via http://yourserver/urlpath. You also might want to look into mod_passenger, though the last time I used it, WSGI was kind of a "second-class citizen" within the library—it could detect WSGI scripts if it were used to serve the whole domain, but otherwise there are no directives to get it to run a WSGI app. A: Just use some good web framework e.g. django and you can have such URLs more than URLs you will have a better infrastructure, templates, db orm etc
How to hide "cgi-bin", ".py", etc from my URLs?
Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py" But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never have the messy details showing the script that was used to run them. They're clean of cgi-bin, .py, etc. extensions. How do I do that? EDIT: Thanks for responses, every single one helpful, lots to learn. I'm going with URL Rewriting for now; example in the docs looks extremely close to what I actually want to do. But I'm committed to python, so will have to look at WSGI down the road.
[ "The python way of writing web applications is not cgi-bin. It is by using WSGI.\nWSGI is a standard interface between web servers and Python web applications or frameworks. The PEP 0333 defines it.\nThere are no disadvantages in using it instead of CGI. And you'll gain a lot. Beautiful URLs is just one of the neat things you can do easily.\nAlso, writing a WSGI application means you can deploy on any web server that supports the WSGI interface. Apache does so by using mod_wsgi.\nYou can configure it in apache like that:\nWSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.py\n\nThen all requests on http://myserver.domain/myapp will go to myapp.py's application callable, including http://myserver.domain/myapp/something/here. \nexample myapp.py:\ndef application(environ, start_response):\n start_response('200 OK', [('Content-type', 'text/plain')])\n return ['Hello World!']\n\n", "I think you can do this by rewriting URL through Apache configuration. You can see the Apache documentation for rewriting here.\n", "You have to use URL Rewriting.\nIt is not a noob question, it can be quite tricky :)\nhttp://httpd.apache.org/docs/2.0/misc/rewriteguide.html\nHope you find it helpful\n", "this is an excerpt from a .htaccess that I use to achieve such a thing, this for example redirects all requests that were not to index.php to that file, of course you then have to check the server-variables within the file you redirect to to see, what was requested.\nOr you simply make a rewrite rule, where you use a RegExp like ^.*\\/cgi-bin\\/.*\\.py$ to determine when and what to rewrite. Such a RegExp must be crafted very carefully, so that rewriting only takes place when desired.\n<IfModule mod_rewrite.c>\n RewriteEngine On #activate rewriting\n RewriteBase / #url base for rewriting\n RewriteCond %{REQUEST_FILENAME} !index.php #requested file is not index.php\n RewriteCond %{REQUEST_FILENAME} !^.*\\.gif$ #requested file is no .gif\n RewriteCond %{REQUEST_FILENAME} !^.*\\.jpg$ #requested file is no .jpg\n RewriteCond %{REQUEST_FILENAME} !-d #is not a directory\n RewriteRule . /index.php [L] #send it all to index.php\n</IfModule>\n\nThe above Example uses RewriteConditions to determine when to rewrite ( .gif's, .jpeg's and index.php are excluded ).\nHmm, so thats a long text already. Hope it was a bit helpful, but you won't be able to avoid learning the syntax of the Apache RewriteEngine.\n", "You'll find the ScriptAlias directive helpful. Using\nScriptAlias /urlpath /your/cgi-bin/script.py\n\nyou can access your script via http://yourserver/urlpath.\nYou also might want to look into mod_passenger, though the last time I used it, WSGI was kind of a \"second-class citizen\" within the library—it could detect WSGI scripts if it were used to serve the whole domain, but otherwise there are no directives to get it to run a WSGI app.\n", "Just use some good web framework e.g. django and you can have such URLs\nmore than URLs you will have a better infrastructure, templates, db orm etc\n" ]
[ 14, 5, 4, 4, 4, 3 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000882430_cgi_python.txt
Q: Where to keep Python unit tests? Possible Duplicate: Where do the Python unit tests go? Are unit tests kept in the same file as the code, a separate file in the same directory, or in an entirely different directory? A: I always place my unit tests in a subdirectory to the related code called test. For example: /libs/authentication, the tests would be placed in /libs/authentication/tests A: I prefer to keep them in a seperate directory, usually called either "unittests" or just "tests". I then play games in the Makefile to have to automatically handle this directory, if it exists. It's a little bit of a pain to set up, but I personally prefer not to have the unit tests cluttering up the functional code. This way they are "close" enough to be obvious, but not in your face all the time. A: The usual project layout is to have a separate directory with tests, with the tests also subdivided by what they are testing. A: We keep a separate directory with a parallel class hierarchy. The unit test class name being Test[ClassNameUnderTest]. Should multiple test classes be needed, they are postfixed with an _ and additional text. A: I keep a separate test source tree that mimics the package structure of my source tree. Example: /src/main/java/com/xyz/MyClass.java /src/test/java/com/xyz/MyClassTest.java With this structure you can test package level methods.
Where to keep Python unit tests?
Possible Duplicate: Where do the Python unit tests go? Are unit tests kept in the same file as the code, a separate file in the same directory, or in an entirely different directory?
[ "I always place my unit tests in a subdirectory to the related code called test.\nFor example: /libs/authentication, the tests would be placed in /libs/authentication/tests\n", "I prefer to keep them in a seperate directory, usually called either \"unittests\" or just \"tests\". I then play games in the Makefile to have to automatically handle this directory, if it exists.\nIt's a little bit of a pain to set up, but I personally prefer not to have the unit tests cluttering up the functional code. This way they are \"close\" enough to be obvious, but not in your face all the time.\n", "The usual project layout is to have a separate directory with tests, with the tests also subdivided by what they are testing.\n", "We keep a separate directory with a parallel class hierarchy. The unit test class name being Test[ClassNameUnderTest]. Should multiple test classes be needed, they are postfixed with an _ and additional text.\n", "I keep a separate test source tree that mimics the package structure of my source tree.\nExample:\n/src/main/java/com/xyz/MyClass.java\n/src/test/java/com/xyz/MyClassTest.java\n\nWith this structure you can test package level methods.\n" ]
[ 15, 5, 3, 0, 0 ]
[ "for each project there is a test project\nExample naming\nmain project\n\nCompany.Project.Area\n\nmain project testing\n\nCompany.Project.Area.Test\n\n" ]
[ -1 ]
[ "code_organization", "python", "unit_testing" ]
stackoverflow_0000882399_code_organization_python_unit_testing.txt
Q: Is there a way to poll a file handle returned from subprocess.Popen? Say I write this: from subprocessing import Popen, STDOUT, PIPE p = Popen(["myproc"], stderr=STDOUT, stdout=PIPE) Now if I do line = p.stdout.readline() my program waits until the subprocess outputs the next line. Is there any magic I can do to p.stdout so that I could read the output if it's there, but just continue otherwise? I'm looking for something like Queue.get_nowait() I know I can just create a thread for reading p.stdout, but let's assume I can't create new threads. A: Use p.stdout.read(1) this will read character by character And here is a full example: import subprocess import sys process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) while True: out = process.stdout.read(1) if out == '' and process.poll() != None: break if out != '': sys.stdout.write(out) sys.stdout.flush() A: Use the select module in Python's standard library, see http://docs.python.org/library/select.html . select.select([p.stdout.fileno()], [], [], 0) immediately returns a tuple whose items are three lists: the first one is going to be non-empty if there's something to read on that file descriptor.
Is there a way to poll a file handle returned from subprocess.Popen?
Say I write this: from subprocessing import Popen, STDOUT, PIPE p = Popen(["myproc"], stderr=STDOUT, stdout=PIPE) Now if I do line = p.stdout.readline() my program waits until the subprocess outputs the next line. Is there any magic I can do to p.stdout so that I could read the output if it's there, but just continue otherwise? I'm looking for something like Queue.get_nowait() I know I can just create a thread for reading p.stdout, but let's assume I can't create new threads.
[ "Use p.stdout.read(1) this will read character by character\nAnd here is a full example:\nimport subprocess\nimport sys\n\nprocess = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n)\n\nwhile True:\n out = process.stdout.read(1)\n if out == '' and process.poll() != None:\n break\n if out != '':\n sys.stdout.write(out)\n sys.stdout.flush()\n\n", "Use the select module in Python's standard library, see http://docs.python.org/library/select.html . select.select([p.stdout.fileno()], [], [], 0) immediately returns a tuple whose items are three lists: the first one is going to be non-empty if there's something to read on that file descriptor.\n" ]
[ 8, 5 ]
[]
[]
[ "pipe", "python", "subprocess" ]
stackoverflow_0000883152_pipe_python_subprocess.txt
Q: Python unittest: how do I test the argument in an Exceptions? I am testing for Exceptions using unittest, for example: self.assertRaises(UnrecognizedAirportError, func, arg1, arg2) and my code raises: raise UnrecognizedAirportError('From') Which works well. How do I test that the argument in the exception is what I expect it to be? I wish to somehow assert that capturedException.argument == 'From'. I hope this is clear enough - thanks in advance! Tal. A: Like this. >>> try: ... raise UnrecognizedAirportError("func","arg1","arg2") ... except UnrecognizedAirportError, e: ... print e.args ... ('func', 'arg1', 'arg2') >>> Your arguments are in args, if you simply subclass Exception. See http://docs.python.org/library/exceptions.html#module-exceptions If the exception class is derived from the standard root class BaseException, the associated value is present as the exception instance’s args attribute. Edit Bigger Example. class TestSomeException( unittest.TestCase ): def testRaiseWithArgs( self ): try: ... Something that raises the exception ... self.fail( "Didn't raise the exception" ) except UnrecognizedAirportError, e: self.assertEquals( "func", e.args[0] ) self.assertEquals( "arg1", e.args[1] ) except Exception, e: self.fail( "Raised the wrong exception" ) A: assertRaises is a bit simplistic, and doesn't let you test the details of the raised exception beyond it belonging to a specified class. For finer-grained testing of exceptions, you need to "roll your own" with a try/except/else block (you can do it once and for all in a def assertDetailedRaises method you add to your own generic subclass of unittest's test-case, then have your test cases all inherit your subclass instead of unittest's).
Python unittest: how do I test the argument in an Exceptions?
I am testing for Exceptions using unittest, for example: self.assertRaises(UnrecognizedAirportError, func, arg1, arg2) and my code raises: raise UnrecognizedAirportError('From') Which works well. How do I test that the argument in the exception is what I expect it to be? I wish to somehow assert that capturedException.argument == 'From'. I hope this is clear enough - thanks in advance! Tal.
[ "Like this.\n>>> try:\n... raise UnrecognizedAirportError(\"func\",\"arg1\",\"arg2\")\n... except UnrecognizedAirportError, e:\n... print e.args\n...\n('func', 'arg1', 'arg2')\n>>>\n\nYour arguments are in args, if you simply subclass Exception. \nSee http://docs.python.org/library/exceptions.html#module-exceptions\n\nIf the exception class is derived from\n the standard root class BaseException,\n the associated value is present as the\n exception instance’s args attribute.\n\n\nEdit Bigger Example.\nclass TestSomeException( unittest.TestCase ):\n def testRaiseWithArgs( self ):\n try:\n ... Something that raises the exception ...\n self.fail( \"Didn't raise the exception\" )\n except UnrecognizedAirportError, e:\n self.assertEquals( \"func\", e.args[0] )\n self.assertEquals( \"arg1\", e.args[1] )\n except Exception, e:\n self.fail( \"Raised the wrong exception\" )\n\n", "assertRaises is a bit simplistic, and doesn't let you test the details of the raised exception beyond it belonging to a specified class. For finer-grained testing of exceptions, you need to \"roll your own\" with a try/except/else block (you can do it once and for all in a def assertDetailedRaises method you add to your own generic subclass of unittest's test-case, then have your test cases all inherit your subclass instead of unittest's).\n" ]
[ 11, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0000883357_python_unit_testing.txt
Q: wxPython + multiprocessing: Checking if a color string is legitimate I have a wxPython program with two processes: A primary and a secondary one (I'm using the multiprocessing module.) The primary one runs the wxPython GUI, the secondary one does not. However, there is something I would like to do from the secondary process: Given a string that describes a color, to check whether this would be legitimate color for wxPython. That means, whether I can create a wx.Pen(color_string) or not. How do I do this? (I tried making a wx.Pen and comparing its color to the null color, but that required to create a wx.App in the second process, and when I did create one the program raised an error in some special wxPython window.) A: You could make two Queues between the two processes and have the second one delegate wx-related functionality to the first one (by pushing on the first queue the parameters of the task to perform, and waiting for the result on the second one).
wxPython + multiprocessing: Checking if a color string is legitimate
I have a wxPython program with two processes: A primary and a secondary one (I'm using the multiprocessing module.) The primary one runs the wxPython GUI, the secondary one does not. However, there is something I would like to do from the secondary process: Given a string that describes a color, to check whether this would be legitimate color for wxPython. That means, whether I can create a wx.Pen(color_string) or not. How do I do this? (I tried making a wx.Pen and comparing its color to the null color, but that required to create a wx.App in the second process, and when I did create one the program raised an error in some special wxPython window.)
[ "You could make two Queues between the two processes and have the second one delegate wx-related functionality to the first one (by pushing on the first queue the parameters of the task to perform, and waiting for the result on the second one).\n" ]
[ 1 ]
[]
[]
[ "multiprocessing", "python", "wxpython" ]
stackoverflow_0000883348_multiprocessing_python_wxpython.txt
Q: Calling python from python - persistence of module imports? So I have some Python scripts, and I've got a BaseHTTPServer to serve up their responses. If the requested file is a .py then I'll run that script using execfile(script.py). The question is this: are there any special rules about imports? One script needs to run just once, and it would be good to keep the objects it creates alive between requests. Can I trust that that will happen? Does script run via execfile() run any differently, or have any scope access issues? A: The documentation for the execfile method is here. Since no particular version of python was specified, I'm going to assume we're talking about 2.6.2. The documentation for execfile specifies it takes three arguments: the filename, a dictionary (to act as the local variables), and a second dictionary (to act as the global variables). If you omit the second and third arguments, the file's contents are run in their own scope (like a module) that captures local variables but exposes global variables to the parent scope. So if the file creates local variables, they won't be retained, but global variables will be retained. However, running execfile without local and global contexts specified means that the file sees the locals and globals of the calling function. For code that you don't trust, this should be considered a security hole. It may generally be wise to create two dictionaries for locals and globals and pass those in as the second and third arguments to execfile. If you keep those dictionaries somewhere (such as in another dictionary keyed by the filename), then you could re-use those dictionaries the next time the file is served, which will keep the objects created by the file alive. So in short: execfile isn't exactly like import. But you can retain dictionaries of the locals and globals to keep the results of an execfile call around to be used again. A: I recommend not using execfile. Instead, you can dynamically import the python file they request as a module using the builtin __import__ function. Here's a complete, working example that I just wrote and tested: from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() filename = self.path.lstrip("/") self.wfile.write("You requested " + filename + "\n\n") if filename.endswith(".py"): pyname = filename.replace("/", ".")[:-3] module = __import__(pyname) self.wfile.write( module.do_work() ) HTTPServer(("",8080), Handler).serve_forever() So in this case, if someone visits http://localhost:8080/some_page then "You requested some_page" will be printed. But if you request http://localhost:8080/some_module.py then the file some_module.py will be imported as a Python module and the do_work function in that module will be called. So if that module contains the code def do_work(): return "Hello World!" and you make that request, then the resulting page will be You requested some_module.py Hello World! This should be a good starting point for dealing with such things. As an aside, if you find yourself wanting a more advanced web server, I highly recommend CherryPy.
Calling python from python - persistence of module imports?
So I have some Python scripts, and I've got a BaseHTTPServer to serve up their responses. If the requested file is a .py then I'll run that script using execfile(script.py). The question is this: are there any special rules about imports? One script needs to run just once, and it would be good to keep the objects it creates alive between requests. Can I trust that that will happen? Does script run via execfile() run any differently, or have any scope access issues?
[ "The documentation for the execfile method is here. Since no particular version of python was specified, I'm going to assume we're talking about 2.6.2.\nThe documentation for execfile specifies it takes three arguments: the filename, a dictionary (to act as the local variables), and a second dictionary (to act as the global variables). If you omit the second and third arguments, the file's contents are run in their own scope (like a module) that captures local variables but exposes global variables to the parent scope. So if the file creates local variables, they won't be retained, but global variables will be retained.\nHowever, running execfile without local and global contexts specified means that the file sees the locals and globals of the calling function. For code that you don't trust, this should be considered a security hole. It may generally be wise to create two dictionaries for locals and globals and pass those in as the second and third arguments to execfile. If you keep those dictionaries somewhere (such as in another dictionary keyed by the filename), then you could re-use those dictionaries the next time the file is served, which will keep the objects created by the file alive.\nSo in short: execfile isn't exactly like import. But you can retain dictionaries of the locals and globals to keep the results of an execfile call around to be used again.\n", "I recommend not using execfile. Instead, you can dynamically import the python file they request as a module using the builtin __import__ function. Here's a complete, working example that I just wrote and tested:\nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\n\nclass Handler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/plain\")\n self.end_headers()\n\n filename = self.path.lstrip(\"/\")\n self.wfile.write(\"You requested \" + filename + \"\\n\\n\")\n if filename.endswith(\".py\"):\n pyname = filename.replace(\"/\", \".\")[:-3]\n module = __import__(pyname)\n self.wfile.write( module.do_work() )\n\nHTTPServer((\"\",8080), Handler).serve_forever()\n\nSo in this case, if someone visits http://localhost:8080/some_page then \"You requested some_page\" will be printed.\nBut if you request http://localhost:8080/some_module.py then the file some_module.py will be imported as a Python module and the do_work function in that module will be called. So if that module contains the code\ndef do_work():\n return \"Hello World!\"\n\nand you make that request, then the resulting page will be\nYou requested some_module.py\n\nHello World!\n\nThis should be a good starting point for dealing with such things. As an aside, if you find yourself wanting a more advanced web server, I highly recommend CherryPy.\n" ]
[ 2, 1 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0000883211_import_module_python.txt
Q: Custom implementation of "tail -f" functionality in C EDIT: I used, finally, inotify. As stefanB says, inotify is the thing to use. I found a tail clone that uses inotify to implement the -f mode, inotail. Original question text: I'm trying to implement the "tail -f" logic in a C project, for prototyping purposes I developed it in python as follow: # A forever loop, each 5 seconds writes a line into file.txt from time import * while 1: sleep(5) file = open("file.txt", "a") file.write("This is a test\n") file.close() The next code follows the eof of file.txt (updated by the code above) # tail -f from time import * file = open("file.txt", "r") file.seek(0, 2) while 1: line = file.readline() if not line: sleep(1) else: print line file.close() All works fine but the C implementation is not working (there are no check-error code). The inclusion of stdio.h, string.h and unistd.h is omitted (the colorization hides the header inclusion code). #define LINE_LEN 256 int main(int argc, char **argv) { FILE *f; char line[LINE_LEN]; f = fopen("file.txt", "r"); fseek(f, 0, SEEK_END); while (1) { fgets(line, LINE_LEN, f); if (strlen(line) == 0) { sleep(1); } else { printf("Readed: %s", line); } } fclose(f); return 0; } Some idea? Is a good idea implement it with a poll() instead the presented solution?. Thanks in advance. A: Once a FILE * has seen an error or eof, it has its internal status set so that it continues to return error or eof on subsequent calls. You need to call clearerr(f); after the sleep returns to clear the eof setting and get it to try to read more data from the file. A: EDIT: Seems like inotify is the thing to use. It should be included in linux kernel since 2.6.13 . An article from IBM developerworks about inotify. Previous answer: Have a look at Linux File Alteration Monitor (in linux kernels 2.4.x >). It's a framework that let's you subscribe for file changes and you get callback from kernel when change happens. This should be better than polling. Examples how to poll for file changes, check out sections Waiting for file changes and Polling for file changes. I haven't tried it yet. A: From the tail man page: -f Do not stop when end-of-file is reached, but rather to wait for additional data to be appended to the input. If the file is replaced (i.e., the inode number changes), tail will reopen the file and continue. If the file is truncated, tail will reset its position to the beginning. This makes tail more useful for watching log files that may get rotated. The -f option is ignored if the standard input is a pipe, but not if it is a FIFO. So, you could do the same thing: Use stat() to read the inode number of the file Display the contents of that file. Store the position of the file descriptor eg, p = ftell(fd) Use stat() again, and see if the inode has changed. If so, display the contents of the file from position p onward Repeat
Custom implementation of "tail -f" functionality in C
EDIT: I used, finally, inotify. As stefanB says, inotify is the thing to use. I found a tail clone that uses inotify to implement the -f mode, inotail. Original question text: I'm trying to implement the "tail -f" logic in a C project, for prototyping purposes I developed it in python as follow: # A forever loop, each 5 seconds writes a line into file.txt from time import * while 1: sleep(5) file = open("file.txt", "a") file.write("This is a test\n") file.close() The next code follows the eof of file.txt (updated by the code above) # tail -f from time import * file = open("file.txt", "r") file.seek(0, 2) while 1: line = file.readline() if not line: sleep(1) else: print line file.close() All works fine but the C implementation is not working (there are no check-error code). The inclusion of stdio.h, string.h and unistd.h is omitted (the colorization hides the header inclusion code). #define LINE_LEN 256 int main(int argc, char **argv) { FILE *f; char line[LINE_LEN]; f = fopen("file.txt", "r"); fseek(f, 0, SEEK_END); while (1) { fgets(line, LINE_LEN, f); if (strlen(line) == 0) { sleep(1); } else { printf("Readed: %s", line); } } fclose(f); return 0; } Some idea? Is a good idea implement it with a poll() instead the presented solution?. Thanks in advance.
[ "Once a FILE * has seen an error or eof, it has its internal status set so that it continues to return error or eof on subsequent calls. You need to call clearerr(f); after the sleep returns to clear the eof setting and get it to try to read more data from the file.\n", "EDIT:\nSeems like inotify is the thing to use. It should be included in linux kernel since 2.6.13 . An article from IBM developerworks about inotify.\nPrevious answer:\nHave a look at Linux File Alteration Monitor (in linux kernels 2.4.x >). It's a framework that let's you subscribe for file changes and you get callback from kernel when change happens. This should be better than polling.\nExamples how to poll for file changes, check out sections Waiting for file changes and Polling for file changes.\nI haven't tried it yet.\n", "From the tail man page:\n\n-f Do not stop when end-of-file is reached, but rather to wait for\n additional data to be appended to the\n input. If the file is replaced (i.e.,\n the inode number changes), tail will\n reopen the file and continue. If the\n file is truncated, tail will reset its\n position to the beginning. This makes\n tail more useful for watching log\n files that may get rotated. The -f\n option is ignored if the standard\n input is a pipe, but not if it is a\n FIFO.\n\nSo, you could do the same thing:\n\nUse stat() to read the inode number of the file\nDisplay the contents of that file. Store the position of the file descriptor eg, p = ftell(fd)\nUse stat() again, and see if the inode has changed. If so, display the contents of the file from position p onward\nRepeat \n\n" ]
[ 3, 3, 2 ]
[]
[]
[ "c", "python" ]
stackoverflow_0000883784_c_python.txt
Q: How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods? I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die class to learn more about syntax and use of classes and instances. Here is the original code: class Die(object): ''' simulate a six-sided die ''' def roll(self): self.value=random.randrange(1,7) return self.value def getValue(self): return self.value I was looking at that and after creating some instances I wondered if the word value was a keyword somehow and what the use of the word object in the class statement did and so I decided to find out by changing the class definition to the following: class Die(): ''' simulate a six-sided die ''' def roll(self): self.ban=random.randrange(1,7) return self.ban def getValue(self): return self.ban That change showed me that I got the same behavior from my instances but the following methods/attributes were missing from the instances when I did dir: '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', _repr__', '__setattr__', '__str__', '__weakref__' I also figured out that when I did a dir on an instance I had an additional keyword-ban which I finally figured out was an attribute of my instance. This helped me understand that I could use d1.ban to access the value of my instance. The only reason I could figure out that this was an attribute was I typed d1.happy and got an AttributeError I figured out that d1.GetValue was a method attached to Die because that is what the interpreter told me. So when I am trying to use some complicated but helpful module like BeautifulSoup how can I know which of the things that are listed are attributes of my instance or methods of my instance after typing dir(instance). I would need to know this because this poking around has taught me that with attributes I am calling the result of a method and with methods I am invoking a function on my instance. This question is probably too wordy but it sure did help me better understand the difference between attributes and methods. Specifically, when I look at the result of calling dir on an instance of my Die class I see this ['__doc__', '__module__', 'ban', 'getValue', 'roll'] So it would seem useful to know by looking at that list which are attributes and which are methods without having to resort to trial and error or result to typing in hasattr(myInstance,suspectedAttributeName). After posting the question I tried for each in dir(d1): print hasattr(d1,each) which tells me strictly speaking that all methods are attributes. but I can't call a method without the () so it seems to me that the hasattr() is misleading. A: Instead of: "print hasattr(d1,each)", try: "print each, type(getattr(d1,each))". You should find the results informative. Also, in place of dir() try help(), which I think you're really looking for. A: Consider using the standard library's inspect module -- it's often the handiest approach to introspection, packaging up substantial chunks of functionality (you could implement that from scratch, but reusing well-tested, well-designed code is a good thing). See http://docs.python.org/library/inspect.html for all the details, but for example inspect.getmembers(foo, inspect.ismethod) is an excellent way to get all methods of foo (you'll get (name, value) pairs sorted by name). A: which tells me strictly speaking that all methods are attributes. but I can't call a method without the () so it seems to me that the hasattr() is misleading. Why is it misleading? If obj.ban() is a method, then obj.ban is the corresponding attribute. You can have code like this: print obj.getValue() or get = obj.getValue print get() If you want to get a list of methods on an object, you can try this function. It's not perfect, since it will also trigger for callable attributes that aren't methods, but for 99% of cases should be good enough: def methods(obj): attrs = (getattr(obj, n) for n in dir(obj)) return [a for a in attrs if a.hasattr("__call__")] A: This info module inspired from Dive into Python serves the purpose. def info(obj, spacing=20, collapse=1, variables=False): '''Print methods and their doc Strings Takes any object''' if variables: methodList = [method for method in dir(obj)] else: methodList = [method for method in dir(obj) if callable(getattr(obj,method))] #print methodList print '\n'.join(['%s %s' % (method.ljust(spacing), " ".join(str(getattr(obj,method).__doc__).split())) for method in methodList]) if __name__=='__main__': info(list) A: Ideally, when using a complicated library like BeautifulSoup, you should consult its documentation to see what methods each class provides. However, in the rare case where you don't have easily accessible documentation, you can check for the presence of methods using the following. All methods, which themselves are objects, implement the __call__ method and can be checked using the callable() method which returns True, if the value being checked has the __call__ method. The following code should work. x = Die() x.roll() for attribute in dir(x) : print attribute, callable(getattr(x, attribute)) The above code would return true for all the methods and false for all non callable attributes (such as data members like ban). However, this method also returns True for any callable objects (like inner classes). you can also check if the type of the attribute is instancemethod A: There is a built in method called callable. You can apply it to any object and it will return True/False depending on if it can be called. e.g. >>> def foo(): ... print "This is the only function now" ... >>> localDictionary = dir() >>> for item in localDictionary: ... print repr(item) + "is callable: " + str(callable(locals()[item])) '__builtins__'is callable: False '__doc__'is callable: False '__name__'is callable: False 'foo'is callable: True Note the locals() call will return a dictionary containing everything defined in your current scope. I did this because the items out of the dictionary are just strings, and we need to run callable on the actual object.
How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods?
I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die class to learn more about syntax and use of classes and instances. Here is the original code: class Die(object): ''' simulate a six-sided die ''' def roll(self): self.value=random.randrange(1,7) return self.value def getValue(self): return self.value I was looking at that and after creating some instances I wondered if the word value was a keyword somehow and what the use of the word object in the class statement did and so I decided to find out by changing the class definition to the following: class Die(): ''' simulate a six-sided die ''' def roll(self): self.ban=random.randrange(1,7) return self.ban def getValue(self): return self.ban That change showed me that I got the same behavior from my instances but the following methods/attributes were missing from the instances when I did dir: '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', _repr__', '__setattr__', '__str__', '__weakref__' I also figured out that when I did a dir on an instance I had an additional keyword-ban which I finally figured out was an attribute of my instance. This helped me understand that I could use d1.ban to access the value of my instance. The only reason I could figure out that this was an attribute was I typed d1.happy and got an AttributeError I figured out that d1.GetValue was a method attached to Die because that is what the interpreter told me. So when I am trying to use some complicated but helpful module like BeautifulSoup how can I know which of the things that are listed are attributes of my instance or methods of my instance after typing dir(instance). I would need to know this because this poking around has taught me that with attributes I am calling the result of a method and with methods I am invoking a function on my instance. This question is probably too wordy but it sure did help me better understand the difference between attributes and methods. Specifically, when I look at the result of calling dir on an instance of my Die class I see this ['__doc__', '__module__', 'ban', 'getValue', 'roll'] So it would seem useful to know by looking at that list which are attributes and which are methods without having to resort to trial and error or result to typing in hasattr(myInstance,suspectedAttributeName). After posting the question I tried for each in dir(d1): print hasattr(d1,each) which tells me strictly speaking that all methods are attributes. but I can't call a method without the () so it seems to me that the hasattr() is misleading.
[ "Instead of: \"print hasattr(d1,each)\", try: \"print each, type(getattr(d1,each))\". You should find the results informative. \nAlso, in place of dir() try help(), which I think you're really looking for.\n", "Consider using the standard library's inspect module -- it's often the handiest approach to introspection, packaging up substantial chunks of functionality (you could implement that from scratch, but reusing well-tested, well-designed code is a good thing). See http://docs.python.org/library/inspect.html for all the details, but for example inspect.getmembers(foo, inspect.ismethod) is an excellent way to get all methods of foo (you'll get (name, value) pairs sorted by name).\n", "\nwhich tells me strictly speaking that all methods are attributes. but I can't call a method without the () so it seems to me that the hasattr() is misleading.\n\nWhy is it misleading? If obj.ban() is a method, then obj.ban is the corresponding attribute. You can have code like this:\nprint obj.getValue()\n\nor\nget = obj.getValue\nprint get()\n\nIf you want to get a list of methods on an object, you can try this function. It's not perfect, since it will also trigger for callable attributes that aren't methods, but for 99% of cases should be good enough:\ndef methods(obj):\n attrs = (getattr(obj, n) for n in dir(obj))\n return [a for a in attrs if a.hasattr(\"__call__\")]\n\n", "This info module inspired from Dive into Python serves the purpose. \ndef info(obj, spacing=20, collapse=1, variables=False):\n '''Print methods and their doc Strings\n\n Takes any object'''\n if variables:\n methodList = [method for method in dir(obj)]\n else:\n methodList = [method for method in dir(obj) if callable(getattr(obj,method))]\n\n #print methodList\n\n\n print '\\n'.join(['%s %s' %\n (method.ljust(spacing),\n \" \".join(str(getattr(obj,method).__doc__).split()))\n for method in methodList])\n\n\nif __name__=='__main__':\n info(list)\n\n", "Ideally, when using a complicated library like BeautifulSoup, you should consult its documentation to see what methods each class provides. However, in the rare case where you don't have easily accessible documentation, you can check for the presence of methods using the following. \nAll methods, which themselves are objects, implement the __call__ method and can be checked using the callable() method which returns True, if the value being checked has the __call__ method. \nThe following code should work.\nx = Die()\nx.roll()\n\nfor attribute in dir(x) :\n print attribute, callable(getattr(x, attribute))\n\nThe above code would return true for all the methods and false for all non callable attributes (such as data members like ban). However, this method also returns True for any callable objects (like inner classes). you can also check if the type of the attribute is instancemethod\n", "There is a built in method called callable. You can apply it to any object and it will return True/False depending on if it can be called. e.g.\n>>> def foo():\n... print \"This is the only function now\"\n...\n>>> localDictionary = dir()\n>>> for item in localDictionary:\n... print repr(item) + \"is callable: \" + str(callable(locals()[item]))\n'__builtins__'is callable: False\n'__doc__'is callable: False\n'__name__'is callable: False\n'foo'is callable: True\n\nNote the locals() call will return a dictionary containing everything defined in your current scope. I did this because the items out of the dictionary are just strings, and we need to run callable on the actual object.\n" ]
[ 8, 4, 2, 2, 1, 1 ]
[]
[]
[ "attributes", "methods", "python", "python_datamodel" ]
stackoverflow_0000880160_attributes_methods_python_python_datamodel.txt
Q: How to return a function value with decorator and thread have this code import threading def Thread(f): def decorator(*args,**kargs): print(args) thread = threading.Thread(target=f, args=args) thread.start() thread.join() decorator.__name__ = f.__name__ return decorator @Thread def add_item(a, b): return a+b print(add_item(2,2)) but the function never return the value, exits a way to get the return ? A: The reason None is returned, is because there is nothing to return (besides the fact that decorator doesn't have a return statement). join() always returns None, as per the documentation. For an example of how to communicate with a thread, see this email. If I may ask though: since join() blocks the calling thread, what is there to gain here? Edit: I played around a bit, and the following is a solution that doesn't require a queue (not saying it's a better solution. Just different): import threading # Callable that stores the result of calling the given callable f. class ResultCatcher: def __init__(self, f): self.f = f self.val = None def __call__(self, *args, **kwargs): self.val = self.f(*args, **kwargs) def threaded(f): def decorator(*args,**kargs): # Encapsulate f so that the return value can be extracted. retVal = ResultCatcher(f) th = threading.Thread(target=retVal, args=args) th.start() th.join() # Extract and return the result of executing f. return retVal.val decorator.__name__ = f.__name__ return decorator @threaded def add_item(a, b): return a + b print(add_item(2, 2)) A: That's because you never return a value in your "decorator"-function. You have to include a shared variable in your thread and move the return value of your threaded function back into the "decorator"-function.
How to return a function value with decorator and thread
have this code import threading def Thread(f): def decorator(*args,**kargs): print(args) thread = threading.Thread(target=f, args=args) thread.start() thread.join() decorator.__name__ = f.__name__ return decorator @Thread def add_item(a, b): return a+b print(add_item(2,2)) but the function never return the value, exits a way to get the return ?
[ "The reason None is returned, is because there is nothing to return (besides the fact that decorator doesn't have a return statement). join() always returns None, as per the documentation.\nFor an example of how to communicate with a thread, see this email.\nIf I may ask though: since join() blocks the calling thread, what is there to gain here?\n\nEdit: I played around a bit, and the following is a solution that doesn't require a queue (not saying it's a better solution. Just different):\nimport threading\n\n# Callable that stores the result of calling the given callable f.\nclass ResultCatcher:\n def __init__(self, f):\n self.f = f\n self.val = None\n\n def __call__(self, *args, **kwargs):\n self.val = self.f(*args, **kwargs)\n\ndef threaded(f):\n def decorator(*args,**kargs):\n # Encapsulate f so that the return value can be extracted.\n retVal = ResultCatcher(f)\n\n th = threading.Thread(target=retVal, args=args)\n th.start()\n th.join()\n\n # Extract and return the result of executing f.\n return retVal.val\n\n decorator.__name__ = f.__name__\n return decorator\n\n@threaded\ndef add_item(a, b):\n return a + b\n\nprint(add_item(2, 2))\n\n", "That's because you never return a value in your \"decorator\"-function.\nYou have to include a shared variable in your thread and move the return value of your threaded function back into the \"decorator\"-function.\n" ]
[ 4, 2 ]
[]
[]
[ "decorator", "multithreading", "python" ]
stackoverflow_0000884410_decorator_multithreading_python.txt
Q: How can I create a RSA public key in PEM format from an RSA modulus? I have the modulus of an RSA public key. I want to use this public key with the Python library "M2Crypto", but it requires a public key in PEM format. Thus, I have to convert the RSA modulus to a PEM file. The modulus can be found here. Any ideas? A: The M2Crypto library has a way to reconstruct a public key. You need to know the public exponent, e (often 65337 for RSA keys, but other numbers such as 3 or 17 have been used), and the modulus, n (which is the 512-bit number provided in the question). Note that the docs describe the length-encoded format used for e and n. Once the public key has been reconstructed, it can be saved into a file and used again later without the hassle of conversion.
How can I create a RSA public key in PEM format from an RSA modulus?
I have the modulus of an RSA public key. I want to use this public key with the Python library "M2Crypto", but it requires a public key in PEM format. Thus, I have to convert the RSA modulus to a PEM file. The modulus can be found here. Any ideas?
[ "The M2Crypto library has a way to reconstruct a public key. You need to know the public exponent, e (often 65337 for RSA keys, but other numbers such as 3 or 17 have been used), and the modulus, n (which is the 512-bit number provided in the question). Note that the docs describe the length-encoded format used for e and n.\nOnce the public key has been reconstructed, it can be saved into a file and used again later without the hassle of conversion.\n" ]
[ 4 ]
[]
[]
[ "cryptography", "m2crypto", "python", "rsa" ]
stackoverflow_0000884207_cryptography_m2crypto_python_rsa.txt
Q: wxPython: Drawing a vector-based image from file How can I draw a vector-based image from a file in wxPython? I know nothing of image formats for such a thing, so please recommend. A: You can do this with using cairo & librsvg python bindings. There is a small example here. A: I have done something similar, I had a custom vector image format that I needed to render in a wxPython window. In order to accomplish this I used the GDI interface for drawing commands and I wrote my own parser module. There is a great GDI tutorial at this site that should help you out: http://www.zetcode.com/wxpython/gdi/
wxPython: Drawing a vector-based image from file
How can I draw a vector-based image from a file in wxPython? I know nothing of image formats for such a thing, so please recommend.
[ "You can do this with using cairo & librsvg python bindings. There is a small example here.\n", "I have done something similar, I had a custom vector image format that I needed to render in a wxPython window. In order to accomplish this I used the GDI interface for drawing commands and I wrote my own parser module. There is a great GDI tutorial at this site that should help you out: http://www.zetcode.com/wxpython/gdi/\n" ]
[ 3, 1 ]
[]
[]
[ "python", "vector_graphics", "wxpython" ]
stackoverflow_0000844110_python_vector_graphics_wxpython.txt
Q: Django Admin & Model Deletion I've got a bunch of classes that inherit from a common base class. This common base class does some cleaning up in its delete method. class Base(models.Model): def delete(self): print "foo" class Child(Base): def delete(self): print "bar" super(Child, self).delete() When I call delete on the Child from the shell I get: bar foo as expected When I use the admin, the custom delete functions don't seem to get called. Am I missing something obvious? Thanks, Dom p.s. This is obviously a simplified version of the code I'm using, apologies if it contains typos. Feel free to leave a comment and I'll fix it. A: According to this documentation bug report (Document that the admin bulk delete doesn't call Model.delete()), the admin's bulk delete does NOT call the model's delete function. If you're using bulk delete from the admin, this would explain your problem. From the added documentation on this ticket, the advice is to write a custom bulk delete function that does call the model's delete function. Further information on this behavior is here. The bulk delete action doesn't call the model's delete() method for the sake of efficiency.
Django Admin & Model Deletion
I've got a bunch of classes that inherit from a common base class. This common base class does some cleaning up in its delete method. class Base(models.Model): def delete(self): print "foo" class Child(Base): def delete(self): print "bar" super(Child, self).delete() When I call delete on the Child from the shell I get: bar foo as expected When I use the admin, the custom delete functions don't seem to get called. Am I missing something obvious? Thanks, Dom p.s. This is obviously a simplified version of the code I'm using, apologies if it contains typos. Feel free to leave a comment and I'll fix it.
[ "According to this documentation bug report (Document that the admin bulk delete doesn't call Model.delete()), the admin's bulk delete does NOT call the model's delete function. If you're using bulk delete from the admin, this would explain your problem.\nFrom the added documentation on this ticket, the advice is to write a custom bulk delete function that does call the model's delete function.\nFurther information on this behavior is here. The bulk delete action doesn't call the model's delete() method for the sake of efficiency.\n" ]
[ 9 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0000885103_django_django_admin_python.txt
Q: Problems eagerloading a set of object using SQLAlchemy I'm using Turbogears2 and SQLAlchemy to develop a webapp. I have two mapped tables O1 and O2. O2 has a sorted list of O1s in 'ones'. At some point I want to query all O2's and the referenced O1's. Unfortunately the query below fails because table O2 is aliased in the query and the column referenced by the order_by phrase is no longer known. I'd like to know how I can fix this problem while, if possible, staying in the declarative syntax. base = declarative_base() class O1(base): __tablename__ = 'O1' value = Column(Integer) o2_id = Column(Integer, ForeignKey('O1.id')) # The culprit class O2(base): __tablename__ = 'O2' id = Column(Integer, primary_key=True) ones = relation('O1', order_by = ['O1.value']) Session.query(O2).options(eagerload('ones')).all() # Throws an error A: Use a lambda of clause elements to achieve late binding of the order by, like this: ones = relation('O1', order_by=lambda:[O1.value]) Or as an another option, make the whole order_by a string, like this: ones = relation('O1', order_by='O1.value, O1.something_else')
Problems eagerloading a set of object using SQLAlchemy
I'm using Turbogears2 and SQLAlchemy to develop a webapp. I have two mapped tables O1 and O2. O2 has a sorted list of O1s in 'ones'. At some point I want to query all O2's and the referenced O1's. Unfortunately the query below fails because table O2 is aliased in the query and the column referenced by the order_by phrase is no longer known. I'd like to know how I can fix this problem while, if possible, staying in the declarative syntax. base = declarative_base() class O1(base): __tablename__ = 'O1' value = Column(Integer) o2_id = Column(Integer, ForeignKey('O1.id')) # The culprit class O2(base): __tablename__ = 'O2' id = Column(Integer, primary_key=True) ones = relation('O1', order_by = ['O1.value']) Session.query(O2).options(eagerload('ones')).all() # Throws an error
[ "Use a lambda of clause elements to achieve late binding of the order by, like this:\nones = relation('O1', order_by=lambda:[O1.value])\n\nOr as an another option, make the whole order_by a string, like this:\nones = relation('O1', order_by='O1.value, O1.something_else')\n\n" ]
[ 3 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0000885235_orm_python_sqlalchemy.txt
Q: What is an exotic function signature in Python? I recently saw a reference to "exotic signatures" and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is def exotic_signature((x, y)=(1,2)): return x+y What makes this an "exotic" signature? A: What's exotic is that x and y represent a single function argument that is unpacked into two values... x and y. It's equivalent to: def func(n): x, y = n ... Both functions require a single argument (list or tuple) that contains two elements. A: More information about tuple parameter unpacking (and why it is removed) here: http://www.python.org/dev/peps/pep-3113/ A: Here's a slightly more complex example. Let's say you're doing some kind of graphics programming and you've got a list of points. points = [(1,2), (-3,1), (4,-2), (-1,5), (3,3)] and you want to know how far away they are from the origin. You might define a function like this: def magnitude((x,y)): return (x**2 + y**2)**0.5 and then you can find the distances of your points from (0,0) as: map(magnitude, points) ...well, at least, you could in python 2.x :-)
What is an exotic function signature in Python?
I recently saw a reference to "exotic signatures" and the fact they had been deprecated in 2.6 (and removed in 3.0). The example given is def exotic_signature((x, y)=(1,2)): return x+y What makes this an "exotic" signature?
[ "What's exotic is that x and y represent a single function argument that is unpacked into two values... x and y. It's equivalent to:\ndef func(n):\n x, y = n\n ...\n\nBoth functions require a single argument (list or tuple) that contains two elements.\n", "More information about tuple parameter unpacking (and why it is removed) here:\nhttp://www.python.org/dev/peps/pep-3113/\n", "Here's a slightly more complex example. Let's say you're doing some kind of graphics programming and you've got a list of points.\npoints = [(1,2), (-3,1), (4,-2), (-1,5), (3,3)]\n\nand you want to know how far away they are from the origin. You might define a function like this:\ndef magnitude((x,y)):\n return (x**2 + y**2)**0.5\n\nand then you can find the distances of your points from (0,0) as:\nmap(magnitude, points)\n\n...well, at least, you could in python 2.x :-)\n" ]
[ 6, 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000884068_python.txt
Q: wxPython dialogs: "Enter" keyboard button would not "ok" the dialog I am creating a custom wxPython dialog by subclassing wx.Dialog. When I press Enter while using it, (and while being focused on one of the form elements,) it just takes the focus to the next form element, while I want it to press the ok button. How do I solve this? A: That should happen automatically if the button has the wx.ID_OK id. If that's impossible then the wx.StdDialogButtonSizer.SetAffirmativeButton() method could be a solution (using the StdDialogButtonSizer class will help with correct button placement and positioning on the different platforms), and there is also wx.Button.SetDefault().
wxPython dialogs: "Enter" keyboard button would not "ok" the dialog
I am creating a custom wxPython dialog by subclassing wx.Dialog. When I press Enter while using it, (and while being focused on one of the form elements,) it just takes the focus to the next form element, while I want it to press the ok button. How do I solve this?
[ "That should happen automatically if the button has the wx.ID_OK id. If that's impossible then the wx.StdDialogButtonSizer.SetAffirmativeButton() method could be a solution (using the StdDialogButtonSizer class will help with correct button placement and positioning on the different platforms), and there is also wx.Button.SetDefault().\n" ]
[ 5 ]
[]
[]
[ "keyboard", "python", "wxpython" ]
stackoverflow_0000885294_keyboard_python_wxpython.txt
Q: Wrapping a Python Object I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects: def __init__(self, anObject): self.theObject = anObject and provides a "write" method: def write(self, pathOrFile): plistlib.writeToPlist(self.theObject.__dict__, pathOrFile) Now it would be nice if the PlistObject behaved just like wrapped object itself, meaning that all attributes and methods are somehow "forwarded" to the wrapped object. I realize that the methods __getattr__ and __setattr__ can be used for complex attribute operations: def __getattr__(self, name): return self.theObject.__getattr__(name) But then of course I run into the problem that the constructor now produces an infinite recursion, since also self.theObject = anObject tries to access the wrapped object. How can I avoid this? If the whole idea seems like a bad one, tell me too. A: Unless I'm missing something, this will work just fine: def __getattr__(self, name): return getattr(self.theObject, name) Edit: for those thinking that the lookup of self.theObject will result in an infinite recursive call to __getattr__, let me show you: >>> class Test: ... a = "a" ... def __init__(self): ... self.b = "b" ... def __getattr__(self, name): ... return 'Custom: %s' % name ... >>> Test.a 'a' >>> Test().a 'a' >>> Test().b 'b' >>> Test().c 'Custom: c' __getattr__ is only called as a last resort. Since theObject can be found in __dict__, no issues arise. A: But then of course I run into the problem that the constructor now produces an infinite recursion, since also self.theObject = anObject tries to access the wrapped object. That's why the manual suggests that you do this for all "real" attribute accesses. theobj = object.__getattribute__(self, "theObject") A: I'm glad to see others have been able to help you with the recursive call to __getattr__. Since you've asked for comments on the general approach of serializing to plist, I just wanted to chime in with a few thoughts. Python's plist implementation handles basic types only, and provides no extension mechanism for you to instruct it on serializing/deserializing complex types. If you define a custom class, for example, writePlist won't be able to help, as you've discovered since you're passing the instance's __dict__ for serialization. This has a couple implications: You won't be able to use this to serialize any objects that contain other objects of non-basic type without converting them to a __dict__, and so-on recursively for the entire network graph. If you roll your own network graph walker to serialize all non-basic objects that can be reached, you'll have to worry about circles in the graph where one object has another in a property, which in turn holds a reference back to the first, etc etc. Given then, you may wish to look at pickle instead as it can handle all of these and more. If you need the plist format for other reasons, and you're sure you can stick to "simple" object dicts, then you may wish to just use a simple function... trying to have the PlistObject mock every possible function in the contained object is an onion with potentially many layers as you need to handle all the possibilities of the wrapped instance. Something as simple as this may be more pythonic, and keep the usability of the wrapped object simpler by not wrapping it in the first place: def to_plist(obj, f_handle): writePlist(obj.__dict__, f_handle) I know that doesn't seem very sexy, but it is a lot more maintainable in my opinion than a wrapper given the severe limits of the plist format, and certainly better than artificially forcing all objects in your application to inherit from a common base class when there's nothing in your business domain that actually indicates those disparate objects are related.
Wrapping a Python Object
I'd like to serialize Python objects to and from the plist format (this can be done with plistlib). My idea was to write a class PlistObject which wraps other objects: def __init__(self, anObject): self.theObject = anObject and provides a "write" method: def write(self, pathOrFile): plistlib.writeToPlist(self.theObject.__dict__, pathOrFile) Now it would be nice if the PlistObject behaved just like wrapped object itself, meaning that all attributes and methods are somehow "forwarded" to the wrapped object. I realize that the methods __getattr__ and __setattr__ can be used for complex attribute operations: def __getattr__(self, name): return self.theObject.__getattr__(name) But then of course I run into the problem that the constructor now produces an infinite recursion, since also self.theObject = anObject tries to access the wrapped object. How can I avoid this? If the whole idea seems like a bad one, tell me too.
[ "Unless I'm missing something, this will work just fine:\ndef __getattr__(self, name):\n return getattr(self.theObject, name)\n\n\nEdit: for those thinking that the lookup of self.theObject will result in an infinite recursive call to __getattr__, let me show you:\n>>> class Test:\n... a = \"a\"\n... def __init__(self):\n... self.b = \"b\"\n... def __getattr__(self, name):\n... return 'Custom: %s' % name\n... \n>>> Test.a\n'a'\n>>> Test().a\n'a'\n>>> Test().b\n'b'\n>>> Test().c\n'Custom: c'\n\n__getattr__ is only called as a last resort. Since theObject can be found in __dict__, no issues arise.\n", "\nBut then of course I run into the problem that the constructor now produces an infinite recursion, since also self.theObject = anObject tries to access the wrapped object.\n\nThat's why the manual suggests that you do this for all \"real\" attribute accesses.\ntheobj = object.__getattribute__(self, \"theObject\")\n\n", "I'm glad to see others have been able to help you with the recursive call to __getattr__. Since you've asked for comments on the general approach of serializing to plist, I just wanted to chime in with a few thoughts.\nPython's plist implementation handles basic types only, and provides no extension mechanism for you to instruct it on serializing/deserializing complex types. If you define a custom class, for example, writePlist won't be able to help, as you've discovered since you're passing the instance's __dict__ for serialization.\nThis has a couple implications:\n\nYou won't be able to use this to serialize any objects that contain other objects of non-basic type without converting them to a __dict__, and so-on recursively for the entire network graph.\nIf you roll your own network graph walker to serialize all non-basic objects that can be reached, you'll have to worry about circles in the graph where one object has another in a property, which in turn holds a reference back to the first, etc etc.\n\nGiven then, you may wish to look at pickle instead as it can handle all of these and more. If you need the plist format for other reasons, and you're sure you can stick to \"simple\" object dicts, then you may wish to just use a simple function... trying to have the PlistObject mock every possible function in the contained object is an onion with potentially many layers as you need to handle all the possibilities of the wrapped instance.\nSomething as simple as this may be more pythonic, and keep the usability of the wrapped object simpler by not wrapping it in the first place:\ndef to_plist(obj, f_handle):\n writePlist(obj.__dict__, f_handle)\n\nI know that doesn't seem very sexy, but it is a lot more maintainable in my opinion than a wrapper given the severe limits of the plist format, and certainly better than artificially forcing all objects in your application to inherit from a common base class when there's nothing in your business domain that actually indicates those disparate objects are related.\n" ]
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000884594_python.txt
Q: Error when trying to migrate django application with south I am getting this error when running "./manage.py migrate app_name" While loading migration 'whatever.0001_initial': Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settings) ...tons of other stuff.. raise KeyError("The model '%s' from the app '%s' is not available in this migration." % (model, app)) KeyError: "The model 'appuser' from the app 'whatever' is not available in this migration." I am sure that model "appuser" is both in application models.py and in 0001_initial.py AppUser model from models.py: class AppUser(models.Model): person = models.OneToOneField('Person') user = models.ForeignKey(User, unique=True) class Meta: permissions = ( ('is_one', 'one'), ('is_two', 'two') ) def __unicode__(self): return self.person.__unicode__() AppUser model from 0001_initial.py: # Adding model 'AppUser' db.create_table('app_appuser', ( ('person', models.OneToOneField(orm.Person)), ('id', models.AutoField(primary_key=True)), ('user', models.ForeignKey(orm['auth.User'], unique=True)), )) db.send_create_signal('app', ['AppUser']) ... 'app.appuser': { 'Meta': {'permissions': "(('is_one','one'),('is_two','two'))"}, 'id': ('models.AutoField', [], {'primary_key': 'True'}), 'person': ('models.OneToOneField', ["'Person'"], {}), 'user': ('models.ForeignKey', ['User'], {'unique': 'True'}) }, I am trying to run it on empty database (ie. no "app_*" tables) like that: manage.py migrate app This seem to be happening only on python 2.5 on Mac OS, no probs with Ubuntu/python 2.6 Question - how to fix? Thanks! A: The problem seemed to be with the order of models in the 0001_initial.py file. There was a class which derived from AppUser. When I re-created the migration on Mac OS with manage.py startmigration app --initial and compared that to one generated on Ubuntu the order of models was different. So when I changed the order to match the one on Mac OS, everything worked fine. This problem seems to exist only in 0.5 version of south and is supposedly fixed on trunk.
Error when trying to migrate django application with south
I am getting this error when running "./manage.py migrate app_name" While loading migration 'whatever.0001_initial': Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settings) ...tons of other stuff.. raise KeyError("The model '%s' from the app '%s' is not available in this migration." % (model, app)) KeyError: "The model 'appuser' from the app 'whatever' is not available in this migration." I am sure that model "appuser" is both in application models.py and in 0001_initial.py AppUser model from models.py: class AppUser(models.Model): person = models.OneToOneField('Person') user = models.ForeignKey(User, unique=True) class Meta: permissions = ( ('is_one', 'one'), ('is_two', 'two') ) def __unicode__(self): return self.person.__unicode__() AppUser model from 0001_initial.py: # Adding model 'AppUser' db.create_table('app_appuser', ( ('person', models.OneToOneField(orm.Person)), ('id', models.AutoField(primary_key=True)), ('user', models.ForeignKey(orm['auth.User'], unique=True)), )) db.send_create_signal('app', ['AppUser']) ... 'app.appuser': { 'Meta': {'permissions': "(('is_one','one'),('is_two','two'))"}, 'id': ('models.AutoField', [], {'primary_key': 'True'}), 'person': ('models.OneToOneField', ["'Person'"], {}), 'user': ('models.ForeignKey', ['User'], {'unique': 'True'}) }, I am trying to run it on empty database (ie. no "app_*" tables) like that: manage.py migrate app This seem to be happening only on python 2.5 on Mac OS, no probs with Ubuntu/python 2.6 Question - how to fix? Thanks!
[ "The problem seemed to be with the order of models in the 0001_initial.py file. There was a class which derived from AppUser. When I re-created the migration on Mac OS with\nmanage.py startmigration app --initial\n\nand compared that to one generated on Ubuntu the order of models was different. So when I changed the order to match the one on Mac OS, everything worked fine.\nThis problem seems to exist only in 0.5 version of south and is supposedly fixed on trunk.\n" ]
[ 2 ]
[]
[]
[ "database", "django", "migration", "python" ]
stackoverflow_0000880989_database_django_migration_python.txt
Q: python orm This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conversion (if the app is live)? So, I start with a basic Phone app Object person: name, address, city, state, zip, phone and I change to Object person: title, name, address, city, state, zip, phone object Object phone: type, phone # Do I manually convert via the db and change the code OR does the ORM middleware make the change? and if so - how? A: As of Django 1.02 (and as of the latest run-up to 1.1 in subversion), there is no automatic "schema migration". Your choices are to drop the schema and have Django recreate it (via manage.py syncdb), or alter the schema by hand yourself. There are some tools on the horizon for Django schema migration. (I'm watching South.) A: The Django book covers this issue in Chapter 5, near the end of the chapter (or bottom of the page, in the web edition). Basically, the rules are: When adding a field, first add it to the database manually (using, e.g., ALTER TABLE) and then add the field to the model. (You can use manage.py sqlall to see what SQL statement to execute.) When removing a field, remove it from your model and then execute the appropriate SQL statement to remove the column (e.g., an ALTER TABLE command), and any join tables that were created. Renaming a field is basically a combination of adding/removing fields, as well as copying data. So to answer your question, in Django's case, no, the ORM will not handle modifications for you -- but they're not that hard to do. See that chapter of the book (linked above) for more info. A: We include a 'version' number in the application name. Our directories look like this project settings.py appA_1 __init__.py models.py tests.py appB_1 __init__.py models.py tests.py appB_2 __init__.py models.py tests.py This shows two versions of appB. appB_1 was the original version. When we changed the model, we started by copying the app to create appB_2, and then modified that one. A manage.py syncdb will create the fresh new appB_2. We have to unload and reload the tables by copying from appB_1 to appB_2. Once. Then we can remove appB_1 from the settings.py. Later we can delete the tables from the database.
python orm
This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conversion (if the app is live)? So, I start with a basic Phone app Object person: name, address, city, state, zip, phone and I change to Object person: title, name, address, city, state, zip, phone object Object phone: type, phone # Do I manually convert via the db and change the code OR does the ORM middleware make the change? and if so - how?
[ "As of Django 1.02 (and as of the latest run-up to 1.1 in subversion), there is no automatic \"schema migration\". Your choices are to drop the schema and have Django recreate it (via manage.py syncdb), or alter the schema by hand yourself.\nThere are some tools on the horizon for Django schema migration. (I'm watching South.)\n", "The Django book covers this issue in Chapter 5, near the end of the chapter (or bottom of the page, in the web edition). Basically, the rules are:\n\nWhen adding a field, first add it to the database manually (using, e.g., ALTER TABLE) and then add the field to the model. (You can use manage.py sqlall to see what SQL statement to execute.)\nWhen removing a field, remove it from your model and then execute the appropriate SQL statement to remove the column (e.g., an ALTER TABLE command), and any join tables that were created.\nRenaming a field is basically a combination of adding/removing fields, as well as copying data.\n\nSo to answer your question, in Django's case, no, the ORM will not handle modifications for you -- but they're not that hard to do. See that chapter of the book (linked above) for more info.\n", "We include a 'version' number in the application name.\nOur directories look like this\nproject\n settings.py\n appA_1\n __init__.py\n models.py\n tests.py\n appB_1 \n __init__.py\n models.py\n tests.py \n appB_2\n __init__.py\n models.py\n tests.py\n\nThis shows two versions of appB. appB_1 was the original version. When we changed the model, we started by copying the app to create appB_2, and then modified that one.\nA manage.py syncdb will create the fresh new appB_2. \nWe have to unload and reload the tables by copying from appB_1 to appB_2. Once.\nThen we can remove appB_1 from the settings.py. Later we can delete the tables from the database.\n" ]
[ 5, 4, 0 ]
[]
[]
[ "database", "django", "django_models", "python" ]
stackoverflow_0000885172_database_django_django_models_python.txt
Q: How does MySQL's RENAME TABLE statment work/perform? MySQL has a RENAME TABLE statemnt that will allow you to change the name of a table. The manual mentions The rename operation is done atomically, which means that no other session can access any of the tables while the rename is running The manual does not (to my knowedge) state how this renaming is accomplished. Is an entire copy of the table created, given a new name, and then the old table deleted? Or does MySQL do some magic behind the scenes to quickly rename the table? In other words, does the size of the table have an effect on how long the RENAME table statement will take to run. Are there other things that might cause the renaming of a block to significantly block? A: I believe MySQL only needs to alter metadata and references to the table's old name in stored procedures -- the number of records in the table should be irrelevant. A: In addition to altering the metadata, it also renames the associated .FRM file. While they can claim it being an "atomic" operation, this is an actual comment in the code for the mysql_rename_tables function... /* Lets hope this doesn't fail as the result will be messy */ =)
How does MySQL's RENAME TABLE statment work/perform?
MySQL has a RENAME TABLE statemnt that will allow you to change the name of a table. The manual mentions The rename operation is done atomically, which means that no other session can access any of the tables while the rename is running The manual does not (to my knowedge) state how this renaming is accomplished. Is an entire copy of the table created, given a new name, and then the old table deleted? Or does MySQL do some magic behind the scenes to quickly rename the table? In other words, does the size of the table have an effect on how long the RENAME table statement will take to run. Are there other things that might cause the renaming of a block to significantly block?
[ "I believe MySQL only needs to alter metadata and references to the table's old name in stored procedures -- the number of records in the table should be irrelevant.\n", "In addition to altering the metadata, it also renames the associated .FRM file. While they can claim it being an \"atomic\" operation, this is an actual comment in the code for the mysql_rename_tables function...\n/* Lets hope this doesn't fail as the result will be messy */\n\n=)\n" ]
[ 6, 1 ]
[]
[]
[ "migration", "mysql", "php", "python", "ruby" ]
stackoverflow_0000885771_migration_mysql_php_python_ruby.txt
Q: dnspython and python objects I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html: import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', rdata.preference In the python CLI, a dir(answers) gives me: ['__class__', '__delattr__', '__delitem__', '__delslice__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__iter__', '__len__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'expiration', 'qname', 'rdclass', 'rdtype', 'response', 'rrset'] Two things are confusing to me (which are related): Iteration over the answers object. What is rdata in the example? None of the attributes or methods of answers matches exchange or preference. Clearly rdata is not just a simple alias of answers, but I don't understand where those attributes are coming from. A: In the example code, answers is an iterable object containing zero or more items, which are each assigned to rdata in turn. To see the properties of the individual responses, try: dir(answers[0]) A: answers is an iterable as indicated by its "__iter__" method. Think of answers as a list of rdatas. You can try doing this to get 1 rdata from answers: answers.__iter__().next() A: I haven't looked at dns.resolver as of yet - I just added it to the ever-growing list of things to check out. I would guess that rdata refers to the resource record type specific data as described in Section 4.1.3 of RFC1035. The response of a DNS request contains three data sections in addition to the query and headers: Answers Authoritative Name Server records Additional Resource records From the looks of it dns.resolver.query() is returning the first section. In this case, each resource record in the answer section is going to have different attributes based on the record type. In this case, you asked for MX records so the records should have exactly the attributes that you have - exchange and preference. These are described in Section 3.3.9 of RFC1035. I suspect that dns.resolver is overriding __getattr__ or something similar to perform the magic that you are seeing so you won't see the fields directly in a dir(). Chances are that you are safe using the attributes as defined in RFC1035. I will definitely have to check this out tomorrow since I have need of a decent DNS subsystem for Python. Thanks for mentioning this module and have fun with DNS. It is really pretty interesting stuff if you really dig into how it works. I still think that it is one of the earlier expressions of that ReSTful thing that is all the rage these days ;) A: If you're on Python 2.6, the "proper" way to get the first item of any iterable (such as answers here) is next(iter(answers)); if you want to avoid an exception when answers is an empty iterable, then next(iter(answers), somevalue) will return somevalue instead of raising StopIteration. If you're on 2.5, then iter(answers).next(), but you'll have to use it inside a try/except StopIteration: statement if you need to deal with a possible empty iterable.
dnspython and python objects
I'm trying to use the dnspython library, and am a little confused by their example for querying MX records on this page: www.dnspython.org/examples.html: import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', rdata.preference In the python CLI, a dir(answers) gives me: ['__class__', '__delattr__', '__delitem__', '__delslice__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__iter__', '__len__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'expiration', 'qname', 'rdclass', 'rdtype', 'response', 'rrset'] Two things are confusing to me (which are related): Iteration over the answers object. What is rdata in the example? None of the attributes or methods of answers matches exchange or preference. Clearly rdata is not just a simple alias of answers, but I don't understand where those attributes are coming from.
[ "In the example code, answers is an iterable object containing zero or more items, which are each assigned to rdata in turn. To see the properties of the individual responses, try:\ndir(answers[0])\n\n", "answers is an iterable as indicated by its \"__iter__\" method. Think of answers as a list of rdatas.\nYou can try doing this to get 1 rdata from answers:\nanswers.__iter__().next()\n\n", "I haven't looked at dns.resolver as of yet - I just added it to the ever-growing list of things to check out. I would guess that rdata refers to the resource record type specific data as described in Section 4.1.3 of RFC1035. The response of a DNS request contains three data sections in addition to the query and headers:\n\nAnswers\nAuthoritative Name Server records\nAdditional Resource records\n\nFrom the looks of it dns.resolver.query() is returning the first section. In this case, each resource record in the answer section is going to have different attributes based on the record type. In this case, you asked for MX records so the records should have exactly the attributes that you have - exchange and preference. These are described in Section 3.3.9 of RFC1035.\nI suspect that dns.resolver is overriding __getattr__ or something similar to perform the magic that you are seeing so you won't see the fields directly in a dir(). Chances are that you are safe using the attributes as defined in RFC1035. I will definitely have to check this out tomorrow since I have need of a decent DNS subsystem for Python.\nThanks for mentioning this module and have fun with DNS. It is really pretty interesting stuff if you really dig into how it works. I still think that it is one of the earlier expressions of that ReSTful thing that is all the rage these days ;)\n", "If you're on Python 2.6, the \"proper\" way to get the first item of any iterable (such as answers here) is next(iter(answers)); if you want to avoid an exception when answers is an empty iterable, then next(iter(answers), somevalue) will return somevalue instead of raising StopIteration. If you're on 2.5, then iter(answers).next(), but you'll have to use it inside a try/except StopIteration: statement if you need to deal with a possible empty iterable.\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "dns", "dnspython", "python" ]
stackoverflow_0000885634_dns_dnspython_python.txt
Q: Can I use re.sub (or regexobject.sub) to replace text in a subgroup? I need to parse a configuration file which looks like this (simplified): <config> <links> <link name="Link1" id="1"> <encapsulation> <mode>ipsec</mode> </encapsulation> </link> <link name="Link2" id="2"> <encapsulation> <mode>udp</mode> </encapsulation> </link> </links> My goal is to be able to change parameters specific to a particular link, but I'm having trouble getting substitution to work correctly. I have a regex that can isolate a parameter value on a specific link, where the value is contained in capture group 1: link_id = r'id="1"' parameter = 'mode' link_regex = '<link [\w\W]+ %s>[\w\W]*[\w\W]*<%s>([\w\W]*)</%s>[\w\W]*</link>' \ % (link_id, parameter, parameter) Thus, print re.search(final_regex, f_read).group(1) prints ipsec The examples in the regex howto all seem to assume that one wants to use the capture group in the replacement, but what I need to do is replace the capture group itself (e.g. change the Link1 mode from ipsec to udp). A: I have to give you the obligatory: "don't use regular expressions to do this." Check out how very easily awesome it is to do this with BeautifulSoup, for example: >>> from BeautifulSoup import BeautifulStoneSoup >>> html = """ ... <config> ... <links> ... <link name="Link1" id="1"> ... <encapsulation> ... <mode>ipsec</mode> ... </encapsulation> ... </link> ... <link name="Link2" id="2"> ... <encapsulation> ... <mode>udp</mode> ... </encapsulation> ... </link> ... </links> ... </config> ... """ >>> soup = BeautifulStoneSoup(html) >>> soup.find('link', id=1) <link name="Link1" id="1"> <encapsulation> <mode>ipsec</mode> </encapsulation> </link> >>> soup.find('link', id=1).mode.contents[0].replaceWith('whatever') >>> soup.find('link', id=1) <link name="Link1" id="1"> <encapsulation> <mode>whatever</mode> </encapsulation> </link> Looking at your regular expression I can't really tell if this is exactly what you wanted to do, but whatever it is you want to do, using a library like BeautifulSoup is much, much, better than trying to patch a regular expression together. I highly recommend going this route if possible. A: This looks like valid XML, in that case you don't need BeautifulSoup, definitely not the regex, just load XML using any good XML library, edit it and print it out, here is a approach using ElementTree: import xml.etree.cElementTree as ET s = """<config> <links> <link name="Link1" id="1"> <encapsulation> <mode>ipsec</mode> </encapsulation> </link> <link name="Link2" id="2"> <encapsulation> <mode>udp</mode> </encapsulation> </link> </links> </config> """ configElement = ET.fromstring(s) for modeElement in configElement.findall("*/*/*/mode"): modeElement.text = "udp" print ET.tostring(configElement) It will change all mode elements to udp, this is the output: <config> <links> <link id="1" name="Link1"> <encapsulation> <mode>udp</mode> </encapsulation> </link> <link id="2" name="Link2"> <encapsulation> <mode>udp</mode> </encapsulation> </link> </links> </config> A: Supposing that your link_regex is correct, you can add parenthesis like this: (<link [\w\W]+ %s>[\w\W]*[\w\W]*<%s>)([\w\W]*)(</%s>[\w\W]*</link>) and then you could do: p = re.compile(link_regex) replacement = 'foo' print p.sub(r'\g<1>' + replacement + r'\g<3>' , f_read) A: not sure i'd do it that way, but the quickest way would be to shift the captures: ([\w\W][\w\W]<%s>)[\w\W]([\w\W])' and replace with group1 +mode+group2
Can I use re.sub (or regexobject.sub) to replace text in a subgroup?
I need to parse a configuration file which looks like this (simplified): <config> <links> <link name="Link1" id="1"> <encapsulation> <mode>ipsec</mode> </encapsulation> </link> <link name="Link2" id="2"> <encapsulation> <mode>udp</mode> </encapsulation> </link> </links> My goal is to be able to change parameters specific to a particular link, but I'm having trouble getting substitution to work correctly. I have a regex that can isolate a parameter value on a specific link, where the value is contained in capture group 1: link_id = r'id="1"' parameter = 'mode' link_regex = '<link [\w\W]+ %s>[\w\W]*[\w\W]*<%s>([\w\W]*)</%s>[\w\W]*</link>' \ % (link_id, parameter, parameter) Thus, print re.search(final_regex, f_read).group(1) prints ipsec The examples in the regex howto all seem to assume that one wants to use the capture group in the replacement, but what I need to do is replace the capture group itself (e.g. change the Link1 mode from ipsec to udp).
[ "I have to give you the obligatory: \"don't use regular expressions to do this.\"\nCheck out how very easily awesome it is to do this with BeautifulSoup, for example:\n>>> from BeautifulSoup import BeautifulStoneSoup\n>>> html = \"\"\"\n... <config>\n... <links>\n... <link name=\"Link1\" id=\"1\">\n... <encapsulation>\n... <mode>ipsec</mode>\n... </encapsulation>\n... </link>\n... <link name=\"Link2\" id=\"2\">\n... <encapsulation>\n... <mode>udp</mode>\n... </encapsulation>\n... </link>\n... </links>\n... </config>\n... \"\"\"\n>>> soup = BeautifulStoneSoup(html)\n>>> soup.find('link', id=1)\n<link name=\"Link1\" id=\"1\">\n<encapsulation>\n<mode>ipsec</mode>\n</encapsulation>\n</link>\n>>> soup.find('link', id=1).mode.contents[0].replaceWith('whatever')\n>>> soup.find('link', id=1)\n<link name=\"Link1\" id=\"1\">\n<encapsulation>\n<mode>whatever</mode>\n</encapsulation>\n</link>\n\nLooking at your regular expression I can't really tell if this is exactly what you wanted to do, but whatever it is you want to do, using a library like BeautifulSoup is much, much, better than trying to patch a regular expression together. I highly recommend going this route if possible.\n", "This looks like valid XML, in that case you don't need BeautifulSoup, definitely not the regex, just load XML using any good XML library, edit it and print it out, here is a approach using ElementTree:\nimport xml.etree.cElementTree as ET\n\ns = \"\"\"<config>\n<links>\n<link name=\"Link1\" id=\"1\">\n <encapsulation>\n <mode>ipsec</mode>\n </encapsulation>\n</link>\n<link name=\"Link2\" id=\"2\">\n <encapsulation>\n <mode>udp</mode>\n </encapsulation>\n</link>\n</links>\n</config>\n\"\"\"\nconfigElement = ET.fromstring(s)\n\nfor modeElement in configElement.findall(\"*/*/*/mode\"):\n modeElement.text = \"udp\"\n\nprint ET.tostring(configElement)\n\nIt will change all mode elements to udp, this is the output:\n<config>\n<links>\n<link id=\"1\" name=\"Link1\">\n <encapsulation>\n <mode>udp</mode>\n </encapsulation>\n</link>\n<link id=\"2\" name=\"Link2\">\n <encapsulation>\n <mode>udp</mode>\n </encapsulation>\n</link>\n</links>\n</config>\n\n", "Supposing that your link_regex is correct, you can add parenthesis like this:\n(<link [\\w\\W]+ %s>[\\w\\W]*[\\w\\W]*<%s>)([\\w\\W]*)(</%s>[\\w\\W]*</link>)\n\nand then you could do:\np = re.compile(link_regex)\nreplacement = 'foo'\nprint p.sub(r'\\g<1>' + replacement + r'\\g<3>' , f_read)\n\n", "not sure i'd do it that way, but the quickest way would be to shift the captures:\n([\\w\\W][\\w\\W]<%s>)[\\w\\W]([\\w\\W])' and replace with group1 +mode+group2\n" ]
[ 6, 2, 1, 0 ]
[]
[]
[ "python", "regex", "regex_group" ]
stackoverflow_0000886111_python_regex_regex_group.txt
Q: Django without shell access Is it possible to run django without shell access? My hoster supports the following for 5€/month: python (I assume via mod_python) mysql There is no shell nor cronjob support, which costs additional 10€/month, so I'm trying to avoid it. I know that Google Apps also work without shell access, but I assume that is possible because of their special configuration. A: It's possible but not desirable. Having shell access makes it possible to centralise things properly using symlinks. Get a better host would be my first suggestion. WebFaction is the most recommended shared host for using with Django. If that's out of your price range, there are plenty of hosts that give you a proper system account (vs just a ftp account) and have mod_python or mod_wsgi (preferred now). Google Apps works without shell because their system looks for a dispatcher script that you have to write to an exact specification. A: It is possible. Usually you will develop your application locally (where shell access is nice to have) and publish your work to your server. All you need for this is FTP access and some way to import a database dump from your development database (often hosters provide an installation of phpMyAdmin for this). python (I assume via mod_python) From my experience, you are most certainly wrong with that assumption. Many low-cost providers claim to support python but in fact provide only an outdated version that can be used with CGI scripts. This setup will have a pretty low performance for Django apps.
Django without shell access
Is it possible to run django without shell access? My hoster supports the following for 5€/month: python (I assume via mod_python) mysql There is no shell nor cronjob support, which costs additional 10€/month, so I'm trying to avoid it. I know that Google Apps also work without shell access, but I assume that is possible because of their special configuration.
[ "It's possible but not desirable. Having shell access makes it possible to centralise things properly using symlinks. \nGet a better host would be my first suggestion. WebFaction is the most recommended shared host for using with Django.\nIf that's out of your price range, there are plenty of hosts that give you a proper system account (vs just a ftp account) and have mod_python or mod_wsgi (preferred now).\nGoogle Apps works without shell because their system looks for a dispatcher script that you have to write to an exact specification.\n", "It is possible.\nUsually you will develop your application locally (where shell access is nice to have) and publish your work to your server. All you need for this is FTP access and some way to import a database dump from your development database (often hosters provide an installation of phpMyAdmin for this).\n\npython (I assume via mod_python)\n\nFrom my experience, you are most certainly wrong with that assumption. Many low-cost providers claim to support python but in fact provide only an outdated version that can be used with CGI scripts. This setup will have a pretty low performance for Django apps.\n" ]
[ 4, 1 ]
[]
[]
[ "django", "python", "shell" ]
stackoverflow_0000886526_django_python_shell.txt
Q: How to use counter in for loop python my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item in i: daily_user_status_list=[] print counter val_time1 = str_date_list[counter] val_time2 = str_date_list[counter + 1] counter =counter + 1 I am getting code error while doing counter = counter + 1. Basically, I need to different time from my str_date_list each time. but counter = counter +1 give me code error. Is there any other way of doing it? A: The counter is getting out of step with the sequences you're iterating over. But more than that, the counter is totally unnecessary. You've got several manual iterations of things that could be automated, and they're causing you to trip over. Especially, you hardly ever need to manually track a counter while iterating; Python's sequence types know how to iterate themselves. Here's my re-write of the intent of the above code (in the interactive interpreter to show it working): >>> dates = ["%(day)02d-05-09" % vars() for day in range(1, 31+1)] >>> date_ranges = zip(dates[:-1], dates[1:]) >>> for (date_begin, date_end) in date_ranges: ... print (date_begin, date_end) ... ('01-05-09', '02-05-09') ('02-05-09', '03-05-09') ('03-05-09', '04-05-09') … ('28-05-09', '29-05-09') ('29-05-09', '30-05-09') ('30-05-09', '31-05-09') A: Just for kicks, here's the super-compact Pythonic way to write this: from itertools import izip, islice str_date_list = ['%02d-05-09' % i for i in xrange(1, 32)] for val_time1, val_time2 in izip(islice(str_date_list, 0, None), islice(str_date_list, 1, None)): daily_user_status_list = [ <whatever goes here> ] # more code... A: The error you're seeing is because you're indexing out of range on the str_date_list list, not because you're incrementing the variable. Compare the largest value of counter that the loop prints (30) to the length of the list (len(str_date_list)). Since indexing starts at 0, the largest index into a list of length n is n - 1. A: You don't need to duplicate the loop iteration variable and the counter: my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') for i in xrange(len(my_date_list)-1): daily_user_status_list=[] print i val_time1 = str_date_list[i] val_time2 = str_date_list[i + 1] A: you do not need to create a iterator for going thru 0-31 you can use enumerate e.g. for i, sdate in enumerate(str_date_list): print i, sdate if you are using iter isn't item and counter same? A: counter += 1 but that isn't the problem. What's the error? Indentation error maybe? A: Better written: str_date_list=[] for n in xrange(1,32): str_date_list.append(str(n).zfill(2)+'-'+'05' + '-' +'09') for i in xrange(len(str_date_list)): daily_user_status_list=[] print i val_time1 = str_date_list[i] val_time2 = str_date_list[i + 1] xrange gives us a (quite performing) iterator over natural numbers given bounds. we use zfill to make sure there is a leading zero instead of writing them all explicitly it's important to avoid iterating out of the array bounds!
How to use counter in for loop python
my_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] str_date_list=[] for item in my_date_list: str_date_list.append(item+'-'+'05' + '-' +'09') counter= 0 i = iter(range(31)) for item in i: daily_user_status_list=[] print counter val_time1 = str_date_list[counter] val_time2 = str_date_list[counter + 1] counter =counter + 1 I am getting code error while doing counter = counter + 1. Basically, I need to different time from my str_date_list each time. but counter = counter +1 give me code error. Is there any other way of doing it?
[ "The counter is getting out of step with the sequences you're iterating over. But more than that, the counter is totally unnecessary.\nYou've got several manual iterations of things that could be automated, and they're causing you to trip over. Especially, you hardly ever need to manually track a counter while iterating; Python's sequence types know how to iterate themselves.\nHere's my re-write of the intent of the above code (in the interactive interpreter to show it working):\n>>> dates = [\"%(day)02d-05-09\" % vars() for day in range(1, 31+1)]\n>>> date_ranges = zip(dates[:-1], dates[1:])\n>>> for (date_begin, date_end) in date_ranges:\n... print (date_begin, date_end)\n... \n('01-05-09', '02-05-09')\n('02-05-09', '03-05-09')\n('03-05-09', '04-05-09')\n…\n('28-05-09', '29-05-09')\n('29-05-09', '30-05-09')\n('30-05-09', '31-05-09')\n\n", "Just for kicks, here's the super-compact Pythonic way to write this:\nfrom itertools import izip, islice\nstr_date_list = ['%02d-05-09' % i for i in xrange(1, 32)]\nfor val_time1, val_time2 in izip(islice(str_date_list, 0, None), islice(str_date_list, 1, None)):\n daily_user_status_list = [ <whatever goes here> ]\n # more code...\n\n", "The error you're seeing is because you're indexing out of range on the str_date_list list, not because you're incrementing the variable.\nCompare the largest value of counter that the loop prints (30) to the length of the list (len(str_date_list)). Since indexing starts at 0, the largest index into a list of length n is n - 1.\n", "You don't need to duplicate the loop iteration variable and the counter:\nmy_date_list = ['01', '02', '03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']\nstr_date_list=[]\nfor item in my_date_list:\n str_date_list.append(item+'-'+'05' + '-' +'09')\n\nfor i in xrange(len(my_date_list)-1):\n daily_user_status_list=[]\n print i\n val_time1 = str_date_list[i]\n val_time2 = str_date_list[i + 1]\n\n", "\nyou do not need to create a iterator for going thru 0-31\nyou can use enumerate e.g.\nfor i, sdate in enumerate(str_date_list):\n print i, sdate\nif you are using iter isn't item and counter same?\n\n", "counter += 1\nbut that isn't the problem. What's the error? Indentation error maybe?\n", "Better written:\nstr_date_list=[]\nfor n in xrange(1,32):\n str_date_list.append(str(n).zfill(2)+'-'+'05' + '-' +'09')\n\nfor i in xrange(len(str_date_list)):\n daily_user_status_list=[]\n print i\n val_time1 = str_date_list[i]\n val_time2 = str_date_list[i + 1]\n\n\nxrange gives us a (quite performing) iterator over natural numbers given bounds.\nwe use zfill to make sure there is a leading zero instead of writing them all explicitly\nit's important to avoid iterating out of the array bounds!\n\n" ]
[ 8, 4, 2, 2, 2, 1, 0 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0000886629_iterator_python.txt
Q: How to perform a query in django that selects all projects where I am a team member of? I have the concept of a team in my django app. class Team(models.Model): name = models.CharField(max_length=200) #snip team_members = models.ManyToManyField(User) I would like to fetch all teams the currently logged in user is member of. Something along the lines of Team.objects.all().filter(request.user.id__in = team_members.all()) This obvious doesn't work. Does anyone have some suggestions on how to do such query without going directly to sql? I did look at the django documentation of "in" queries, but I couldn't find my use case there. Many thanks! Nick. A: You don't need in here, Django handles that automatically in a ManyToMany lookup. Also, you need to understand that the database fields must always be on the left of the lookup, as they are actually handled as parameters to a function. What you actually want is very simple: Team.objects.filter(team_members=request.user) or request.user.team_set.all()
How to perform a query in django that selects all projects where I am a team member of?
I have the concept of a team in my django app. class Team(models.Model): name = models.CharField(max_length=200) #snip team_members = models.ManyToManyField(User) I would like to fetch all teams the currently logged in user is member of. Something along the lines of Team.objects.all().filter(request.user.id__in = team_members.all()) This obvious doesn't work. Does anyone have some suggestions on how to do such query without going directly to sql? I did look at the django documentation of "in" queries, but I couldn't find my use case there. Many thanks! Nick.
[ "You don't need in here, Django handles that automatically in a ManyToMany lookup.\nAlso, you need to understand that the database fields must always be on the left of the lookup, as they are actually handled as parameters to a function.\nWhat you actually want is very simple:\nTeam.objects.filter(team_members=request.user)\n\nor\nrequest.user.team_set.all()\n\n" ]
[ 4 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0000886624_django_pinax_python.txt
Q: Making a python cgi script to finish gracefully I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, the cgi script is silently killed on the server, and as a result no cleanup code gets executed. How can i force the script to always finish. A: You can trap the exit signal with the signal module. Haven't tried this with mod_python though. http://docs.python.org/library/signal.html Note in the docs: When a signal arrives during an I/O operation, it is possible that the I/O operation raises an exception after the signal handler returns. This is dependent on the underlying Unix system’s semantics regarding interrupted system calls. You may need to catch I/O exceptions for the broken pipe and/or file write if you don't sys.exit from your handler. A: The script is probably not killed silently; you just don't see the exception which python throws. I suggest to wrap the whole script in try-except and write any exception to a log file. This way, you can see what really happens. The logging module is your friend. A: You may be able to use the atexit module. http://docs.python.org/library/atexit.html From the documentation: The atexit module defines a single function to register cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination. Note: the functions registered via this module are not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called. This is an alternate interface to the functionality provided by the sys.exitfunc variable.
Making a python cgi script to finish gracefully
I have a python cgi script that accepts user uploads (via sys.stdin.read). After receiving the file (whether successfully or unsuccessfully), the script needs to do some cleanup. This works fine when upload finishes correctly, however if the user closes the client, the cgi script is silently killed on the server, and as a result no cleanup code gets executed. How can i force the script to always finish.
[ "You can trap the exit signal with the signal module. Haven't tried this with mod_python though.\nhttp://docs.python.org/library/signal.html\nNote in the docs:\n\nWhen a signal arrives during an I/O operation, it is possible that the I/O operation raises an exception after the signal handler returns. This is dependent on the underlying Unix system’s semantics regarding interrupted system calls.\n\nYou may need to catch I/O exceptions for the broken pipe and/or file write if you don't sys.exit from your handler.\n", "The script is probably not killed silently; you just don't see the exception which python throws. I suggest to wrap the whole script in try-except and write any exception to a log file.\nThis way, you can see what really happens. The logging module is your friend.\n", "You may be able to use the atexit module.\nhttp://docs.python.org/library/atexit.html\nFrom the documentation:\n\nThe atexit module defines a single function to register cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination.\nNote: the functions registered via this module are not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called.\nThis is an alternate interface to the functionality provided by the sys.exitfunc variable.\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000886653_cgi_python.txt
Q: Controlling bars width in matplotlib with per-month data When I plot data sampled per month with bars, their width is very thin. If I set X axis minor locator to DayLocator(), I can see the bars width is adjusted to 1 day, but I would like them to fill a whole month. I tried to set the minor ticks locator to MonthLocator() without effect. [edit] Maybe an example will be more explicit, here is an ipython -pylab example of what I mean : x = [datetime.datetime(2008, 1, 1, 0, 0), datetime.datetime(2008, 2, 1, 0, 0), datetime.datetime(2008, 3, 1, 0, 0), datetime.datetime(2008, 4, 1, 0, 0), datetime.datetime(2008, 5, 1, 0, 0), datetime.datetime(2008, 6, 1, 0, 0), datetime.datetime(2008, 7, 1, 0, 0), datetime.datetime(2008, 8, 1, 0, 0), datetime.datetime(2008, 9, 1, 0, 0), datetime.datetime(2008, 10, 1, 0, 0), datetime.datetime(2008, 11, 1, 0, 0), datetime.datetime(2008, 12, 1, 0, 0)] y = cos(numpy.arange(12) * 2) bar(x, y) This gives 12 2 pixels wide bars, I would like them to be wider and extend from month to month. A: Just use the width keyword argument: bar(x, y, width=30) Or, since different months have different numbers of days, to make it look good you can use a sequence: bar(x, y, width=[(x[j+1]-x[j]).days for j in range(len(x)-1)] + [30])
Controlling bars width in matplotlib with per-month data
When I plot data sampled per month with bars, their width is very thin. If I set X axis minor locator to DayLocator(), I can see the bars width is adjusted to 1 day, but I would like them to fill a whole month. I tried to set the minor ticks locator to MonthLocator() without effect. [edit] Maybe an example will be more explicit, here is an ipython -pylab example of what I mean : x = [datetime.datetime(2008, 1, 1, 0, 0), datetime.datetime(2008, 2, 1, 0, 0), datetime.datetime(2008, 3, 1, 0, 0), datetime.datetime(2008, 4, 1, 0, 0), datetime.datetime(2008, 5, 1, 0, 0), datetime.datetime(2008, 6, 1, 0, 0), datetime.datetime(2008, 7, 1, 0, 0), datetime.datetime(2008, 8, 1, 0, 0), datetime.datetime(2008, 9, 1, 0, 0), datetime.datetime(2008, 10, 1, 0, 0), datetime.datetime(2008, 11, 1, 0, 0), datetime.datetime(2008, 12, 1, 0, 0)] y = cos(numpy.arange(12) * 2) bar(x, y) This gives 12 2 pixels wide bars, I would like them to be wider and extend from month to month.
[ "Just use the width keyword argument:\nbar(x, y, width=30)\n\nOr, since different months have different numbers of days, to make it look good you can use a sequence:\nbar(x, y, width=[(x[j+1]-x[j]).days for j in range(len(x)-1)] + [30])\n\n" ]
[ 59 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0000886716_matplotlib_python.txt
Q: Make Emacs use UTF-8 with Python Interactive Mode When I start Python from Mac OS' Terminal.app, python recognises the encoding as UTF-8: $ python3.0 Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.encoding 'UTF-8' This works the same for python2.5. But inside Emacs, the encoding is US-ASCII. Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.encoding 'US-ASCII' How do I make Emacs communicate with Python so that sys.stdout knows to use UTF-8? Edit: Since I don't have the rep to edit the accepted answer, here is precisely what worked for me on Aquaemacs 1.6, Mac OS 10.5.6. In the python-mode-hook, I added the line (setenv "LANG" "en_GB.UTF-8") Apparently, Mac OS requires "UTF-8", while dfa says that Ubuntu requires "UTF8". Additionally, I had to set the input/output encoding by doing C-x RET p and then typing "utf-8" twice. I should probably find out how to set this permanently. Thanks to dfa and Jouni for collectively helping me find the answer. Here is my final python-mode-hook: (add-hook 'python-mode-hook (lambda () (set (make-variable-buffer-local 'beginning-of-defun-function) 'py-beginning-of-def-or-class) (define-key py-mode-map "\C-c\C-z" 'py-shell) (setq outline-regexp "def\\|class ") (setenv "LANG" "en_GB.UTF-8"))) ; <-- *this* line is new A: check your environment variables: $ LANG="en_US.UTF8" python -c "import sys; print sys.stdout.encoding" UTF-8 $ LANG="en_US" python -c "import sys; print sys.stdout.encoding" ANSI_X3.4-1968 in your python hook, try: (setenv "LANG" "en_US.UTF8")
Make Emacs use UTF-8 with Python Interactive Mode
When I start Python from Mac OS' Terminal.app, python recognises the encoding as UTF-8: $ python3.0 Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.encoding 'UTF-8' This works the same for python2.5. But inside Emacs, the encoding is US-ASCII. Python 3.0.1 (r301:69556, May 18 2009, 16:44:01) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.encoding 'US-ASCII' How do I make Emacs communicate with Python so that sys.stdout knows to use UTF-8? Edit: Since I don't have the rep to edit the accepted answer, here is precisely what worked for me on Aquaemacs 1.6, Mac OS 10.5.6. In the python-mode-hook, I added the line (setenv "LANG" "en_GB.UTF-8") Apparently, Mac OS requires "UTF-8", while dfa says that Ubuntu requires "UTF8". Additionally, I had to set the input/output encoding by doing C-x RET p and then typing "utf-8" twice. I should probably find out how to set this permanently. Thanks to dfa and Jouni for collectively helping me find the answer. Here is my final python-mode-hook: (add-hook 'python-mode-hook (lambda () (set (make-variable-buffer-local 'beginning-of-defun-function) 'py-beginning-of-def-or-class) (define-key py-mode-map "\C-c\C-z" 'py-shell) (setq outline-regexp "def\\|class ") (setenv "LANG" "en_GB.UTF-8"))) ; <-- *this* line is new
[ "check your environment variables:\n$ LANG=\"en_US.UTF8\" python -c \"import sys; print sys.stdout.encoding\"\nUTF-8\n$ LANG=\"en_US\" python -c \"import sys; print sys.stdout.encoding\" \nANSI_X3.4-1968\n\nin your python hook, try:\n(setenv \"LANG\" \"en_US.UTF8\")\n\n" ]
[ 7 ]
[]
[]
[ "emacs", "encoding", "python", "terminal", "utf_8" ]
stackoverflow_0000888406_emacs_encoding_python_terminal_utf_8.txt
Q: Problem using py2app with the lxml package I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' installed. My Setup.py looks like this: from setuptools import setup OPTIONS = {'argv_emulation': True, 'packages' : ['lxml']} setup(app=[MyApp.py], data_files=[], options={'py2app' : OPTIONS}, setup_requires=['py2app']) Running the application produces the following output: MyApp Error An unexpected error has occurred during execution of the main script ImportError: dlopen(/Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so, 2): Symbol not found: _xmlSchematronParse Referenced from: /Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so Expected in: dynamic lookup The symbol '_xmlSchematronParse' is from a library called 'libxml2' that 'lxml' depends on. The version that comes preinstalled with Mac OS X isn't up to date enough for 'lxml', so I had to install version 2.7.2 (in /usr/local). py2app, for some reason, is linking in the version in /Developer/SDKs/MacOSX10.3.9.sdk/usr/lib. When I run my application as a Python script though, the correct version is found. (I checked this just now by hiding the 2.7.2 version.) So my question now is, how can I tell py2app where to look for libraries? A: Found it. py2app has a 'frameworks' option to let you specify frameworks, and also dylibs. My setup.py file now looks like this: from setuptools import setup DATA_FILES = [] OPTIONS = {'argv_emulation': True, 'packages' : ['lxml'], 'frameworks' : ['/usr/local/libxml2-2.7.2/lib/libxml2.2.7.2.dylib'] } setup(app=MyApp.py, data_files=DATA_FILES, options={'py2app' : OPTIONS}, setup_requires=['py2app']) and that's fixed it. Thanks for the suggestions that led me here. A: ------------- Edit-------------- libxml2 is standard in the python.org version of Python. It is not standard in Apple's version of Python. Make sure py2app is using the right version of Python, or install libxml2 and libxslt on your Mac. A: I have no experience with the combination of lxml and py2app specifically, but I've had issues with py2app not picking up modules that were not explicitly imported. For example, I had to explicitly include modules that are imported via __import__(), like this: OPTIONS['includes'] = [filename[:-3].replace('/', '.') for filename \ in glob.glob('path/to/*.py')] Maybe it also helps in your case to insert an explicit from lxml import etree somewhere in your code? A: I just tried my app (uses py2app and lxml, with a similar setup) on another Mac without development libraries installed, and it works, so there must be something wrong in your system. My guess is that py2app picks the wrong version of libxml2 (I see it comes bundled with the iPhone SDK for example, which is probably not the version you want). Mine, as the whole python toolchain, comes from MacPorts, md5 sum of the latest libxml2.2.dylib (the one that ends up in my .app) is 863c7208b6c34f116a2925444933c22a on my system.
Problem using py2app with the lxml package
I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' installed. My Setup.py looks like this: from setuptools import setup OPTIONS = {'argv_emulation': True, 'packages' : ['lxml']} setup(app=[MyApp.py], data_files=[], options={'py2app' : OPTIONS}, setup_requires=['py2app']) Running the application produces the following output: MyApp Error An unexpected error has occurred during execution of the main script ImportError: dlopen(/Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so, 2): Symbol not found: _xmlSchematronParse Referenced from: /Users/ake/XXXX/XXXX/MyApp.app/Contents/Resources/lib/python2.5/lxml/etree.so Expected in: dynamic lookup The symbol '_xmlSchematronParse' is from a library called 'libxml2' that 'lxml' depends on. The version that comes preinstalled with Mac OS X isn't up to date enough for 'lxml', so I had to install version 2.7.2 (in /usr/local). py2app, for some reason, is linking in the version in /Developer/SDKs/MacOSX10.3.9.sdk/usr/lib. When I run my application as a Python script though, the correct version is found. (I checked this just now by hiding the 2.7.2 version.) So my question now is, how can I tell py2app where to look for libraries?
[ "Found it. py2app has a 'frameworks' option to let you specify frameworks, and also dylibs. My setup.py file now looks like this:\nfrom setuptools import setup\n\nDATA_FILES = []\nOPTIONS = {'argv_emulation': True,\n 'packages' : ['lxml'],\n 'frameworks' : ['/usr/local/libxml2-2.7.2/lib/libxml2.2.7.2.dylib']\n }\n\nsetup(app=MyApp.py,\n data_files=DATA_FILES,\n options={'py2app' : OPTIONS},\n setup_requires=['py2app'])\n\nand that's fixed it.\nThanks for the suggestions that led me here.\n", "------------- Edit--------------\nlibxml2 is standard in the python.org version of Python. It is not standard in Apple's version of Python. Make sure py2app is using the right version of Python, or install libxml2 and libxslt on your Mac.\n", "I have no experience with the combination of lxml and py2app specifically, but I've had issues with py2app not picking up modules that were not explicitly imported. For example, I had to explicitly include modules that are imported via __import__(), like this:\nOPTIONS['includes'] = [filename[:-3].replace('/', '.') for filename \\\n in glob.glob('path/to/*.py')]\n\nMaybe it also helps in your case to insert an explicit from lxml import etree somewhere in your code?\n", "I just tried my app (uses py2app and lxml, with a similar setup) on another Mac without development libraries installed, and it works, so there must be something wrong in your system. My guess is that py2app picks the wrong version of libxml2 (I see it comes bundled with the iPhone SDK for example, which is probably not the version you want).\nMine, as the whole python toolchain, comes from MacPorts, md5 sum of the latest libxml2.2.dylib (the one that ends up in my .app) is 863c7208b6c34f116a2925444933c22a on my system.\n" ]
[ 14, 1, 1, 1 ]
[]
[]
[ "lxml", "py2app", "python" ]
stackoverflow_0000868510_lxml_py2app_python.txt
Q: ManyToOneField in Django I'm trying to define a many-to-one field in the class that is the "Many". For example, imagine a situation where a user can only be a member of one group but a group can have many users: class User(models.Model): name = models.CharField() class Group(models.Model): name = models.CharField() # This is what I want to do -> users = models.ManyToOneField(User) Django docs will tell to define a group field in the User model as a ForeignKey, but I need to define the relationship in the Group model. As far as I know, there isn't a ManyToOneField and I would rather not have to use a ManyToManyField. A: A ManyToOne field, as you've guessed, is called ForeignKey in Django. You will have to define it on your User class for the logic to work properly, but Django will make a reverse property available on the Groups model automatically: class Group(models.Model): name = models.CharField(max_length=64) class User(models.Model): name = models.CharField(max_length=64) group = models.ForeignKey(Group) g = Group.objects.get(id=1) print g.user_set.all() # prints list of all users in the group Remember that Django's models sit on top of a relational database... there's no way to define a single FK field in a table that points to more than one foreign key (without a M2M, that is), so putting the ManyToOne relationship on the Groups object doesn't map to the underlying data store. If you were writing raw SQL, you'd model this relationship with a foreign key from the user table to the group table in any event, if it helps to think of it that way. The syntax and logic of using a ManyToOne property that is defined on a Group instance, if such a concept existed, would be much less straightforward than the ForeignKey defined on User. A: Assuming that the Users construct is the built-in authentication system... I would recommend creating a Profile model of some sort and attaching the OneToMany field to it instead. You can then hook the Profile model to the user model. A: You should probably be looking at simply using built in reverse lookups: group = Group.objects.get(id=1) users_in_group = group.user_set.all() Reverse lookup sets are automatically created for any foreign keys or many-to-many relationships to the model in question. If you want to refer to this with a friendlier name, or provide additional filtering before returning, you can always wrap the call in a method: class Group(models.Model): name = models.CharField(max_length=64) def users(self): return self.user_set.all() Either can be called from the templates: {{ group.user_set.all }} {{ group.users }}
ManyToOneField in Django
I'm trying to define a many-to-one field in the class that is the "Many". For example, imagine a situation where a user can only be a member of one group but a group can have many users: class User(models.Model): name = models.CharField() class Group(models.Model): name = models.CharField() # This is what I want to do -> users = models.ManyToOneField(User) Django docs will tell to define a group field in the User model as a ForeignKey, but I need to define the relationship in the Group model. As far as I know, there isn't a ManyToOneField and I would rather not have to use a ManyToManyField.
[ "A ManyToOne field, as you've guessed, is called ForeignKey in Django. You will have to define it on your User class for the logic to work properly, but Django will make a reverse property available on the Groups model automatically:\nclass Group(models.Model):\n name = models.CharField(max_length=64)\n\nclass User(models.Model):\n name = models.CharField(max_length=64)\n group = models.ForeignKey(Group)\n\ng = Group.objects.get(id=1)\nprint g.user_set.all() # prints list of all users in the group\n\nRemember that Django's models sit on top of a relational database... there's no way to define a single FK field in a table that points to more than one foreign key (without a M2M, that is), so putting the ManyToOne relationship on the Groups object doesn't map to the underlying data store. If you were writing raw SQL, you'd model this relationship with a foreign key from the user table to the group table in any event, if it helps to think of it that way. The syntax and logic of using a ManyToOne property that is defined on a Group instance, if such a concept existed, would be much less straightforward than the ForeignKey defined on User.\n", "Assuming that the Users construct is the built-in authentication system... I would recommend creating a Profile model of some sort and attaching the OneToMany field to it instead. You can then hook the Profile model to the user model.\n", "You should probably be looking at simply using built in reverse lookups:\ngroup = Group.objects.get(id=1)\nusers_in_group = group.user_set.all()\n\nReverse lookup sets are automatically created for any foreign keys or many-to-many relationships to the model in question.\nIf you want to refer to this with a friendlier name, or provide additional filtering before returning, you can always wrap the call in a method:\nclass Group(models.Model):\n name = models.CharField(max_length=64)\n\n def users(self):\n return self.user_set.all()\n\nEither can be called from the templates:\n{{ group.user_set.all }}\n\n{{ group.users }}\n\n" ]
[ 10, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000888550_django_python.txt
Q: Function Decorators I like being able to measure performance of the python functions I code, so very often I do something similar to this... import time def some_function(arg1, arg2, ..., argN, verbose = True) : t = time.clock() # works best in Windows # t = time.time() # apparently works better in Linux # Function code goes here t = time.clock() - t if verbose : print "some_function executed in",t,"sec." return return_val Yes, I know you are supposed to measure performance with timeit, but this works just fine for my needs, and allows me to turn this information on and off for debugging very smoothly. That code of course was from before I knew about function decorators... Not that I know much about them now, but I think I could write a decorator that did the following, using the **kwds dictionary: some_function(arg1, arg2, ..., argN) # Does not time function some_function(arg1, arg2, ..., argN, verbose = True) # Times function I would nevertheless like to duplicate the prior working of my functions, so that the working would be something more like: some_function(arg1, arg2, ..., argN) # Does not time function some_function(arg1, arg2, ..., argN, False) # Does not time function some_function(arg1, arg2, ..., argN, True) # Times function I guess this would require the decorator to count the number of arguments, know how many the original function will take, strip any in excess, pass the right number of them to the function... I'm uncertain though on how to tell python to do this... Is it possible? Is there a better way of achieving the same? A: Though inspect may get you a bit on the way, what you want is in general not possible: def f(*args): pass Now how many arguments does f take? Since *args and **kwargs allow for an arbitrary number of arguments, there is no way to determine the number of arguments a function requires. In fact there are cases where the function really handles as many as there are thrown at it! Edit: if you're willing to put up with verbose as a special keyword argument, you can do this: import time def timed(f): def dec(*args, **kwargs): verbose = kwargs.pop('verbose', False) t = time.clock() ret = f(*args, **kwargs) if verbose: print("%s executed in %ds" % (f.__name__, time.clock() - t)) return ret return dec @timed def add(a, b): return a + b print(add(2, 2, verbose=True)) (Thanks Alex Martelli for the kwargs.pop tip!) A: +1 on Stephan202's answer, however (putting this in a separate answer since comments don't format code well!), the following bit of code in that answer: verbose = False if 'verbose' in kwargs: verbose = True del kwargs['verbose'] can be expressed much more clearly and concisely as: verbose = kwargs.pop('verbose', False) A: it might be difficult but you can do something on these lines. Code below tries to remove any extra arguments and prints them out. def mydeco(func): def wrap(*args, **kwargs): """ we want to eat any extra argument, so just count args and kwargs and if more(>func.func_code.co_argcount) first take it out from kwargs based on func.func_code.co_varnames, else last one from args """ extraArgs = [] newKwargs = {} for name, value in kwargs.iteritems(): if name in func.func_code.co_varnames: newKwargs[name] = value else: extraArgs.append(kwargs[name]) diff = len(args) + len(newKwargs) - func.func_code.co_argcount if diff: extraArgs.extend(args[-diff:]) args = args[:-diff] func(*args, **newKwargs) print "%s has extra args=%s"%(func.func_name, extraArgs) return wrap @mydeco def func1(a, b, c=3): pass func1(1,b=2,c=3, d="x") func1(1,2,3,"y") output is func1 has extra args=['x'] func1 has extra args=['y']
Function Decorators
I like being able to measure performance of the python functions I code, so very often I do something similar to this... import time def some_function(arg1, arg2, ..., argN, verbose = True) : t = time.clock() # works best in Windows # t = time.time() # apparently works better in Linux # Function code goes here t = time.clock() - t if verbose : print "some_function executed in",t,"sec." return return_val Yes, I know you are supposed to measure performance with timeit, but this works just fine for my needs, and allows me to turn this information on and off for debugging very smoothly. That code of course was from before I knew about function decorators... Not that I know much about them now, but I think I could write a decorator that did the following, using the **kwds dictionary: some_function(arg1, arg2, ..., argN) # Does not time function some_function(arg1, arg2, ..., argN, verbose = True) # Times function I would nevertheless like to duplicate the prior working of my functions, so that the working would be something more like: some_function(arg1, arg2, ..., argN) # Does not time function some_function(arg1, arg2, ..., argN, False) # Does not time function some_function(arg1, arg2, ..., argN, True) # Times function I guess this would require the decorator to count the number of arguments, know how many the original function will take, strip any in excess, pass the right number of them to the function... I'm uncertain though on how to tell python to do this... Is it possible? Is there a better way of achieving the same?
[ "Though inspect may get you a bit on the way, what you want is in general not possible:\ndef f(*args):\n pass\n\nNow how many arguments does f take? Since *args and **kwargs allow for an arbitrary number of arguments, there is no way to determine the number of arguments a function requires. In fact there are cases where the function really handles as many as there are thrown at it!\n\nEdit: if you're willing to put up with verbose as a special keyword argument, you can do this:\nimport time\n\ndef timed(f):\n def dec(*args, **kwargs):\n verbose = kwargs.pop('verbose', False)\n t = time.clock()\n\n ret = f(*args, **kwargs)\n\n if verbose:\n print(\"%s executed in %ds\" % (f.__name__, time.clock() - t))\n\n return ret\n\n return dec\n\n@timed\ndef add(a, b):\n return a + b\n\nprint(add(2, 2, verbose=True))\n\n(Thanks Alex Martelli for the kwargs.pop tip!)\n", "+1 on Stephan202's answer, however (putting this in a separate answer since comments don't format code well!), the following bit of code in that answer:\nverbose = False\nif 'verbose' in kwargs:\n verbose = True\n del kwargs['verbose']\n\ncan be expressed much more clearly and concisely as:\nverbose = kwargs.pop('verbose', False)\n\n", "it might be difficult but you can do something on these lines. Code below tries to remove any extra arguments and prints them out.\ndef mydeco(func):\n def wrap(*args, **kwargs):\n \"\"\"\n we want to eat any extra argument, so just count args and kwargs\n and if more(>func.func_code.co_argcount) first take it out from kwargs \n based on func.func_code.co_varnames, else last one from args\n \"\"\"\n extraArgs = []\n\n newKwargs = {}\n for name, value in kwargs.iteritems():\n if name in func.func_code.co_varnames:\n newKwargs[name] = value\n else:\n extraArgs.append(kwargs[name])\n\n diff = len(args) + len(newKwargs) - func.func_code.co_argcount\n if diff:\n extraArgs.extend(args[-diff:])\n args = args[:-diff]\n\n func(*args, **newKwargs)\n print \"%s has extra args=%s\"%(func.func_name, extraArgs)\n\n return wrap\n\n@mydeco\ndef func1(a, b, c=3):\n pass\n\nfunc1(1,b=2,c=3, d=\"x\")\nfunc1(1,2,3,\"y\")\n\noutput is\nfunc1 has extra args=['x']\nfunc1 has extra args=['y']\n\n" ]
[ 9, 8, 0 ]
[]
[]
[ "argument_passing", "decorator", "python" ]
stackoverflow_0000889088_argument_passing_decorator_python.txt
Q: How can I read()/write() against a python HTTPConnection? I've got python code of the form: (o,i) = os.popen2 ("/usr/bin/ssh host executable") ios = IOSource(i,o) Library code then uses this IOSource, doing writes() and read()s against inputstream i and outputstream o. Yes, there is IPC going on here.. Think RPC. I want to do this, but in an HTTP fashion rather than spawning an ssh. I've done python http before with: conn=httplib.HTTPConnection('localhost',8000) conn.connect() conn.request('POST','/someurl/') response=conn.getresponse() How do I get the inputstream/outputstream from the HTTPConnection so that my lib code can read from/write to just like the ssh example above? A: for output: output = response.read() http://docs.python.org/library/httplib.html#httpresponse-objects for input: pass your data in the POST body of your request
How can I read()/write() against a python HTTPConnection?
I've got python code of the form: (o,i) = os.popen2 ("/usr/bin/ssh host executable") ios = IOSource(i,o) Library code then uses this IOSource, doing writes() and read()s against inputstream i and outputstream o. Yes, there is IPC going on here.. Think RPC. I want to do this, but in an HTTP fashion rather than spawning an ssh. I've done python http before with: conn=httplib.HTTPConnection('localhost',8000) conn.connect() conn.request('POST','/someurl/') response=conn.getresponse() How do I get the inputstream/outputstream from the HTTPConnection so that my lib code can read from/write to just like the ssh example above?
[ "for output:\noutput = response.read()\n\nhttp://docs.python.org/library/httplib.html#httpresponse-objects\nfor input:\npass your data in the POST body of your request\n" ]
[ 1 ]
[]
[]
[ "http", "python", "rpc" ]
stackoverflow_0000889528_http_python_rpc.txt
Q: Dividing in an if statement In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement. a = range(20) for i in a: if i / 3 == True: print i A: Yes, but. Please, please, please. Never say if some expression == True. It's redundant and causes many people to wonder what you're thinking. More importantly. i/3 is the quotient. i%3 is the remainder. If i is a multiple of 3, i%3 == 0. A: Everyone here has done a good job explaining how to do it right. I just want to explain what you are doing wrong. if i / 3 == True Is equivalent to: if i / 3 == 1 Because True == 1. So you are basicly checking if i when divided by 3 equals 1. Your code will actually print 3 4 5. I think what you wanted to do is to check if i is a multiple of 3. Like this: if i % 3 == 0 You can of course use an if statement to do it. Or you can use list comprehension with if [x for x in range(20) if x % 3 == 0] To those how are down voting this, from python documentation: Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. A: At the command prompt: >>> [i for i in range(20) if i%3 == 0] >>> [0, 3, 6, 9, 12, 15, 18] OR >>> a = [i for i in range(20) if i%3 == 0] >>> print a [0, 3, 6, 9, 12, 15, 18] >>> A: Hmm seems you want a weird thing - you divide i by 3 and check if it is equal to 1. As 4 == True => False. A: Short answer: no. You cannot make assignments in if statements in python. But really, I don't understand what you are trying to do here. Your sample code will only print out the numbers 3, 4, and 5 because every other value of i divided by 3 evaluates to something other than 1 (and therefore false). If you want to divide everything in a list by 3, you want map(lambda x: x / 3, range(20)). if you want decimal answers, map(lambda x : x / 3.0, range(20)). These will return a new list where each element is a the number in the original list divided by three. A: While working on Project Euler myself, I found "if not x % y" to be the cleanest way to represent "if x is a multiple of y". This is equivalent to "if x % y == 0", seen in other answers. I don't believe there is a significant difference between the two; which you use is simply a matter of personal preference.
Dividing in an if statement
In Python, if I had a range, and I wanted to iterate over it and divide each number by another number, could I do that in a if statement. a = range(20) for i in a: if i / 3 == True: print i
[ "Yes, but.\nPlease, please, please. Never say if some expression == True. It's redundant and causes many people to wonder what you're thinking.\nMore importantly. \ni/3 is the quotient.\ni%3 is the remainder. If i is a multiple of 3, i%3 == 0.\n", "Everyone here has done a good job explaining how to do it right. I just want to explain what you are doing wrong.\nif i / 3 == True\n\nIs equivalent to:\nif i / 3 == 1\n\nBecause True == 1. So you are basicly checking if i when divided by 3 equals 1. Your code will actually print 3 4 5.\nI think what you wanted to do is to check if i is a multiple of 3. Like this:\nif i % 3 == 0\n\nYou can of course use an if statement to do it. Or you can use list comprehension with if\n[x for x in range(20) if x % 3 == 0]\n\n\nTo those how are down voting this, from python documentation:\nBoolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively.\n", "At the command prompt:\n>>> [i for i in range(20) if i%3 == 0]\n>>> [0, 3, 6, 9, 12, 15, 18]\n\nOR\n>>> a = [i for i in range(20) if i%3 == 0]\n>>> print a\n[0, 3, 6, 9, 12, 15, 18]\n>>>\n\n", "Hmm seems you want a weird thing - you divide i by 3 and check if it is equal to 1.\nAs 4 == True => False.\n", "Short answer: no. You cannot make assignments in if statements in python.\nBut really, I don't understand what you are trying to do here. Your sample code will only print out the numbers 3, 4, and 5 because every other value of i divided by 3 evaluates to something other than 1 (and therefore false).\nIf you want to divide everything in a list by 3, you want map(lambda x: x / 3, range(20)). if you want decimal answers, map(lambda x : x / 3.0, range(20)). These will return a new list where each element is a the number in the original list divided by three.\n", "While working on Project Euler myself, I found \"if not x % y\" to be the cleanest way to represent \"if x is a multiple of y\". This is equivalent to \"if x % y == 0\", seen in other answers. I don't believe there is a significant difference between the two; which you use is simply a matter of personal preference.\n" ]
[ 7, 3, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000889446_python.txt
Q: Closing and Opening Frames in wxPython I'm working on writing a very simple client/server application as an excuse to start learning network/gui programming in python. At the moment I'm stuck on transitioning from my login frame to the main frame of the application. The login frame is a subclass of wx.Frame, and basically I just want to close it and open the main frame when it receives confirmation from the server: def handleServerSignon(self, msg): if msg.getCode() == net.message.HANDLE_IN_USE: self.status.SetStatusText('Handle already in use') elif msg.getCode() == net.message.SIGNON_SUCCESSFUL: self.Close() mainWindow = wx.Frame(None, wx.ID_ANY, 'main window', wx.DefaultPosition, \ (640, 480)) mainWindow.Show(True) I can't even get this to give a consistent error message though... sometimes it works, sometimes it crashes with the following: python: ../../src/xcb_io.c:242: process_responses: Assertion `(((long) (dpy->last_request_read) - (long) (dpy->request)) <= 0)' failed. Any help is very much appreciated! Walker A: I would make your main frame appear, then show a modal login dialog over top instead. If you don't want to do that, I suggest you create two separate Frames and have your application listen for a close event on the login frame. Handle the login in that event handler, then have it show the main window. Basically, you don't want to be instantiating the main window in your event handler since once you leave the function, scope is lost the the garbage collector will try to remove your frame. Lastly, you should consider calling getCode() once and caching the result for your comparisons. Since your if statement and elif statement both call getCode() it very well may be yielding different results. A: mainWindow is a local variable of handleServerSignon. This is a guess, but I think it may be garbage collected as soon as the handleServerSignon method returns.
Closing and Opening Frames in wxPython
I'm working on writing a very simple client/server application as an excuse to start learning network/gui programming in python. At the moment I'm stuck on transitioning from my login frame to the main frame of the application. The login frame is a subclass of wx.Frame, and basically I just want to close it and open the main frame when it receives confirmation from the server: def handleServerSignon(self, msg): if msg.getCode() == net.message.HANDLE_IN_USE: self.status.SetStatusText('Handle already in use') elif msg.getCode() == net.message.SIGNON_SUCCESSFUL: self.Close() mainWindow = wx.Frame(None, wx.ID_ANY, 'main window', wx.DefaultPosition, \ (640, 480)) mainWindow.Show(True) I can't even get this to give a consistent error message though... sometimes it works, sometimes it crashes with the following: python: ../../src/xcb_io.c:242: process_responses: Assertion `(((long) (dpy->last_request_read) - (long) (dpy->request)) <= 0)' failed. Any help is very much appreciated! Walker
[ "I would make your main frame appear, then show a modal login dialog over top instead.\nIf you don't want to do that, I suggest you create two separate Frames and have your application listen for a close event on the login frame. Handle the login in that event handler, then have it show the main window. Basically, you don't want to be instantiating the main window in your event handler since once you leave the function, scope is lost the the garbage collector will try to remove your frame.\nLastly, you should consider calling getCode() once and caching the result for your comparisons. Since your if statement and elif statement both call getCode() it very well may be yielding different results.\n", "mainWindow is a local variable of handleServerSignon. This is a guess, but I think it may be garbage collected as soon as the handleServerSignon method returns.\n" ]
[ 2, 0 ]
[]
[]
[ "network_programming", "python", "user_interface", "wxpython" ]
stackoverflow_0000885453_network_programming_python_user_interface_wxpython.txt
Q: No reverse error in Google App Engine Django patch? I am using Google App Engine patch Django. When I try to go to the admin site, http://127.0.0.1:8080/admin/ , I keep getting this error: TemplateSyntaxError at /admin/ Caught an exception while rendering: Reverse for 'settings.django.contrib.auth.views.logout' with arguments '()' and keyword arguments '{}' not found. It's a fresh installation and I have not changed much. But I am not able to solve this problem. This is the urls.py file that comes with the patch inside the registration app: urlpatterns = patterns('', # Activation keys get matched by \w+ instead of the more specific # [a-fA-F0-9]{40} because a bad activation key should still get to # that way it can return a sensible "invalid key" message instead # confusing 404. url(r'^activate/(?P<activation_key>\w+)/$', activate, name='registration_activate'), url(r'^login/$', auth_views.login, {'template_name': 'registration/login.html'}, name='auth_login'), url(r'^logout/$', auth_views.logout, name='auth_logout'), url(r'^password/change/$', auth_views.password_change, name='auth_password_change'), url(r'^password/change/done/$', auth_views.password_change_done, name='auth_password_change_done'), url(r'^password/reset/$', auth_views.password_reset, name='auth_password_reset'), url(r'^password/reset/confirm/(?P<uidb36>.+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='auth_password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.password_reset_complete, name='auth_password_reset_complete'), url(r'^password/reset/done/$', auth_views.password_reset_done, name='auth_password_reset_done'), url(r'^register/$', register, name='registration_register'), url(r'^register/complete/$', direct_to_template, {'template': 'registration/registration_complete.html'}, name='registration_complete'), ) A: I could not find a proper answer to my question. Anyways I solved the problem temporarily by reinstalling the Django framework and the app engine SDK.
No reverse error in Google App Engine Django patch?
I am using Google App Engine patch Django. When I try to go to the admin site, http://127.0.0.1:8080/admin/ , I keep getting this error: TemplateSyntaxError at /admin/ Caught an exception while rendering: Reverse for 'settings.django.contrib.auth.views.logout' with arguments '()' and keyword arguments '{}' not found. It's a fresh installation and I have not changed much. But I am not able to solve this problem. This is the urls.py file that comes with the patch inside the registration app: urlpatterns = patterns('', # Activation keys get matched by \w+ instead of the more specific # [a-fA-F0-9]{40} because a bad activation key should still get to # that way it can return a sensible "invalid key" message instead # confusing 404. url(r'^activate/(?P<activation_key>\w+)/$', activate, name='registration_activate'), url(r'^login/$', auth_views.login, {'template_name': 'registration/login.html'}, name='auth_login'), url(r'^logout/$', auth_views.logout, name='auth_logout'), url(r'^password/change/$', auth_views.password_change, name='auth_password_change'), url(r'^password/change/done/$', auth_views.password_change_done, name='auth_password_change_done'), url(r'^password/reset/$', auth_views.password_reset, name='auth_password_reset'), url(r'^password/reset/confirm/(?P<uidb36>.+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='auth_password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.password_reset_complete, name='auth_password_reset_complete'), url(r'^password/reset/done/$', auth_views.password_reset_done, name='auth_password_reset_done'), url(r'^register/$', register, name='registration_register'), url(r'^register/complete/$', direct_to_template, {'template': 'registration/registration_complete.html'}, name='registration_complete'), )
[ "I could not find a proper answer to my question. Anyways I solved the problem temporarily by reinstalling the Django framework and the app engine SDK.\n" ]
[ 1 ]
[]
[]
[ "django", "django_urls", "google_app_engine", "python" ]
stackoverflow_0000872100_django_django_urls_google_app_engine_python.txt
Q: SQLAlchemy - MappedCollection problem I have some problems with setting up the dictionary collection in Python's SQLAlchemy: I am using declarative definition of tables. I have Item table in 1:N relation with Record table. I set up the relation using the following code: _Base = declarative_base() class Record(_Base): __tablename__ = 'records' item_id = Column(String(M_ITEM_ID), ForeignKey('items.id')) id = Column(String(M_RECORD_ID), primary_key=True) uri = Column(String(M_RECORD_URI)) name = Column(String(M_RECORD_NAME)) class Item(_Base): __tablename__ = 'items' id = Column(String(M_ITEM_ID), primary_key=True) records = relation(Record, collection_class=column_mapped_collection(Record.name), backref='item') Now I want to work with the Items and Records. Let's create some objects: i1 = Item(id='id1') r = Record(id='mujrecord') And now I want to associate these objects using the following code: i1.records['source_wav'] = r but the Record r doesn't have set the name attribute (the foreign key). Is there any solution how to automatically ensure this? (I know that setting the foreign key during the Record creation works, but it doesn't sound good for me). Many thanks A: You want something like this: from sqlalchemy.orm import validates class Item(_Base): [...] @validates('records') def validate_record(self, key, record): assert record.name is not None, "Record fails validation, must have a name" return record With this, you get the desired validation: >>> i1 = Item(id='id1') >>> r = Record(id='mujrecord') >>> i1.records['source_wav'] = r Traceback (most recent call last): [...] AssertionError: Record fails validation, must have a name >>> r.name = 'foo' >>> i1.records['source_wav'] = r >>> A: I can't comment yet, so I'm just going to write this as a separate answer: from sqlalchemy.orm import validates class Item(_Base): [...] @validates('records') def validate_record(self, key, record): record.name=key return record This is basically a copy of Gunnlaugur's answer but abusing the validates decorator to do something more useful than exploding. A: You have: backref='item' Is this a typo for backref='name' ?
SQLAlchemy - MappedCollection problem
I have some problems with setting up the dictionary collection in Python's SQLAlchemy: I am using declarative definition of tables. I have Item table in 1:N relation with Record table. I set up the relation using the following code: _Base = declarative_base() class Record(_Base): __tablename__ = 'records' item_id = Column(String(M_ITEM_ID), ForeignKey('items.id')) id = Column(String(M_RECORD_ID), primary_key=True) uri = Column(String(M_RECORD_URI)) name = Column(String(M_RECORD_NAME)) class Item(_Base): __tablename__ = 'items' id = Column(String(M_ITEM_ID), primary_key=True) records = relation(Record, collection_class=column_mapped_collection(Record.name), backref='item') Now I want to work with the Items and Records. Let's create some objects: i1 = Item(id='id1') r = Record(id='mujrecord') And now I want to associate these objects using the following code: i1.records['source_wav'] = r but the Record r doesn't have set the name attribute (the foreign key). Is there any solution how to automatically ensure this? (I know that setting the foreign key during the Record creation works, but it doesn't sound good for me). Many thanks
[ "You want something like this:\nfrom sqlalchemy.orm import validates\n\nclass Item(_Base):\n [...]\n\n @validates('records')\n def validate_record(self, key, record):\n assert record.name is not None, \"Record fails validation, must have a name\"\n return record\n\nWith this, you get the desired validation:\n>>> i1 = Item(id='id1')\n>>> r = Record(id='mujrecord')\n>>> i1.records['source_wav'] = r\nTraceback (most recent call last):\n [...]\nAssertionError: Record fails validation, must have a name\n>>> r.name = 'foo'\n>>> i1.records['source_wav'] = r\n>>> \n\n", "I can't comment yet, so I'm just going to write this as a separate answer:\nfrom sqlalchemy.orm import validates\n\nclass Item(_Base):\n [...]\n\n @validates('records')\n def validate_record(self, key, record):\n record.name=key\n return record\n\nThis is basically a copy of Gunnlaugur's answer but abusing the validates decorator to do something more useful than exploding.\n", "You have:\nbackref='item'\n\nIs this a typo for \nbackref='name'\n\n?\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000793848_python_sqlalchemy.txt
Q: SQLAlchemy - Database hits on every request? I'm currently working with a web application written in Python (and using SQLAlchemy). In order to handle authentication, the app first checks for a user ID in the session, and providing it exists, pulls that whole user record out of the database and stores it for the rest of that request. Another query is also run to check the permissions of the user it has stored. I'm fairly new to the web application development world, but from my understanding, hitting the database for something like this on every request isn't efficient. Or is this considered a normal thing to do? The only thing I've thought of so far is pulling up this data once, and storing what's relevant (most of the data isn't even required on every request). However, this brings up the problem of what's supposed to happen if this user record happens to be removed in the interim. Any ideas on how best to manage this? A: "hitting the database for something like this on every request isn't efficient." False. And, you've assumed that there's no caching, which is also false. Most ORM layers are perfectly capable of caching rows, saving some DB queries. Most RDBMS's have extensive caching, resulting in remarkably fast responses to common queries. All ORM layers will use consistent SQL, further aiding the database in optimizing the repetitive operations. (Specifically, the SQL statement is cached, saving parsing and planning time.) " Or is this considered a normal thing to do?" True. Until you can prove that your queries are the slowest part of your application, don't worry. Build something that actually works. Then optimize the part that you can prove is the bottleneck. A: For a user login and basic permission tokens in a simple web application I will definitely store that in a cookie-based session. It's true that a few SELECTs per request is not a big deal at all, but then again if you can get some/all of your web requests to execute from cached data with no DB hits at all, that just adds that much more scalability to an app which is planning on receiving a lot of load. The issue of the user token being changed on the database is handled in two ways. One is, ignore it - for a lot of use cases its not that big a deal for the user to log out and log back in again to get at new permissions that have been granted elsewhere (witness unix as an example). The other is that all mutations of the user row are filtered through a method that also resets the state within the cookie-based session, but this is only effective if the user him/herself is the one initiating the changes through the browser interface. If OTOH neither of the above use cases apply to you, then you probably need to stick with a little bit of database access built into every request. A: You are basically talking about caching data as a performance optimization. As always, premature optimization is a bad idea. It's hard to know where the bottlenecks are beforehand, even more so if the application domain is new to you. Optimization adds complexity and if you optimize the wrong things, you not only have wasted the effort, but have made the necessary optimizations harder. Requesting user data usually is usually a pretty trivial query. You can build yourself a simple benchmark to see what kind of overhead it will introduce. If it isn't a significant percentage of your time-budget, just leave it be. If you still want to cache the data on the application server then you have to come up with a cache invalidation scheme. Possible schemes are to check for changes from the database. If you don't have a lot of data to cache, this really isn't significantly more efficient than just reloading it. Another option is to just time out cached data. This is a good option if instant visibility of changes isn't important. Another option is to actively invalidate caches on changes. This depends on whether you only modify the database through your application and if you have a single application server or a clustered solution. A: It's a Database, so often it's fairly common to "hit" the Database to pull the required data. You can reduce single queries if you build up Joins or Stored Procedures.
SQLAlchemy - Database hits on every request?
I'm currently working with a web application written in Python (and using SQLAlchemy). In order to handle authentication, the app first checks for a user ID in the session, and providing it exists, pulls that whole user record out of the database and stores it for the rest of that request. Another query is also run to check the permissions of the user it has stored. I'm fairly new to the web application development world, but from my understanding, hitting the database for something like this on every request isn't efficient. Or is this considered a normal thing to do? The only thing I've thought of so far is pulling up this data once, and storing what's relevant (most of the data isn't even required on every request). However, this brings up the problem of what's supposed to happen if this user record happens to be removed in the interim. Any ideas on how best to manage this?
[ "\"hitting the database for something like this on every request isn't efficient.\"\nFalse. And, you've assumed that there's no caching, which is also false.\nMost ORM layers are perfectly capable of caching rows, saving some DB queries.\nMost RDBMS's have extensive caching, resulting in remarkably fast responses to common queries.\nAll ORM layers will use consistent SQL, further aiding the database in optimizing the repetitive operations. (Specifically, the SQL statement is cached, saving parsing and planning time.)\n\" Or is this considered a normal thing to do?\"\nTrue.\nUntil you can prove that your queries are the slowest part of your application, don't worry. Build something that actually works. Then optimize the part that you can prove is the bottleneck.\n", "For a user login and basic permission tokens in a simple web application I will definitely store that in a cookie-based session. It's true that a few SELECTs per request is not a big deal at all, but then again if you can get some/all of your web requests to execute from cached data with no DB hits at all, that just adds that much more scalability to an app which is planning on receiving a lot of load. \nThe issue of the user token being changed on the database is handled in two ways. One is, ignore it - for a lot of use cases its not that big a deal for the user to log out and log back in again to get at new permissions that have been granted elsewhere (witness unix as an example). The other is that all mutations of the user row are filtered through a method that also resets the state within the cookie-based session, but this is only effective if the user him/herself is the one initiating the changes through the browser interface.\nIf OTOH neither of the above use cases apply to you, then you probably need to stick with a little bit of database access built into every request.\n", "You are basically talking about caching data as a performance optimization. As always, premature optimization is a bad idea. It's hard to know where the bottlenecks are beforehand, even more so if the application domain is new to you. Optimization adds complexity and if you optimize the wrong things, you not only have wasted the effort, but have made the necessary optimizations harder.\nRequesting user data usually is usually a pretty trivial query. You can build yourself a simple benchmark to see what kind of overhead it will introduce. If it isn't a significant percentage of your time-budget, just leave it be.\nIf you still want to cache the data on the application server then you have to come up with a cache invalidation scheme.\nPossible schemes are to check for changes from the database. If you don't have a lot of data to cache, this really isn't significantly more efficient than just reloading it.\nAnother option is to just time out cached data. This is a good option if instant visibility of changes isn't important.\nAnother option is to actively invalidate caches on changes. This depends on whether you only modify the database through your application and if you have a single application server or a clustered solution.\n", "It's a Database, so often it's fairly common to \"hit\" the Database to pull the required data. You can reduce single queries if you build up Joins or Stored Procedures.\n" ]
[ 3, 3, 2, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000881517_python_sqlalchemy.txt
Q: How do I detect when my window is minimized with wxPython? I am writing a small wxPython utility. I would like to use some event to detect when a user minimizes the application/window. I have looked around but did not find an event like wx.EVT_MINIMIZE that I could bind to. Anyone know of a way that can be used to detect this? A: Add a handler for the wx.EVT_ICONIZE event.
How do I detect when my window is minimized with wxPython?
I am writing a small wxPython utility. I would like to use some event to detect when a user minimizes the application/window. I have looked around but did not find an event like wx.EVT_MINIMIZE that I could bind to. Anyone know of a way that can be used to detect this?
[ "Add a handler for the wx.EVT_ICONIZE event.\n" ]
[ 3 ]
[]
[]
[ "minimize", "python", "wxpython" ]
stackoverflow_0000890170_minimize_python_wxpython.txt
Q: What is "wua" mode when opening a file in python? I have recently been going through some of our windows python 2.4 code and come across this: self.logfile = open(self.logfile_name, "wua") I know what w, u and a do on their own, but what happens when you combine them? A: The a is superfluous. wua is the same as wu since w comes first and will thus truncate the file. If you would reverse the order, that is, auw, that would be the same as au. Visualized: >>> f = open('test.txt', 'r') >>> f.read() 'Initial contents\n' >>> f.close() >>> f = open('test.txt', 'wua') >>> print >> f, 'writing' >>> f.close() >>> f = open('test.txt', 'r') >>> f.read() 'writing\n' >>> f.close() >>> f = open('test.txt', 'auw') >>> print >> f, 'appending' >>> f.close() >>> f = open('test.txt', 'r') >>> f.read() 'writing\nappending\n' >>> f.close() (Reminder: both a and w open the file for writing, but the former appends while the other truncates.) A: I did not notice that you knew what the modifiers did. Combined they will do the following: A and W together is superfluous since both will open for writing. When using W, the file will be overwritten. When using A, all new text is appended after the existing content. U means "open file XXX for input as a text file with universal newline interpretation". W is for Write A is for Append U will convert the file to use the defined newline character. More here: http://codesnippets.joyent.com/posts/show/1969 A: Underneath the hood Python 2.4 passes the the builtin open's arguments on to the operating system's fopen function. Python does do some mangling of the mode string under certain conditions. if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0) mode = "rb"; So if you pass an upper case U or rU it will open the file for binary reading. Looking at the GNU libc source and according to the MSDN page describing the windows implementation of fopen the 'u' option is ignored. Having more than one mode designator ('r', 'w' and 'a') in the mode string has no effect. This can be seen by looking at the GNU libc implementation of mode string parsing: switch (*mode) { case 'r': omode = O_RDONLY; break; case 'w': omode = O_WRONLY; oflags = O_CREAT|O_TRUNC; break; case 'a': omode = O_WRONLY; oflags = O_CREAT|O_APPEND; break; default: __set_errno (EINVAL); return NULL; } The first character of the mode string is searched for one of 'r', 'w' or 'a', if it's not one of these characters an error is raised. Therefore when a file is opened as "wua" it will be opened for writing only, created if it doesn't exist and truncated. 'u' and 'a' will be ignored.
What is "wua" mode when opening a file in python?
I have recently been going through some of our windows python 2.4 code and come across this: self.logfile = open(self.logfile_name, "wua") I know what w, u and a do on their own, but what happens when you combine them?
[ "The a is superfluous. wua is the same as wu since w comes first and will thus truncate the file. If you would reverse the order, that is, auw, that would be the same as au. Visualized:\n>>> f = open('test.txt', 'r')\n>>> f.read()\n'Initial contents\\n'\n>>> f.close()\n>>> f = open('test.txt', 'wua')\n>>> print >> f, 'writing'\n>>> f.close()\n>>> f = open('test.txt', 'r')\n>>> f.read()\n'writing\\n'\n>>> f.close()\n>>> f = open('test.txt', 'auw')\n>>> print >> f, 'appending'\n>>> f.close()\n>>> f = open('test.txt', 'r')\n>>> f.read()\n'writing\\nappending\\n'\n>>> f.close()\n\n(Reminder: both a and w open the file for writing, but the former appends while the other truncates.)\n", "I did not notice that you knew what the modifiers did. Combined they will do the following:\nA and W together is superfluous since both will open for writing. When using W, the file will be overwritten. When using A, all new text is appended after the existing content.\nU means \"open file XXX for input as a text file with universal newline interpretation\".\n\nW is for Write\nA is for Append\nU will\nconvert the file to use the defined\nnewline character.\n\nMore here:\nhttp://codesnippets.joyent.com/posts/show/1969\n", "Underneath the hood Python 2.4 passes the the builtin open's arguments on to the operating system's fopen function. Python does do some mangling of the mode string under certain conditions.\nif (strcmp(mode, \"U\") == 0 || strcmp(mode, \"rU\") == 0)\n mode = \"rb\";\n\nSo if you pass an upper case U or rU it will open the file for binary reading. Looking at the GNU libc source and according to the MSDN page describing the windows implementation of fopen the 'u' option is ignored.\nHaving more than one mode designator ('r', 'w' and 'a') in the mode string has no effect. This can be seen by looking at the GNU libc implementation of mode string parsing:\nswitch (*mode)\n{\ncase 'r':\n omode = O_RDONLY;\n break;\ncase 'w':\n omode = O_WRONLY;\n oflags = O_CREAT|O_TRUNC;\n break;\ncase 'a':\n omode = O_WRONLY;\n oflags = O_CREAT|O_APPEND;\n break;\ndefault:\n __set_errno (EINVAL);\n return NULL;\n}\n\nThe first character of the mode string is searched for one of 'r', 'w' or 'a', if it's not one of these characters an error is raised.\nTherefore when a file is opened as \"wua\" it will be opened for writing only, created if it doesn't exist and truncated. 'u' and 'a' will be ignored.\n" ]
[ 5, 3, 2 ]
[]
[]
[ "file", "python" ]
stackoverflow_0000886238_file_python.txt
Q: Substituting a regex only when it doesn't match another regex (Python) Long story short, I have two regex patterns. One pattern matches things that I want to replace, and the other pattern matches a special case of those patterns that should not be replace. For a simple example, imagine that the first one is "\{.*\}" and the second one is "\{\{.*\}\}". Then "{this}" should be replaced, but "{{this}}" should not. Is there an easy way to take a string and say "substitute all instances of the first string with "hello" so long as it is not matching the second string"? In other words, is there a way to make a regex that is "matches the first string but not the second" easily without modifying the first string? I know that I could modify my first regex by hand to never match instances of the second, but as the first regex gets more complex, that gets very difficult. A: Using negative look-ahead/behind assertion pattern = re.compile( "(?<!\{)\{(?!\{).*?(?<!\})\}(?!\})" ) pattern.sub( "hello", input_string ) Negative look-ahead/behind assertion allows you to compare against more of the string, but is not considered as using up part of the string for the match. There is also a normal look ahead/behind assertion which will cause the string to match only if the string IS followed/preceded by the given pattern. That's a bit confusing looking, here it is in pieces: "(?<!\{)" #Not preceded by a { "\{" #A { "(?!\{)" #Not followed by a { ".*?" #Any character(s) (non-greedy) "(?<!\})" #Not preceded by a } (in reference to the next character) "\}" #A } "(?!\})" #Not followed by a } So, we're looking for a { without any other {'s around it, followed by some characters, followed by a } without any other }'s around it. By using negative look-ahead/behind assertion, we condense it down to a single regular expression which will successfully match only single {}'s anywhere in the string. Also, note that * is a greedy operator. It will match as much as it possibly can. If you use "\{.*\}" and there is more than one {} block in the text, everything between will be taken with it. "This is some example text {block1} more text, watch me disappear {block2} even more text" becomes "This is some example text hello even more text" instead of "This is some example text hello more text, watch me disappear hello even more text" To get the proper output we need to make it non-greedy by appending a ?. The python docs do a good job of presenting the re library, but the only way to really learn is to experiment. A: You can give replace a function (reference) But make sure the first regex contain the second one. This is just an example: regex1 = re.compile('\{.*\}') regex2 = re.compile('\{\{.*\}\}') def replace(match): match = match.group(0) if regex2.match(match): return match return 'replacement' regex1.sub(replace, data) A: You could replace all the {} instances with your replacement string (which would include the {{}} ones), and then replace the {{}} ones with a back-reference to itself (overwriting the first replace with the original data) -- then only the {} instances would have changed. A: It strikes me as sub-optimal to match against two different regexes when what you're looking for is really one pattern. To illustrate: import re foo = "{{this}}" bar = "{that}" re.match("\{[^\{].*[^\}]\}", foo) # gives you nothing re.match("\{[^\{].*[^\}]\}", bar) # gives you a match object So it's really your regex which could be a bit more precise.
Substituting a regex only when it doesn't match another regex (Python)
Long story short, I have two regex patterns. One pattern matches things that I want to replace, and the other pattern matches a special case of those patterns that should not be replace. For a simple example, imagine that the first one is "\{.*\}" and the second one is "\{\{.*\}\}". Then "{this}" should be replaced, but "{{this}}" should not. Is there an easy way to take a string and say "substitute all instances of the first string with "hello" so long as it is not matching the second string"? In other words, is there a way to make a regex that is "matches the first string but not the second" easily without modifying the first string? I know that I could modify my first regex by hand to never match instances of the second, but as the first regex gets more complex, that gets very difficult.
[ "Using negative look-ahead/behind assertion\npattern = re.compile( \"(?<!\\{)\\{(?!\\{).*?(?<!\\})\\}(?!\\})\" )\npattern.sub( \"hello\", input_string )\n\nNegative look-ahead/behind assertion allows you to compare against more of the string, but is not considered as using up part of the string for the match. There is also a normal look ahead/behind assertion which will cause the string to match only if the string IS followed/preceded by the given pattern.\nThat's a bit confusing looking, here it is in pieces:\n\"(?<!\\{)\" #Not preceded by a {\n\"\\{\" #A {\n\"(?!\\{)\" #Not followed by a {\n\".*?\" #Any character(s) (non-greedy)\n\"(?<!\\})\" #Not preceded by a } (in reference to the next character)\n\"\\}\" #A }\n\"(?!\\})\" #Not followed by a }\n\nSo, we're looking for a { without any other {'s around it, followed by some characters, followed by a } without any other }'s around it.\nBy using negative look-ahead/behind assertion, we condense it down to a single regular expression which will successfully match only single {}'s anywhere in the string.\nAlso, note that * is a greedy operator. It will match as much as it possibly can. If you use \"\\{.*\\}\" and there is more than one {} block in the text, everything between will be taken with it.\n\n\"This is some example text {block1} more text, watch me disappear {block2} even more text\"\n\nbecomes\n\n\"This is some example text hello even more text\"\n\ninstead of\n\n\"This is some example text hello more text, watch me disappear hello even more text\"\n\nTo get the proper output we need to make it non-greedy by appending a ?.\nThe python docs do a good job of presenting the re library, but the only way to really learn is to experiment.\n", "You can give replace a function (reference)\nBut make sure the first regex contain the second one. This is just an example:\nregex1 = re.compile('\\{.*\\}')\nregex2 = re.compile('\\{\\{.*\\}\\}')\n\ndef replace(match):\n match = match.group(0)\n if regex2.match(match):\n return match\n return 'replacement'\n\n\nregex1.sub(replace, data)\n\n", "You could replace all the {} instances with your replacement string (which would include the {{}} ones), and then replace the {{}} ones with a back-reference to itself (overwriting the first replace with the original data) -- then only the {} instances would have changed.\n", "It strikes me as sub-optimal to match against two different regexes when what you're looking for is really one pattern. To illustrate:\nimport re\nfoo = \"{{this}}\"\nbar = \"{that}\"\nre.match(\"\\{[^\\{].*[^\\}]\\}\", foo) # gives you nothing\nre.match(\"\\{[^\\{].*[^\\}]\\}\", bar) # gives you a match object\n\nSo it's really your regex which could be a bit more precise.\n" ]
[ 7, 4, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000889045_python_regex.txt
Q: Google App Engine Python Code: User Service What does this example program from the Google App Engine documentation mean when it references self? Where can i look up what methods (such as self.response...)? from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class MainPage(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hello, ' + user.nickname()) else: self.redirect(users.create_login_url(self.request.uri)) application = webapp.WSGIApplication( [('/', MainPage)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main() A: self refers to the webapp.RequestHandler class. Here is its documentation: http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html, which tells you what response means. A: self is a python convention which means 'this' in other languages like Java, C#, C++, etc...I've found it bizarre that you need to explicitly reference yourself when talking about objects (I have a Java background), but you sort of get used to it. If you're going to use python, I suggest you get an editor that does code completion and understands python syntax, it'll make your life easier when trying to determine what functions are available for a given class or module
Google App Engine Python Code: User Service
What does this example program from the Google App Engine documentation mean when it references self? Where can i look up what methods (such as self.response...)? from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class MainPage(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hello, ' + user.nickname()) else: self.redirect(users.create_login_url(self.request.uri)) application = webapp.WSGIApplication( [('/', MainPage)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
[ "self refers to the webapp.RequestHandler class. Here is its documentation: http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html, which tells you what response means.\n", "self is a python convention which means 'this' in other languages like Java, C#, C++, etc...I've found it bizarre that you need to explicitly reference yourself when talking about objects (I have a Java background), but you sort of get used to it.\nIf you're going to use python, I suggest you get an editor that does code completion and understands python syntax, it'll make your life easier when trying to determine what functions are available for a given class or module\n" ]
[ 5, 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000890857_google_app_engine_python.txt
Q: Dynamic generation of .doc files How can you dynamically generate a .doc file using AJAX? Python? Adobe AIR? I'm thinking of a situation where an online program/desktop app takes in user feedback in article form (a la wiki) in Icelandic character encoding and then upon pressing a button releases a .doc file containing the user input for the webpage. Any solutions/suggestions would be much appreciated. PS- I don't want to go the C#/Java way with this. A: The problem with the *.doc MS word format is, that it isn't documented enough, therefor it can't have a very good support like, for example, PDF, which is a standard. Except of the problems with generating the doc, you're users might have problems reading the doc files. For example users on linux machines. You should consider producing RTF on the server. It is more standard, and thus more supported both for document generation, and for reading the document afterwards. Unless you need very specific features, it should suffice for most of documents types, and MS word opens it by default, just like it opens its own native format. PyRTF is an project you can use for RTF generation with python. A: It don't have to do much with ajax(in th sense that ajax is generally used for dynamic client side interactions) You need a server side script which takes the input and converts it to doc. You may use something like openoffice and python if it has some interface see http://wiki.services.openoffice.org/wiki/Python or on windows you can directly use Word COM objects to create doc using win32apis but it is less probable, that a windows server serving python :) I think better alternative is to generate PDF which would be nicer and easier. Reportlab has a wonderful pdf generation library and it works like charm from python. Once you have pdf you may use some pdf to doc converter, but I think PDF would be good enough. Edit: Doc generation On second thought if you are insisting on DOC you may have windows server in that case you can use COM objets to generate DOC, xls or whatever see http://win32com.goermezer.de/content/view/173/284/
Dynamic generation of .doc files
How can you dynamically generate a .doc file using AJAX? Python? Adobe AIR? I'm thinking of a situation where an online program/desktop app takes in user feedback in article form (a la wiki) in Icelandic character encoding and then upon pressing a button releases a .doc file containing the user input for the webpage. Any solutions/suggestions would be much appreciated. PS- I don't want to go the C#/Java way with this.
[ "The problem with the *.doc MS word format is, that it isn't documented enough, therefor it can't have a very good support like, for example, PDF, which is a standard.\nExcept of the problems with generating the doc, you're users might have problems reading the doc files. For example users on linux machines.\nYou should consider producing RTF on the server. It is more standard, and thus more supported both for document generation, and for reading the document afterwards. Unless you need very specific features, it should suffice for most of documents types, and MS word opens it by default, just like it opens its own native format.\nPyRTF is an project you can use for RTF generation with python.\n", "It don't have to do much with ajax(in th sense that ajax is generally used for dynamic client side interactions)\nYou need a server side script which takes the input and converts it to doc.\nYou may use something like openoffice and python if it has some interface\nsee http://wiki.services.openoffice.org/wiki/Python\nor on windows you can directly use Word COM objects to create doc using win32apis\nbut it is less probable, that a windows server serving python :)\nI think better alternative is to generate PDF which would be nicer and easier.\nReportlab has a wonderful pdf generation library and it works like charm from python.\nOnce you have pdf you may use some pdf to doc converter, but I think PDF would be good enough.\nEdit: Doc generation\nOn second thought if you are insisting on DOC you may have windows server in that case\nyou can use COM objets to generate DOC, xls or whatever see\nhttp://win32com.goermezer.de/content/view/173/284/\n" ]
[ 2, 0 ]
[]
[]
[ "air", "ajax", "dynamic_data", "python" ]
stackoverflow_0000891315_air_ajax_dynamic_data_python.txt
Q: Why would one choose Iron Python instead of Boo? Possible Duplicates: BOO Vs IronPython Boo vs. IronPython Say you want to embed a scripting language into a .NET application. Boo is modelled on Python syntax, but also includes type inference, and just in general seems to be a better, more modern language to embed as a scripting language. Why, then, is there so much fuss about Iron Python? LATER As was pointed out, this question is an exact duplicate of: this and this A: 2 words: User Base. I already know so many languages that I have to keep references handy so I can remember if it's "else if", "elsif" or "elif" in whatever I'm currently working in. Unless there's a compelling reason to use another language (more than just a few small differences) I'm going to stick with one I already know. A: IronPython is directly developed and supported by Microsoft (under the awesome technical lead of Jim Hugunin!), AND has an insanely great book about it ("IronPython in Action", which I'm biased about but nevertheless evangelize shamelessly). Apart from that, Boo appears to be a great contender, and I'd love to try it out (were I ever to use .NET in earnest rather than as a for-fun endeavor -- as my professional development these days targets Linux and Mac, not Windows, that doesn't seem a likely prospect). If you're using .NET as your main development target, my recommendation is to pick a few small but not toy projects in your area of expertise and develop each of them in both Boo and IronPython (alternating which one goes first) -- after you're through a few, you'll KNOW what's right for you. That's how I ended up switching from Perl 4 to Python as my main language back in the '90s (rather than sticking with Perl 4, of which I was an expert and guru, or switching to then-brand-new Perl 5) -- a few "pilot projects" fully developed in each environment left me with no doubt about what was best for my own productivity. A: People like python, and they don't want anything else. Is there really anything else to this question?
Why would one choose Iron Python instead of Boo?
Possible Duplicates: BOO Vs IronPython Boo vs. IronPython Say you want to embed a scripting language into a .NET application. Boo is modelled on Python syntax, but also includes type inference, and just in general seems to be a better, more modern language to embed as a scripting language. Why, then, is there so much fuss about Iron Python? LATER As was pointed out, this question is an exact duplicate of: this and this
[ "2 words: User Base.\nI already know so many languages that I have to keep references handy so I can remember if it's \"else if\", \"elsif\" or \"elif\" in whatever I'm currently working in. Unless there's a compelling reason to use another language (more than just a few small differences) I'm going to stick with one I already know.\n", "IronPython is directly developed and supported by Microsoft (under the awesome technical lead of Jim Hugunin!), AND has an insanely great book about it (\"IronPython in Action\", which I'm biased about but nevertheless evangelize shamelessly). Apart from that, Boo appears to be a great contender, and I'd love to try it out (were I ever to use .NET in earnest rather than as a for-fun endeavor -- as my professional development these days targets Linux and Mac, not Windows, that doesn't seem a likely prospect).\nIf you're using .NET as your main development target, my recommendation is to pick a few small but not toy projects in your area of expertise and develop each of them in both Boo and IronPython (alternating which one goes first) -- after you're through a few, you'll KNOW what's right for you. That's how I ended up switching from Perl 4 to Python as my main language back in the '90s (rather than sticking with Perl 4, of which I was an expert and guru, or switching to then-brand-new Perl 5) -- a few \"pilot projects\" fully developed in each environment left me with no doubt about what was best for my own productivity.\n", "People like python, and they don't want anything else. Is there really anything else to this question?\n" ]
[ 2, 1, 0 ]
[]
[]
[ ".net", "boo", "ironpython", "python" ]
stackoverflow_0000890420_.net_boo_ironpython_python.txt
Q: Install older versions of Python for testing on Mac OS X I have Mac OS X 10.5.7 with Python 2.5. I need to test a package I am working on with Python 2.3 for compatibility. I don't want to downgrade my whole system so is there a way to do an install of Python 2.3 that does not change the system python? A: You have two main options, install the python 2.3 from macports (easy) or install from source. For macports, run port install python23 For the 2nd, you'll have to go to http://www.python.org/download/releases/2.3.7/ to download the source tarball. Once you have that open a terminal and run ./configure --prefix /home/(your homedir)/software MACOSX_DEPLOYMENT_TARGET=10.5 then make and make install. This should place a separate install in the software directory that you can access directly. A: One alternative is to use a virtual machine. With something like VMWare Fusion or Virtualbox you could install a complete Linux system with Python2.3, and do your testing there. The advantage is that it would be completely sand-boxed, so wouldn't affect your main system at all. A: This page has useful information on building python from source. It's talking about 3.0, but the advice will probably apply to 2.3 as well. A: You can also use the Fink package manager and simply to "fink install python2.3". If you need Python 2.3 to be your default, you can simply change /sw/bin/python and /sw/bin/pydoc to point to the version you want (they sit in /sw/bin/).
Install older versions of Python for testing on Mac OS X
I have Mac OS X 10.5.7 with Python 2.5. I need to test a package I am working on with Python 2.3 for compatibility. I don't want to downgrade my whole system so is there a way to do an install of Python 2.3 that does not change the system python?
[ "You have two main options, install the python 2.3 from macports (easy) or install from source.\nFor macports, run port install python23\nFor the 2nd, you'll have to go to http://www.python.org/download/releases/2.3.7/ to download the source tarball. Once you have that open a terminal and run ./configure --prefix /home/(your homedir)/software MACOSX_DEPLOYMENT_TARGET=10.5 then make and make install. This should place a separate install in the software directory that you can access directly.\n", "One alternative is to use a virtual machine. \nWith something like VMWare Fusion or Virtualbox you could install a complete Linux system with Python2.3, and do your testing there. The advantage is that it would be completely sand-boxed, so wouldn't affect your main system at all.\n", "This page has useful information on building python from source. It's talking about 3.0, but the advice will probably apply to 2.3 as well.\n", "You can also use the Fink package manager and simply to \"fink install python2.3\".\nIf you need Python 2.3 to be your default, you can simply change /sw/bin/python and /sw/bin/pydoc to point to the version you want (they sit in /sw/bin/).\n" ]
[ 6, 1, 0, 0 ]
[]
[]
[ "installation", "python", "version" ]
stackoverflow_0000890827_installation_python_version.txt
Q: GUI app spawned from a LocalSystem Service (via CreateProcessAsUser) does not have focus I have created a service which display a sort of splash screen on the desktop of a specific user and only when that user is logged in (kiosk user). That splash screen, once entered a valid code, will tell that to the service and the service goes to sleep for an x amount of time (depending of the code). The splash screen simply quits. Now when the service wakes up it sees that the splash is no longer there and so start it up. This all is working, the only problem is that the launched application does not have focus, i.e. if I am working in notepad and the time is up, the splash screen is displayed (full screen though) behind notepad. I only have to worry about Windows Vista, I am coding in Python using win32 extensions but I believe this problem lies in CreateProcessAsUser when called from the LocalSystem account. Update: The 'problem' is actually an on purpose limitation to prevent 'irritating' applications like mine from stealing focus. You can change the behaviour by setting: win32gui.SystemParametersInfo(win32con.SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0) which is equivalent in temporarily setting the registry value: HKEY_CURRENT_USER\Control Panel\Desktop\ForegroundLockTimeout This must be done as the user itself, so either build it in the app you are launching or build an launching helper for the app you want to launch. However an application might want to prevent getting it's focus stolen by using some API call which I don't remember right now. A probably good solution would be to find all window handles currently from that user and then use each of these handles to use win32gui.ShowWindow(handle, command) to minimize it. Although for this particular problem setting the locktimeout setting was enough. If anyone wonders how I managed to launch an application to a desktop from a service, here is a link to the code. A: Have you tried launching another processes than your own from the service to see if it gets focus? Like notepad and see if it steals focus from your browser? If so perhaps its the program that can take back the focus when it starts. I otherwise beilive it's the wShowWindow attribute from the STARTUPINFO struct the lpStartupInfo points to that should control it. You also need STARTF_USESHOWWINDOW in dwFlags to use nShowWindow. The values should be SW_SHOW i think, they are listed for the ShowWindow function if you want to try other. A: For various very legitimated reasons, Microsoft would rather not see a service launching an app and stealing focus, however I found the following work around to still accomplish what I want. The original intend is to have a kiosk like application hindered by a pass code like splash screen, which upon entering a 8 character code closes the splash screen for a period time as in the pass code defined. Originally the actual application to use was started by the autostart folder. However I now rewrote it that it is launched from my service, this way I can hide the application by launching an helper application from the service that just hides the program and launches the splash screen, upon exiting the splash screen the program is returned to the previous state.
GUI app spawned from a LocalSystem Service (via CreateProcessAsUser) does not have focus
I have created a service which display a sort of splash screen on the desktop of a specific user and only when that user is logged in (kiosk user). That splash screen, once entered a valid code, will tell that to the service and the service goes to sleep for an x amount of time (depending of the code). The splash screen simply quits. Now when the service wakes up it sees that the splash is no longer there and so start it up. This all is working, the only problem is that the launched application does not have focus, i.e. if I am working in notepad and the time is up, the splash screen is displayed (full screen though) behind notepad. I only have to worry about Windows Vista, I am coding in Python using win32 extensions but I believe this problem lies in CreateProcessAsUser when called from the LocalSystem account. Update: The 'problem' is actually an on purpose limitation to prevent 'irritating' applications like mine from stealing focus. You can change the behaviour by setting: win32gui.SystemParametersInfo(win32con.SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0) which is equivalent in temporarily setting the registry value: HKEY_CURRENT_USER\Control Panel\Desktop\ForegroundLockTimeout This must be done as the user itself, so either build it in the app you are launching or build an launching helper for the app you want to launch. However an application might want to prevent getting it's focus stolen by using some API call which I don't remember right now. A probably good solution would be to find all window handles currently from that user and then use each of these handles to use win32gui.ShowWindow(handle, command) to minimize it. Although for this particular problem setting the locktimeout setting was enough. If anyone wonders how I managed to launch an application to a desktop from a service, here is a link to the code.
[ "Have you tried launching another processes than your own from the service to see if it gets focus? Like notepad and see if it steals focus from your browser? If so perhaps its the program that can take back the focus when it starts.\nI otherwise beilive it's the wShowWindow attribute from the STARTUPINFO struct the lpStartupInfo points to that should control it. You also need STARTF_USESHOWWINDOW in dwFlags to use nShowWindow. The values should be SW_SHOW i think, they are listed for the ShowWindow function if you want to try other.\n", "For various very legitimated reasons, Microsoft would rather not see a service launching an app and stealing focus, however I found the following work around to still accomplish what I want.\nThe original intend is to have a kiosk like application hindered by a pass code like splash screen, which upon entering a 8 character code closes the splash screen for a period time as in the pass code defined. Originally the actual application to use was started by the autostart folder.\nHowever I now rewrote it that it is launched from my service, this way I can hide the application by launching an helper application from the service that just hides the program and launches the splash screen, upon exiting the splash screen the program is returned to the previous state.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "pywin32", "tkinter", "windows_services" ]
stackoverflow_0000860428_python_pywin32_tkinter_windows_services.txt
Q: Strings and file Suppose this is my list of languages. aList = ['Python','C','C++','Java'] How can i write to a file like : Python : ... C : ... C++ : ... Java : ... I have used rjust() to achieve this. Without it how can i do ? Here i have done manually. I want to avoid that,ie; it shuould be ordered automatically. A: You can do this with string formatting operators f=open('filename.txt','w') for item in aList: print >>f, "%-20s : ..." % item The 20 is the field width, while the "-" indicates to left justify it. A: Do you mean this? >>> languages = ['Python','C','C++','Java'] >>> f = open('myfile.txt', 'w') >>> print('\n'.join('%-10s: ...' % l for l in languages), file=f) >>> f.close() >>> print(open('myfile.txt').read()) Python : ... C : ... C++ : ... Java : ... This uses the format specification mini language. Note the print statement uses 3.0 syntax. (Yeah I changed this since Brian's answer links to the 2.5.2 docs. Just for contrast.) A: Automatically determine colon position (using max width) and language order (sorted alphabetically): languages = ['Python','C','C++','Java'] maxlen = max(map(len, languages)) with open('langs.txt', 'w') as f: for L in sorted(languages): f.write('%-*s: ...\n'% (maxlen, L)) print open('langs.txt').read() Output: C : ... C++ : ... Java : ... Python: ...
Strings and file
Suppose this is my list of languages. aList = ['Python','C','C++','Java'] How can i write to a file like : Python : ... C : ... C++ : ... Java : ... I have used rjust() to achieve this. Without it how can i do ? Here i have done manually. I want to avoid that,ie; it shuould be ordered automatically.
[ "You can do this with string formatting operators\nf=open('filename.txt','w')\nfor item in aList:\n print >>f, \"%-20s : ...\" % item\n\nThe 20 is the field width, while the \"-\" indicates to left justify it.\n", "Do you mean this?\n>>> languages = ['Python','C','C++','Java']\n>>> f = open('myfile.txt', 'w')\n>>> print('\\n'.join('%-10s: ...' % l for l in languages), file=f)\n>>> f.close()\n>>> print(open('myfile.txt').read())\nPython : ...\nC : ...\nC++ : ...\nJava : ...\n\nThis uses the format specification mini language. Note the print statement uses 3.0 syntax. (Yeah I changed this since Brian's answer links to the 2.5.2 docs. Just for contrast.)\n", "Automatically determine colon position (using max width) and language order (sorted alphabetically):\nlanguages = ['Python','C','C++','Java']\nmaxlen = max(map(len, languages))\nwith open('langs.txt', 'w') as f:\n for L in sorted(languages):\n f.write('%-*s: ...\\n'% (maxlen, L)) \n\nprint open('langs.txt').read()\n\nOutput:\nC : ...\nC++ : ...\nJava : ...\nPython: ...\n\n" ]
[ 5, 5, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0000891895_python_string.txt
Q: Python regular expression to match # followed by 0-7 followed by ## I would like to intercept string starting with \*#\* followed by a number between 0 and 7 and ending with: ## so something like \*#\*0## but I could not find a regex for this A: Assuming you want to allow only one # before and two after, I'd do it like this: r'^(\#{1}([0-7])\#{2})' It's important to note that Alex's regex will also match things like ###7###### ########1### which may or may not matter. My regex above matches a string starting with #[0-7]## and ignores the end of the string. You could tack a $ onto the end if you wanted it to match only if that's the entire line. The first backreference gives you the entire #<number>## string and the second backreference gives you the number inside the #. A: None of the above examples are taking into account the *#* ^\*#\*[0-7]##$ Pass : *#*7## Fail : *#*22324324## Fail : *#3232# The ^ character will match the start of the string, \* will match a single asterisk, the # characters do not need to be escape in this example, and finally the [0-7] will only match a single character between 0 and 7. A: r'\#[0-7]\#\#' A: The regular expression should be like ^#[0-7]##$ A: As I understand the question, the simplest regular expression you need is: rex= re.compile(r'^\*#\*([0-7])##$') The {1} constructs are redundant. After doing rex.match (or rex.search, but it's not necessary here), .group(1) of the match object contains the digit given. EDIT: The whole matched string is always available as match.group(0). If all you need is the complete string, drop any parentheses in the regular expression: rex= re.compile(r'^\*#\*[0-7]##$')
Python regular expression to match # followed by 0-7 followed by ##
I would like to intercept string starting with \*#\* followed by a number between 0 and 7 and ending with: ## so something like \*#\*0## but I could not find a regex for this
[ "Assuming you want to allow only one # before and two after, I'd do it like this:\nr'^(\\#{1}([0-7])\\#{2})'\n\nIt's important to note that Alex's regex will also match things like\n###7######\n########1###\n\nwhich may or may not matter.\nMy regex above matches a string starting with #[0-7]## and ignores the end of the string. You could tack a $ onto the end if you wanted it to match only if that's the entire line.\nThe first backreference gives you the entire #<number>## string and the second backreference gives you the number inside the #.\n", "None of the above examples are taking into account the *#*\n^\\*#\\*[0-7]##$\n\nPass : *#*7##\nFail : *#*22324324##\nFail : *#3232#\nThe ^ character will match the start of the string, \\* will match a single asterisk, the # characters do not need to be escape in this example, and finally the [0-7] will only match a single character between 0 and 7.\n", "r'\\#[0-7]\\#\\#'\n", "The regular expression should be like ^#[0-7]##$\n", "As I understand the question, the simplest regular expression you need is:\nrex= re.compile(r'^\\*#\\*([0-7])##$')\n\nThe {1} constructs are redundant.\nAfter doing rex.match (or rex.search, but it's not necessary here), .group(1) of the match object contains the digit given.\nEDIT: The whole matched string is always available as match.group(0). If all you need is the complete string, drop any parentheses in the regular expression:\nrex= re.compile(r'^\\*#\\*[0-7]##$')\n\n" ]
[ 7, 4, 1, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000889143_python_regex.txt
Q: How would one build an smtp client in python? buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !! A: Create mail messages (possibly with multipart attachments) with email. The email package is a library for managing email messages, including MIME and other RFC 2822-based message documents. Send mail using smtplib The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. If you are interested in browsing a remote mailbox (for example, to see if the message you sent have arrived), you need a mail service accessible via a known protocol. An popular example is the imaplib module, implementing the IMAP4 protocol. IMAP is supported by gmail. This (imaplib) module defines three classes, IMAP4, IMAP4_SSL and IMAP4_stream, which encapsulate a connection to an IMAP4 server and implement a large subset of the IMAP4rev1 client protocol as defined in RFC 2060. It is backward compatible with IMAP4 (RFC 1730) servers, but note that the STATUS command is not supported in IMAP4. A: If you want the Python standard library to do the work for you (recommended!), use smtplib. To see whether sending the mail worked, just open your inbox ;) If you want to implement the protocol yourself (is this homework?), then read up on the SMTP protocol and use e.g. the socket module. A: Depends what you mean by "received". It's possible to verify "delivery" of a message to a server but there is no 100% reliable guarantee it actually ended up in a mailbox. smtplib will throw an exception on certain conditions (like the remote end reporting user not found) but just as often the remote end will accept the mail and then either filter it or send a bounce notice at a later time.
How would one build an smtp client in python?
buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!
[ "Create mail messages (possibly with multipart attachments) with email.\n\nThe email package is a library for managing email messages, including MIME and other RFC 2822-based message documents.\n\nSend mail using smtplib\n\nThe smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.\n\nIf you are interested in browsing a remote mailbox (for example, to see if the message you sent have arrived), you need a mail service accessible via a known protocol. An popular example is the imaplib module, implementing the IMAP4 protocol. IMAP is supported by gmail.\n\nThis (imaplib) module defines three classes, IMAP4, IMAP4_SSL and IMAP4_stream, which encapsulate a connection to an IMAP4 server and implement a large subset of the IMAP4rev1 client protocol as defined in RFC 2060. It is backward compatible with IMAP4 (RFC 1730) servers, but note that the STATUS command is not supported in IMAP4.\n\n", "If you want the Python standard library to do the work for you (recommended!), use smtplib. To see whether sending the mail worked, just open your inbox ;)\nIf you want to implement the protocol yourself (is this homework?), then read up on the SMTP protocol and use e.g. the socket module.\n", "Depends what you mean by \"received\". It's possible to verify \"delivery\" of a message to a server but there is no 100% reliable guarantee it actually ended up in a mailbox. smtplib will throw an exception on certain conditions (like the remote end reporting user not found) but just as often the remote end will accept the mail and then either filter it or send a bounce notice at a later time.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python", "smtp" ]
stackoverflow_0000892196_python_smtp.txt
Q: filter with string return nothing I run into follow problem. Did I miss anything? Association.all().count() 1 Association.all().fetch(1) [Association(**{'server_url': u'server-url', 'handle': u'handle2', 'secret': 'c2VjcmV0\n', 'issued': 1242892477L, 'lifetime': 200L, 'assoc_type': u'HMAC-SHA1'})] Association.all().filter('server_url =', 'server-url').count() 0 # expect 1 Association.all().filter('server_url =', u'server-url').count() 0 # expect 1 Association.all().filter('issued >', 0).count() 1 A: What kind of property is "server_url"? If it is a TextProperty, then it cannot be used in filters. Unlike StringProperty, a TextProperty value can be more than 500 bytes long. However, TextProperty values are not indexed, and cannot be used in filters or sort orders. http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#TextProperty
filter with string return nothing
I run into follow problem. Did I miss anything? Association.all().count() 1 Association.all().fetch(1) [Association(**{'server_url': u'server-url', 'handle': u'handle2', 'secret': 'c2VjcmV0\n', 'issued': 1242892477L, 'lifetime': 200L, 'assoc_type': u'HMAC-SHA1'})] Association.all().filter('server_url =', 'server-url').count() 0 # expect 1 Association.all().filter('server_url =', u'server-url').count() 0 # expect 1 Association.all().filter('issued >', 0).count() 1
[ "What kind of property is \"server_url\"?\nIf it is a TextProperty, then it cannot be used in filters.\n\nUnlike StringProperty, a TextProperty\n value can be more than 500 bytes long.\n However, TextProperty values are not\n indexed, and cannot be used in filters\n or sort orders.\n\nhttp://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#TextProperty \n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000891935_google_app_engine_python.txt
Q: Python: Plugging wx.py.shell.Shell into a separate process I would like to create a shell which will control a separate process that I created with the multiprocessing module. Possible? How? EDIT: I have already achieved a way to send commands to the secondary process: I created a code.InteractiveConsole in that process, and attached it to an input queue and an output queue, so I can command the console from my main process. But I want it in a shell, probably a wx.py.shell.Shell, so a user of the program could use it. A: First create the shell Decouple the shell from your app by making its locals empty Create your code string Compile the code string and get a code object Execute the code object in the shell from wx.py.shell import Shell frm = wx.Frame(None) sh = Shell(frm) frm.Show() sh.interp.locals = {} codeStr = """ from multiprocessing import Process, Queue def f(q): q.put([42, None, 'hello']) q = Queue() p = Process(target=f, args=(q,)) p.start() print q.get() # prints "[42, None, 'hello']" p.join() """ code = compile(codeStr, '', 'exec') sh.interp.runcode(code) Note: The codeStr I stole from the first poster may not work here due to some pickling issues. But the point is you can execute your own codeStr remotely in a shell. A: You can create a Queue which you pass to the separate process. From the Python Docs: from multiprocessing import Process, Queue def f(q): q.put([42, None, 'hello']) if __name__ == '__main__': q = Queue() p = Process(target=f, args=(q,)) p.start() print q.get() # prints "[42, None, 'hello']" p.join() EXAMPLE: In the wx.py.shell.Shell Docs the constructur parameters are given as __init__(self, parent, id, pos, size, style, introText, locals, InterpClass, startupScript, execStartupScript, *args, **kwds) I have not tried it, but locals might be a dictionary of local variables, which you can pass to the shell. So, I would try the following: def f(cmd_queue): shell = wx.py.shell.Shell(parent, id, pos, size, style, introText, locals(), ...) q = Queue() p = Process(target=f, args=(q,)) p.start() Inside the shell, you should then be able to put your commands into cmd_queue which have then to be read in the parent process to be executed.
Python: Plugging wx.py.shell.Shell into a separate process
I would like to create a shell which will control a separate process that I created with the multiprocessing module. Possible? How? EDIT: I have already achieved a way to send commands to the secondary process: I created a code.InteractiveConsole in that process, and attached it to an input queue and an output queue, so I can command the console from my main process. But I want it in a shell, probably a wx.py.shell.Shell, so a user of the program could use it.
[ "\nFirst create the shell \nDecouple the shell from your app by making its locals empty\nCreate your code string\nCompile the code string and get a code object\nExecute the code object in the shell\n\n\n from wx.py.shell import Shell\n\n frm = wx.Frame(None)\n sh = Shell(frm)\n frm.Show() \n sh.interp.locals = {}\n codeStr = \"\"\"\n from multiprocessing import Process, Queue\n\n def f(q):\n q.put([42, None, 'hello'])\n\n q = Queue() \n p = Process(target=f, args=(q,))\n p.start()\n print q.get() # prints \"[42, None, 'hello']\"\n p.join()\n \"\"\"\n\n code = compile(codeStr, '', 'exec')\n sh.interp.runcode(code)\n\n\nNote:\nThe codeStr I stole from the first poster may not work here due to some pickling issues. But the point is you can execute your own codeStr remotely in a shell.\n", "You can create a Queue which you pass to the separate process. From the Python Docs:\nfrom multiprocessing import Process, Queue\n\ndef f(q):\n q.put([42, None, 'hello'])\n\nif __name__ == '__main__':\n q = Queue()\n p = Process(target=f, args=(q,))\n p.start()\n print q.get() # prints \"[42, None, 'hello']\"\n p.join()\n\nEXAMPLE: In the wx.py.shell.Shell Docs the constructur parameters are given as\n__init__(self, parent, id, pos, size, style, introText, locals, \n InterpClass, startupScript, execStartupScript, *args, **kwds) \n\nI have not tried it, but locals might be a dictionary of local variables, which you can pass to the shell. So, I would try the following:\ndef f(cmd_queue):\n shell = wx.py.shell.Shell(parent, id, pos, size, style, introText, locals(),\n ...)\n\nq = Queue()\np = Process(target=f, args=(q,))\np.start()\n\nInside the shell, you should then be able to put your commands into cmd_queue which have then to be read in the parent process to be executed.\n" ]
[ 1, 0 ]
[]
[]
[ "multiprocessing", "python", "shell", "wxpython" ]
stackoverflow_0000865082_multiprocessing_python_shell_wxpython.txt
Q: How to make a dynamic array with different values in Python I have rows in file like : 20040701 0 20040701 0 1 52.965366 61.777687 57.540783 I want to put that in a dynamic array if it's possible ? Something like try: clients = [ (107, "Ella", "Fitzgerald"), (108, "Louis", "Armstrong"), (109, "Miles", "Davis") ] cur.executemany("INSERT INTO clients (id, firstname, lastname) \ VALUES (?, ?, ?)", clients ) except: pass A: You can easily make a list of numbers from a string like your first example, just [float(x) for x in thestring.split()] -- but the "Something like" is nothing like the first example and appears to have nothing to do with the question's Subject. A: In [1]: s = "20040701 0 20040701 0 1 52.965366 61.777687 57.540783" In [2]: strings = s.split(" ") In [3]: strings Out[3]: ['20040701', '0', '20040701', '0', '1', '52.965366', '61.777687', '57.540783'] In [6]: tuple(strings) Out[6]: ('20040701', '0', '20040701', '0', '1', '52.965366', '61.777687', '57.540783') Is that the kind of thing you're looking for? I'm not certain from your question. A: From my reading for your question, I think you want something like: rows=[map(Decimal,x.split(' ')) for x in lines]
How to make a dynamic array with different values in Python
I have rows in file like : 20040701 0 20040701 0 1 52.965366 61.777687 57.540783 I want to put that in a dynamic array if it's possible ? Something like try: clients = [ (107, "Ella", "Fitzgerald"), (108, "Louis", "Armstrong"), (109, "Miles", "Davis") ] cur.executemany("INSERT INTO clients (id, firstname, lastname) \ VALUES (?, ?, ?)", clients ) except: pass
[ "You can easily make a list of numbers from a string like your first example, just [float(x) for x in thestring.split()] -- but the \"Something like\" is nothing like the first example and appears to have nothing to do with the question's Subject.\n", "In [1]: s = \"20040701 0 20040701 0 1 52.965366 61.777687 57.540783\"\n\nIn [2]: strings = s.split(\" \")\n\nIn [3]: strings\nOut[3]: ['20040701', '0', '20040701', '0', '1', '52.965366', '61.777687', '57.540783']\n\nIn [6]: tuple(strings)\nOut[6]: ('20040701', '0', '20040701', '0', '1', '52.965366', '61.777687', '57.540783')\n\nIs that the kind of thing you're looking for? I'm not certain from your question.\n", "From my reading for your question, I think you want something like:\nrows=[map(Decimal,x.split(' ')) for x in lines]\n" ]
[ 2, 2, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0000893143_python_sqlite.txt
Q: Python doctest fails on 0.0 != -0.0--what gives? Given the following code: def slope(x1, y1, x2, y2): """ >>> slope(5, 3, 4, 2) 1.0 >>> slope(1, 2, 3, 2) 0.0 >>> slope(1, 2, 3, 3) 0.5 >>> slope(2, 4, 1, 2) 2.0 """ xa = float (x1) xb = float (x2) ya = float (y1) yb = float (y2) return (ya-yb)/(xa-xb) if name_ == '__main__': import doctest doctest.testmod() The second doctest fails: Failed example: slope(1, 2, 3, 2) Expected: 0.0 Got: -0.0 However, we all know that -0.0 == 0.0. Is doctest doing a string comparison to check results here? Why does the second test fail? A: It fails because doctest does string comparison. It merely checks whether the output is identical to what would have been outputted if the code had been executed at the Python interactive interpreter: >>> 0 / -2 -0.0 Edit:: The link referenced by Daniel Lew below gives some more hints about how this works, and how you may be able to influence this behaviour.
Python doctest fails on 0.0 != -0.0--what gives?
Given the following code: def slope(x1, y1, x2, y2): """ >>> slope(5, 3, 4, 2) 1.0 >>> slope(1, 2, 3, 2) 0.0 >>> slope(1, 2, 3, 3) 0.5 >>> slope(2, 4, 1, 2) 2.0 """ xa = float (x1) xb = float (x2) ya = float (y1) yb = float (y2) return (ya-yb)/(xa-xb) if name_ == '__main__': import doctest doctest.testmod() The second doctest fails: Failed example: slope(1, 2, 3, 2) Expected: 0.0 Got: -0.0 However, we all know that -0.0 == 0.0. Is doctest doing a string comparison to check results here? Why does the second test fail?
[ "It fails because doctest does string comparison. It merely checks whether the output is identical to what would have been outputted if the code had been executed at the Python interactive interpreter:\n>>> 0 / -2\n-0.0\n\nEdit:: The link referenced by Daniel Lew below gives some more hints about how this works, and how you may be able to influence this behaviour.\n" ]
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0000893398_python.txt
Q: Dynamically specifying tags while using replaceWith in Beautiful Soup Previously I asked this question and got back this BeautifulSoup example code, which after some consultation locally, I decided to go with. >>> from BeautifulSoup import BeautifulStoneSoup >>> html = """ ... <config> ... <links> ... <link name="Link1" id="1"> ... <encapsulation> ... <mode>ipsec</mode> ... </encapsulation> ... </link> ... <link name="Link2" id="2"> ... <encapsulation> ... <mode>udp</mode> ... </encapsulation> ... </link> ... </links> ... </config> ... """ >>> soup = BeautifulStoneSoup(html) >>> soup.find('link', id=1) <link name="Link1" id="1"> <encapsulation> <mode>ipsec</mode> </encapsulation> </link> >>> soup.find('link', id=1).mode.contents[0].replaceWith('whatever') >>> soup.find('link', id=1) <link name="Link1" id="1"> <encapsulation> <mode>whatever</mode> </encapsulation> </link> The only problem with this is that the example has a hardcoded tag value (in this case "mode"), and I need to be able to specify any tag within the specified "link" tag. Simple variable substitution doesn't seem to work. A: Try getattr(soup.find('link', id=1), sometag) where you now have a hardcoded tag in soup.find('link', id=1).mode -- getattr is the Python way to get an attribute whose name is held as a string variable, after all! A: No need to use getattr: sometag = 'mode' result = soup.find('link', id=1).find(sometag) print result
Dynamically specifying tags while using replaceWith in Beautiful Soup
Previously I asked this question and got back this BeautifulSoup example code, which after some consultation locally, I decided to go with. >>> from BeautifulSoup import BeautifulStoneSoup >>> html = """ ... <config> ... <links> ... <link name="Link1" id="1"> ... <encapsulation> ... <mode>ipsec</mode> ... </encapsulation> ... </link> ... <link name="Link2" id="2"> ... <encapsulation> ... <mode>udp</mode> ... </encapsulation> ... </link> ... </links> ... </config> ... """ >>> soup = BeautifulStoneSoup(html) >>> soup.find('link', id=1) <link name="Link1" id="1"> <encapsulation> <mode>ipsec</mode> </encapsulation> </link> >>> soup.find('link', id=1).mode.contents[0].replaceWith('whatever') >>> soup.find('link', id=1) <link name="Link1" id="1"> <encapsulation> <mode>whatever</mode> </encapsulation> </link> The only problem with this is that the example has a hardcoded tag value (in this case "mode"), and I need to be able to specify any tag within the specified "link" tag. Simple variable substitution doesn't seem to work.
[ "Try getattr(soup.find('link', id=1), sometag) where you now have a hardcoded tag in soup.find('link', id=1).mode -- getattr is the Python way to get an attribute whose name is held as a string variable, after all!\n", "No need to use getattr:\nsometag = 'mode'\nresult = soup.find('link', id=1).find(sometag)\nprint result\n\n" ]
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "python", "xml" ]
stackoverflow_0000891434_beautifulsoup_python_xml.txt
Q: How to define a system-wide alias for a Python script? I am working on Mac OS X and I have a Python script which is going to be called by other scripts and programs (Apple's launchd in particular). I could call it with python /Users/xyz/long/absolute/path/to/script.py arg1 arg2 Since the location of the script might change, I want to decouple other scripts and the launchd configuration files from the actual location, so that a call to the script looks like script arg1 arg2 Defining an alias for Bash in $HOME/.bash_profile does not work, since launchd does not know about the alias. What is the best way to define a "sytem-wide alias" or something equivalent? A: I usually make a symbolic link and put it in /usr/bin (assuming /usr/bin is part of your PATH) (In a terminal. You may have to use sudo ln -s depending on the permissions. ln -s /Users/xyz/long/absolute/path/to/script.py /usr/bin/script.py If you take Rory's advice and put the #!/usr/bin/python at the beginning of the script, you'll also need to make the script executable. chmod a+x /Users/xyz/long/absolute/path/to/script.py A: As well as doing a symlink, you can put "#! /path/to/python" at the start of the script and make it executabe. Then you don't have to call it with "python /Users/big/long/path/script.py"
How to define a system-wide alias for a Python script?
I am working on Mac OS X and I have a Python script which is going to be called by other scripts and programs (Apple's launchd in particular). I could call it with python /Users/xyz/long/absolute/path/to/script.py arg1 arg2 Since the location of the script might change, I want to decouple other scripts and the launchd configuration files from the actual location, so that a call to the script looks like script arg1 arg2 Defining an alias for Bash in $HOME/.bash_profile does not work, since launchd does not know about the alias. What is the best way to define a "sytem-wide alias" or something equivalent?
[ "I usually make a symbolic link and put it in /usr/bin (assuming /usr/bin is part of your PATH)\n(In a terminal. You may have to use sudo ln -s depending on the permissions.\nln -s /Users/xyz/long/absolute/path/to/script.py /usr/bin/script.py\n\nIf you take Rory's advice and put the #!/usr/bin/python at the beginning of the script, you'll also need to make the script executable.\nchmod a+x /Users/xyz/long/absolute/path/to/script.py\n\n", "As well as doing a symlink, you can put \"#! /path/to/python\" at the start of the script and make it executabe. Then you don't have to call it with \"python /Users/big/long/path/script.py\"\n" ]
[ 6, 3 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0000893543_macos_python.txt
Q: Replacing Microsoft Word Newline Character in Python This feels like it should be an easy one, but I'm having trouble cleaning out the newline character in content pasted from Microsoft Word. Not a full line-break, but the CTRL ENTER character that shows up as a return arrow in Word. I've tried chr(10), chr(13), \u000D, \u000A and a few others, but I can't match it in a string.replace(). Should I be looking for a different character or do I need to use something other than the string.replace method? A: Run this: print repr(mystringobject) That will give a hint of which character you want to remove. If still no clue, paste the result of the command above in the question, and I'll edit my answer. A: you can get the ASCII value of the character like this: for c in 'string': print ord(c), hex(ord(c)) once you know the code, it should be easy to kill the offender.
Replacing Microsoft Word Newline Character in Python
This feels like it should be an easy one, but I'm having trouble cleaning out the newline character in content pasted from Microsoft Word. Not a full line-break, but the CTRL ENTER character that shows up as a return arrow in Word. I've tried chr(10), chr(13), \u000D, \u000A and a few others, but I can't match it in a string.replace(). Should I be looking for a different character or do I need to use something other than the string.replace method?
[ "Run this:\nprint repr(mystringobject)\n\nThat will give a hint of which character you want to remove.\nIf still no clue, paste the result of the command above in the question, and I'll edit my answer.\n", "you can get the ASCII value of the character like this:\nfor c in 'string':\n print ord(c), hex(ord(c))\n\nonce you know the code, it should be easy to kill the offender.\n" ]
[ 4, 2 ]
[]
[]
[ "ms_word", "python", "sanitize" ]
stackoverflow_0000893514_ms_word_python_sanitize.txt
Q: Python PySerial readline function wrong use I'm using a script importing PySerial to read from COM4 messages I would like to intercept end with a couple of # so I tried to use bus.readline(eol='##') where bus is my connection. I expected to read like: *#*3## *#*3## *#*3## Unfortunalyy I found also *#*1##*1*1*99## that I expected to read spleetted into 2 lines *#*1## *1*1*99## Clearly readline is not working but why? A: The readline() method in pyserial reads one character at a time and compares it to the EOL character. You cannot specify multiple characters as the EOL. You'll have to read in and then split later using string.split() or re.split()
Python PySerial readline function wrong use
I'm using a script importing PySerial to read from COM4 messages I would like to intercept end with a couple of # so I tried to use bus.readline(eol='##') where bus is my connection. I expected to read like: *#*3## *#*3## *#*3## Unfortunalyy I found also *#*1##*1*1*99## that I expected to read spleetted into 2 lines *#*1## *1*1*99## Clearly readline is not working but why?
[ "The readline() method in pyserial reads one character at a time and compares it to the EOL character. You cannot specify multiple characters as the EOL. You'll have to read in and then split later using string.split() or re.split()\n" ]
[ 3 ]
[]
[]
[ "pyserial", "python" ]
stackoverflow_0000893747_pyserial_python.txt
Q: Programmatically make HTTP requests through proxies with Python How do I use Python to make an HTTP request through a proxy? What do I need to do to the following code? urllib.urlopen('http://www.google.com') A: The urlopen function supports proxies. Try something like this: urllib.urlopen(your_url, proxies = {"http" : "http://192.168.0.1:80"}) A: You could look at PycURL. I use cURL a lot in PHP and i love it. Though there is probably a neat way to do this currently in Python.
Programmatically make HTTP requests through proxies with Python
How do I use Python to make an HTTP request through a proxy? What do I need to do to the following code? urllib.urlopen('http://www.google.com')
[ "The urlopen function supports proxies. Try something like this:\nurllib.urlopen(your_url, proxies = {\"http\" : \"http://192.168.0.1:80\"})\n\n", "You could look at PycURL. I use cURL a lot in PHP and i love it. Though there is probably a neat way to do this currently in Python.\n" ]
[ 6, 1 ]
[]
[]
[ "http", "proxy", "python" ]
stackoverflow_0000894168_http_proxy_python.txt
Q: Send emails from Google App Engine I have a web server with Django, hosted with Apache server. I would like to configure Google App Engine for the email server. My web server should be able to use Google App Engine, when it makes any email send using EmailMessage or sendmail infrastructure of Google Mail API. I learnt that by using Remote API, I can access Google App Engine server from my main web server. However, I could not access the Mail APIs supported by Google App Engine. Is the Remote API strictly for Datastore? If so, can only the DB read from it and no other API calls can? A: The example code for the remote APi gives you an interactive console from which you can access any of the modules in your application. I see no requirement that they be only datastore operations. A: You may want to use a third-party SMTP relaying service. Here's a list. Most of them have a simple API that lets you forward your email to their service. That way, you're not bound by the AppEngine's limits. The more reputable ones also take care of headers necessary so your app isn't tagged as a spam sender (which hopefully, it isn't :-)
Send emails from Google App Engine
I have a web server with Django, hosted with Apache server. I would like to configure Google App Engine for the email server. My web server should be able to use Google App Engine, when it makes any email send using EmailMessage or sendmail infrastructure of Google Mail API. I learnt that by using Remote API, I can access Google App Engine server from my main web server. However, I could not access the Mail APIs supported by Google App Engine. Is the Remote API strictly for Datastore? If so, can only the DB read from it and no other API calls can?
[ "The example code for the remote APi gives you an interactive console from which you can access any of the modules in your application. I see no requirement that they be only datastore operations.\n", "You may want to use a third-party SMTP relaying service. Here's a list.\nMost of them have a simple API that lets you forward your email to their service. That way, you're not bound by the AppEngine's limits. The more reputable ones also take care of headers necessary so your app isn't tagged as a spam sender (which hopefully, it isn't :-)\n" ]
[ 2, 0 ]
[]
[]
[ "django", "google_app_engine", "mail_server", "python" ]
stackoverflow_0000892266_django_google_app_engine_mail_server_python.txt
Q: Is there free wiki source code that will run on the Google App Engine? I found the sample code cccwiki which is good, but I would like a wiki that keeps tracks of all revisions to the pages and lets users show diffs and revert to previous versions. A: You can start with http://code.google.com/p/google-app-engine-samples/downloads/detail?name=cccwiki_20080409.tar.gz&can=2&q= which is exactly "A simple Google App Engine wiki application" for you to download, try, and modify as you want. You can also browse its sources online at http://code.google.com/p/google-app-engine-samples/source/browse/trunk/cccwiki/ . A: Someone pointed me to pickywiki. I'll give it a try.
Is there free wiki source code that will run on the Google App Engine?
I found the sample code cccwiki which is good, but I would like a wiki that keeps tracks of all revisions to the pages and lets users show diffs and revert to previous versions.
[ "You can start with http://code.google.com/p/google-app-engine-samples/downloads/detail?name=cccwiki_20080409.tar.gz&can=2&q= which is exactly \"A simple Google App Engine wiki application\" for you to download, try, and modify as you want. You can also browse its sources online at http://code.google.com/p/google-app-engine-samples/source/browse/trunk/cccwiki/ .\n", "Someone pointed me to pickywiki. I'll give it a try.\n" ]
[ 0, 0 ]
[]
[]
[ "google_app_engine", "open_source", "python", "wiki" ]
stackoverflow_0000882454_google_app_engine_open_source_python_wiki.txt