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: Passing dictionaries to a Python script through the command line How can I pass a dictionary to a python script from another python script over the command line? I use subprocess to call the second script. The options I've come to are: I) Build a module to parse a dictionary from a string (more in-depth than I had hoped to go). II) Use a temporary file to write a pickle, and pass the file's name as an argument III) Don't allow dictionaries, but handle key/value pairs (that is "prog.py keya valuea keyb valub") The solution does not have to be user-friendly, but does need to be program friendly. The second program must be run as a separate process, due to security and resource concerns. A: Have you looked at the pickle module to pass the data over stdout/stdin? Example: knights.py: import pickle import sys desires = {'say': 'ni', 'obtain': 'shrubbery'} pickle.dump(desires, sys.stdout) roundtable.py: import pickle import sys knightsRequest = pickle.load(sys.stdin) for req in knightsRequest: print "The knights %s %s." % (req, knightsRequest[req]) Usage and output: $ python knights.py | python roundtable.py The knights say ni. The knights obtain shrubbery. A: If you don't need a too terribly complicated data structure, might I recommend simplejson? It's available as a built-in module (called json) in Python 2.6 and later. A: Aside from pickle, another option is ast.literal_eval, if your dictionaries only contain Python primitives. >>> d = {3: 9, 'apple': 'orange'} >>> s = str(d) >>> s "{3: 9, 'apple': 'orange'}" >>> import ast >>> x = ast.literal_eval(s) >>> x {3: 9, 'apple': 'orange'} A: If what's in the dictionary (both keys and values) can be represented as strings, you should be able to pass it as a string argument to the second script which can recreate it. d = {'a':1,'b':2} d == eval(repr(d), None) >>>True Edit: Here's a slightly more involved example showing its use with a simple custom class: class MyClass: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return 'MyClass(%r, %r)' % (self.a, self.b) def __eq__(self, other): return (self.a == other.a) and (self.b == other.b) d = {'foo':42, 'bar': MyClass(17,'astring') } print 'd:', d print 'repr(d):', repr(d) print "d == eval(repr(d), {'MyClass':MyClass})?:", \ d == eval(repr(d), {'MyClass':MyClass}) # outputs: # d: {'foo': 42, 'bar': MyClass(17, 'astring')} # repr(d): {'foo': 42, 'bar': MyClass(17, 'astring')} # d == eval(repr(d), {'MyClass':MyClass})?: True A: How about xmlrpc? Client http://docs.python.org/library/xmlrpclib.html Server http://docs.python.org/library/simplexmlrpcserver.html Both are in python core. A: Just print the dictionary in one python script print( "dict=" + str(dict) ) and use it as (python script1.py; cat script2.py) | python - and now you should be able access the dictionary through global variable 'dict' in the second python script.
Passing dictionaries to a Python script through the command line
How can I pass a dictionary to a python script from another python script over the command line? I use subprocess to call the second script. The options I've come to are: I) Build a module to parse a dictionary from a string (more in-depth than I had hoped to go). II) Use a temporary file to write a pickle, and pass the file's name as an argument III) Don't allow dictionaries, but handle key/value pairs (that is "prog.py keya valuea keyb valub") The solution does not have to be user-friendly, but does need to be program friendly. The second program must be run as a separate process, due to security and resource concerns.
[ "Have you looked at the pickle module to pass the data over stdout/stdin? \nExample:\nknights.py:\nimport pickle\nimport sys\n\ndesires = {'say': 'ni', 'obtain': 'shrubbery'}\npickle.dump(desires, sys.stdout)\n\nroundtable.py:\nimport pickle\nimport sys\n\nknightsRequest = pickle.load(sys.stdin)\nfor req in knights...
[ 9, 6, 6, 2, 0, 0 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0003780468_command_line_python.txt
Q: Integrating a script language into a C++ application I'm really new to C++ and I've come across a problem I've not been able to solve by reading documentations. I want to embed a script language into my c++ application. That language could be javascript, lua or preferably python. I'm not looking for something like Boost.Python / swig, something that is able to wrap my c++ functions / classes to a python interface, but rather a python_evaluate_and_return_result_as_variable("my_code"); function. I have a whole bunch of structs containing a few integers: struct my_integers { int a; int b; int c; int d; int e; }; Now I want to do some math with these integers, for example: i.a = i.c * i.e; The math I want to do will be changing a lot in the future and I need people other then me be able to change the math without having access to the c++ code. I'm thinking about a code structure like this: I initialize my struct and fill it with the starting values I load an external python function, lets say "my_python_function", that takes the struct as an argument and does so math with it before returning it. I get my struct like i = my_python_function_cppwrapper(i) Is something like that possible? I googled a lot for this but the only thing I seem to find are wrappers that provide c++ -> python (or the other way around) functionallity without really interacting with variables. I'd be really thankful for any help, Robin. A: The Python documentation has a page on embedding Python in a C or C++ application. A: Why not use Boost.Python? You can expose your data classes to Python and execute a script/function as described here. A: If you want to simply run Python scripts from C/C++, then use the Python C API. In your C/C++ code: PyRun_SimpleString("import math; x = math.sqrt(2 * 2)"); For more complicated things, you will have to look at the API docs, but it's pretty straightforward. A: How about embedding a JavaScript engine, such as V8? A: dont forget the grand-daddy of embedded scripting language - tcl. tcl has v nice c++ wrapper (modelled on boost.python) that makes it trivial to invoke and to wire up callbacks to your code A: Lua works pretty well too, especially since its small, is ansi c compliant, has a low memory foot print along with a great wiki and messaging list. If you need even more speed there is a x86 32 and 64 bit jit version(luajit). Binding can be done with an array of tools/libraries, like swig or lunar(the wiki lists them all). The only problem that i can see is binding the struct members so they can be referenced directly(ie: struct.member = 4), though its possible to set this up with metatables that have get and set methods bound to variable names A: You say that you're not looking for something to wrap your C++ functions / classes in a Python interface, but if you want Python code to be able to refer to members of your C++ my_integers structure, that is wrapping C++ classes in a Python interface. Of course, you're free to wrap as many or as few classes as you want - in this example, you'd wrap my_integers, then you'd embed a Python interpreter to do stuff with my_integers. A: For something as simple as you describe, you could implement an interpreter for your own 'little language'. You could even call it the "Robin" language. ;-) A: I advice using Lua as internal scripting engine. Implementation is just a few lines, and though light, the language has sufficient power. So no need for TCL. You might as well look at python, integration in C++ is rather easy, as there exists a Boost.Python implementation facilitating integration. But depending on the application, I'd still recommend Lua.
Integrating a script language into a C++ application
I'm really new to C++ and I've come across a problem I've not been able to solve by reading documentations. I want to embed a script language into my c++ application. That language could be javascript, lua or preferably python. I'm not looking for something like Boost.Python / swig, something that is able to wrap my c++ functions / classes to a python interface, but rather a python_evaluate_and_return_result_as_variable("my_code"); function. I have a whole bunch of structs containing a few integers: struct my_integers { int a; int b; int c; int d; int e; }; Now I want to do some math with these integers, for example: i.a = i.c * i.e; The math I want to do will be changing a lot in the future and I need people other then me be able to change the math without having access to the c++ code. I'm thinking about a code structure like this: I initialize my struct and fill it with the starting values I load an external python function, lets say "my_python_function", that takes the struct as an argument and does so math with it before returning it. I get my struct like i = my_python_function_cppwrapper(i) Is something like that possible? I googled a lot for this but the only thing I seem to find are wrappers that provide c++ -> python (or the other way around) functionallity without really interacting with variables. I'd be really thankful for any help, Robin.
[ "The Python documentation has a page on embedding Python in a C or C++ application.\n", "Why not use Boost.Python? You can expose your data classes to Python and execute a script/function as described here.\n", "If you want to simply run Python scripts from C/C++, then use the Python C API. In your C/C++ code:...
[ 8, 8, 6, 2, 1, 1, 1, 1, 1 ]
[]
[]
[ "c++", "embedding", "python", "scripting" ]
stackoverflow_0003780398_c++_embedding_python_scripting.txt
Q: Creating lists using yield in Ruby and Python I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby. In Python: def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) In Ruby: def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| result << x} Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's yield results in simple iteration, which is great. Ruby's yield invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky. Is there a more elegant Ruby way? UPDATE Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x. A: So, for your new example, try this: def foo(x) (0..x).select { |i| bar(i) } end Basically, unless you're writing an iterator of your own, you don't need yield very often in Ruby. You'll probably do a lot better if you stop trying to write Python idioms using Ruby syntax. A: For the Python version I would use a generator expression like: (i for i in range(x) if bar(i)) Or for this specific case of filtering values, even more simply itertools.ifilter(bar,range(x)) A: The exact equivalent of your Python code (using Ruby Generators) would be: def foo(x) Enumerator.new do |yielder| (0..x).each { |v| yielder.yield(v) if bar(v) } end end result = Array(foo(100)) In the above, the list is lazily generated (just as in the Python example); see: def bar(v); v % 2 == 0; end f = foo(100) f.next #=> 0 f.next #=> 2 A: I know it's not exactly what you were looking for, but a more elegant way to express your example in ruby is: result = Array.new(100) {|x| x*x} A: def squares(x) (0..x).map { |i| i * i } end Anything involving a range of values is best handled with, well, a range, rather than times and array generation. A: For the Python list comprehension version posted by stbuton use xrange instead of range if you want a generator. range will create the entire list in memory. A: yield means different things ruby and python. In ruby, you have to specify a callback block if I remember correctly, whereas generators in python can be passed around and yield to whoever holds them.
Creating lists using yield in Ruby and Python
I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby. In Python: def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) In Ruby: def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| result << x} Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's yield results in simple iteration, which is great. Ruby's yield invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky. Is there a more elegant Ruby way? UPDATE Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x.
[ "So, for your new example, try this:\ndef foo(x)\n (0..x).select { |i| bar(i) }\nend\n\nBasically, unless you're writing an iterator of your own, you don't need yield very often in Ruby. You'll probably do a lot better if you stop trying to write Python idioms using Ruby syntax.\n", "For the Python version I wo...
[ 10, 7, 5, 1, 1, 1, 1 ]
[]
[]
[ "list", "python", "ruby", "yield" ]
stackoverflow_0000608951_list_python_ruby_yield.txt
Q: How can I replace the class by monkey patching? How can I replace the ORM class - so it should not cause recursion !!! Problem: original class has the super call, when its got replaced - it causes self inheritance and causes maximum recursion depth exceed exception. i.e. class orm is calling super(orm, self).... and orm has been replaced by another class which inherits original orm.... Package ! addons __init__.py osv run_app.py ./addons: __init__.py test_app1.py test.py ./osv: __init__.py orm.py contents of orm.py class orm_template(object): def __init__(self, *args, **kw): super(orm_template, self).__init__() def fields_get(self, fields): return fields def browse(self, id): return id class orm(orm_template): def __init__(self, *args, **kw): super(orm, self).__init__(*args, **kw) def fields_get(self, fields, context = None): return super(orm, self).fields_get(fields) def read(self, fields): return fields contents of addons/init.py import test def main(app): print "Running..." __import__(app, globals(), locals()) contents of addons/test.py from osv import orm import osv class orm(orm.orm): def __init__(self, *args, **kw): super(orm, self).__init__(*args, **kw) def fields_get(self, *args, **kw): print "my fields get................." return super(orm, self).fields_get(*args, **kw) osv.orm.orm = orm print "replaced.........................." contents of test_app1.py from osv.orm import orm class hello(orm): _name = 'hellos' def __init__(self, *args, **kw): super(hello, self).__init__(*args, **kw) print hello('test').fields_get(['name']) contents of run_app.py import addons addons.main('test_app1') OUTPUT >>>python run_app.py replaced.......................... Running... ... ... super(orm, self).__init__(*args, **kw) RuntimeError: maximum recursion depth exceeded I've seen the similar question A: Your addons/test.py needs to get and keep a reference to the original orm.orm and use that instead of the replaced version. I.e.: from osv import orm import osv original_orm = osv.orm class orm(original_orm): def __init__(self, *args, **kw): super(orm, self).__init__(*args, **kw) def fields_get(self, *args, **kw): print "my fields get................." return super(orm, self).fields_get(*args, **kw) osv.orm.orm = orm print "replaced.........................." so the monkeypatched-in class inherit from the original rather than from itself, as you had it in your setup. BTW, if you can avoid monkey-patching by better design of the osv module (e.g. w/a setter function to set what's the orm) you'll be happier;-).
How can I replace the class by monkey patching?
How can I replace the ORM class - so it should not cause recursion !!! Problem: original class has the super call, when its got replaced - it causes self inheritance and causes maximum recursion depth exceed exception. i.e. class orm is calling super(orm, self).... and orm has been replaced by another class which inherits original orm.... Package ! addons __init__.py osv run_app.py ./addons: __init__.py test_app1.py test.py ./osv: __init__.py orm.py contents of orm.py class orm_template(object): def __init__(self, *args, **kw): super(orm_template, self).__init__() def fields_get(self, fields): return fields def browse(self, id): return id class orm(orm_template): def __init__(self, *args, **kw): super(orm, self).__init__(*args, **kw) def fields_get(self, fields, context = None): return super(orm, self).fields_get(fields) def read(self, fields): return fields contents of addons/init.py import test def main(app): print "Running..." __import__(app, globals(), locals()) contents of addons/test.py from osv import orm import osv class orm(orm.orm): def __init__(self, *args, **kw): super(orm, self).__init__(*args, **kw) def fields_get(self, *args, **kw): print "my fields get................." return super(orm, self).fields_get(*args, **kw) osv.orm.orm = orm print "replaced.........................." contents of test_app1.py from osv.orm import orm class hello(orm): _name = 'hellos' def __init__(self, *args, **kw): super(hello, self).__init__(*args, **kw) print hello('test').fields_get(['name']) contents of run_app.py import addons addons.main('test_app1') OUTPUT >>>python run_app.py replaced.......................... Running... ... ... super(orm, self).__init__(*args, **kw) RuntimeError: maximum recursion depth exceeded I've seen the similar question
[ "Your addons/test.py needs to get and keep a reference to the original orm.orm and use that instead of the replaced version. I.e.:\nfrom osv import orm\nimport osv\noriginal_orm = osv.orm\nclass orm(original_orm):\n def __init__(self, *args, **kw):\n super(orm, self).__init__(*args, **kw) \n def fi...
[ 5 ]
[]
[]
[ "class", "monkeypatching", "python" ]
stackoverflow_0003781280_class_monkeypatching_python.txt
Q: Sort distributed couples from two lists Having two lists, I want to get all the possible couples. (a couple can be only one element from list 1 and another from list 2) If I do a double "foreach" statement, I get it immediately (I am using python): couples = [] for e1 in list_1: for e2 in list_2: couples.append([l1, l2]) How can I sort couples list in a way that elements be placed in a more distributed way? for example: list_1 = [a,b,c] list_2 = [1,2] I will get: [a, 1] [a, 2] [b, 1] [b, 2] [c, 1] [c, 2] And expect to be sorted to something like this: [a, 1] [b, 2] [c, 1] [a, 2] [b, 1] [c, 2] What algorithm should I use to get this results? A: You should check out itertools.product() from the stdlib. Edit: I meant product(), not permutations(). import itertools list_1 = ['a','b','c'] list_2 = [1,2] # To pair list_1 with list_2 paired = list(itertools.product(list_1, list_2)) # => [('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)] # To get the sorting you desired: wanted = sorted(paired, key=lambda x: x[1]) # [('a', 1), ('b', 1), ('c', 1), ('a', 2), ('b', 2), ('c', 2)] Since product() returns an iterator, you don't need to cast it to a list() (and with large lists you probably shouldn't.) I just added that for illustration in this example should decide to test it yourself and want to print the values. A: from itertools import islice, izip, cycle list_1 = ['a','b','c'] list_2 = [1,2] list(islice(izip(cycle(list_1), cycle(list_2)), len(list_1)*len(list_2))) Returns [('a', 1), ('b', 2), ('c', 1), ('a', 2), ('b', 1), ('c', 2)] A: To do the the way you want and you could flip the values: >>> z = [[k, l] for l in x for k in y] >>> z [[1, 'a'], [2, 'a'], [3, 'a'], [1, 'b'], [2, 'b'], [3, 'b'], [1, 'c'], [2, 'c'], [3, 'c']] >>> z.sort() >>> z [[1, 'a'], [1, 'b'], [1, 'c'], [2, 'a'], [2, 'b'], [2, 'c'], [3, 'a'], [3, 'b'], [3, 'c']] >>> T = [[x[1], x[0]] for x in z] >>> T [['a', 1], ['b', 1], ['c', 1], ['a', 2], ['b', 2], ['c', 2], ['a', 3], ['b', 3], ['c', 3]] A: In pseudo code (not pretty sure about python's syntax) : given list_1 of size n, and list_2 of size m: couples = [] for i=0 to n-1 for j=0 to m-1 couples.append( [ list_1[i], list_2[ (i+j) % m] ] )
Sort distributed couples from two lists
Having two lists, I want to get all the possible couples. (a couple can be only one element from list 1 and another from list 2) If I do a double "foreach" statement, I get it immediately (I am using python): couples = [] for e1 in list_1: for e2 in list_2: couples.append([l1, l2]) How can I sort couples list in a way that elements be placed in a more distributed way? for example: list_1 = [a,b,c] list_2 = [1,2] I will get: [a, 1] [a, 2] [b, 1] [b, 2] [c, 1] [c, 2] And expect to be sorted to something like this: [a, 1] [b, 2] [c, 1] [a, 2] [b, 1] [c, 2] What algorithm should I use to get this results?
[ "You should check out itertools.product() from the stdlib.\nEdit: I meant product(), not permutations().\nimport itertools\n\nlist_1 = ['a','b','c']\nlist_2 = [1,2]\n\n# To pair list_1 with list_2 \npaired = list(itertools.product(list_1, list_2))\n# => [('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)]\n...
[ 3, 3, 0, 0 ]
[]
[]
[ "algorithm", "python", "sorting" ]
stackoverflow_0003781342_algorithm_python_sorting.txt
Q: Are my permissions set correctly? (python) In python I'm doing a os.system('chmod o+w filename.png') command so I can overwrite the file with pngcrush. These are the permissions after I set them in python: -rw-rw-rw- 1 me users 925 Sep 20 11:25 filename.png Then I attempt: os.system('pngcrush filename.png filename.png') which is supposed to overwrite the file, but I get: Cannot overwrite input file filename.png What could be the problem? Isn't pngcrush being run as an 'other' user, for which write permissions are enabled? Thanks! A: The problem is with the way you execute the pngcrush program, not with permissions of filename.png or Python. It simply attempts to open filename.png both for input and output, which is of course invalid. Give pngcrush either the -e or the -d option to tell it how to write output. Read its man for more information. A: Perhaps pngcrush isn't letting you use the same name for both input and output files? Have you tried changing the output filename? If so, what were the results? A: As an aside (not related to the problem of the input and output files being the same), you can change the mode of a file using os.chmod, which is more efficient than running chmod: import os import stat path = "filename.png" mode = os.stat(path).st_mode # get current mode newmode = mode | stat.S_IWOTH # set the 'others can write' bit os.chmod(path, newmode) # set new mode A: Perhaps you're supposed to give a different (non-existing) filename for output. Have you tried the same in a shell?
Are my permissions set correctly? (python)
In python I'm doing a os.system('chmod o+w filename.png') command so I can overwrite the file with pngcrush. These are the permissions after I set them in python: -rw-rw-rw- 1 me users 925 Sep 20 11:25 filename.png Then I attempt: os.system('pngcrush filename.png filename.png') which is supposed to overwrite the file, but I get: Cannot overwrite input file filename.png What could be the problem? Isn't pngcrush being run as an 'other' user, for which write permissions are enabled? Thanks!
[ "The problem is with the way you execute the pngcrush program, not with permissions of filename.png or Python. It simply attempts to open filename.png both for input and output, which is of course invalid.\nGive pngcrush either the -e or the -d option to tell it how to write output. Read its man for more informatio...
[ 3, 2, 2, 0 ]
[]
[]
[ "file_permissions", "python" ]
stackoverflow_0003781302_file_permissions_python.txt
Q: why python doesn't need type declaration for python, other way what are the adv. of not declaring type? If we know the type of variable or parameter very well, why not to declare them? I'd like to know why it's bad or not necessary. Sorry, I'm new on Python (from about 1 year) and before I was on C, VB, VB.NET and C# programming languages. With Python, I hope to have bad parameter types to be catched at compilation time. And I hope to have an IDE that suggests me every attributes of a variable at design time. May be I'm too Microsoft minded, but variable type declaration seems to be the basic for me. A: I'm sure you know the + function. So, what is it's type? Numbers? Well, it works for lists and strings too. It even works for every object that defines __add__. Or in some cases when one object defines __radd__. So it's hard to tell the type of this function already. But Python makes it even possible to define these methods at runtime, for example through descriptors or a metaclass. You could even define them based on user input! Because Python is so highly dynamic, it's simply impossible for the Python compiler to figure out the type of anything (besides literals) without executing the program. So even if you wrote annotations, you would gain nothing, the type checking would still occur at runtime! A: Python uses Dynamic Typing (Duck Typing to be precise) and hence you need not declare a variable. It is a programming and style approach the Developers of Python have chosen. Being a high level language this approach fits into Pythons philosophy of easy readable code. There are other languages which follow this approach too. (PHP). A: That's the nature of dynamic languages. Static typing is the Java/C# style. (And even C# can infer type using var now.) It's a tradeoff: you're exchanging type safety for flexibility at runtime. A: Python is strongly-typed so a declaring variable's type is unnecessary. (For obvious reasons you must usually still declare variables!) The reason for this is because exceptions are raised if you try to do things to types that aren't supported, such as adding an integer to string: >>> foo = "Hello" >>> bar = 2 >>> foo + bar Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects Most other languages do not behave in this way and bad things can happen because of it.
why python doesn't need type declaration for python, other way what are the adv. of not declaring type?
If we know the type of variable or parameter very well, why not to declare them? I'd like to know why it's bad or not necessary. Sorry, I'm new on Python (from about 1 year) and before I was on C, VB, VB.NET and C# programming languages. With Python, I hope to have bad parameter types to be catched at compilation time. And I hope to have an IDE that suggests me every attributes of a variable at design time. May be I'm too Microsoft minded, but variable type declaration seems to be the basic for me.
[ "I'm sure you know the + function. So, what is it's type? Numbers? Well, it works for lists and strings too. It even works for every object that defines __add__. Or in some cases when one object defines __radd__. \nSo it's hard to tell the type of this function already. But Python makes it even possible to define t...
[ 10, 4, 3, 2 ]
[]
[]
[ "programming_languages", "python" ]
stackoverflow_0003781454_programming_languages_python.txt
Q: How to create new list of dicts in python by consolidating dicts in another list? In Python, I have a list of dicts as follows: orig_list = [ {'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'display_name': u'AVG', 'value': 7.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'display_name': u'AVG', 'value': 12.0}, {'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'display_name': u'AVG', 'value': 7.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'display_name': u'AVG', 'value': 12.0}, {'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo', 'display_name': u'AVG', 'value': 18.0}, {'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo', 'display_name': u'AVG', 'value': 18.0}, {'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne', 'display_name': u'AVG', 'value': 23.5}, {'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo', 'display_name': u'REC', 'value': 2.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'display_name': u'REC', 'value': 1.0}, {'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'display_name': u'REC', 'value': 1.0}, {'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne', 'display_name': u'REC', 'value': 2.0}, {'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne', 'display_name': u'TD', 'value': 1.0}, {'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo', 'display_name': u'YDS', 'value': 36.0}, {'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'display_name': u'YDS', 'value': 7.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'display_name': u'YDS', 'value': 12.0}, {'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne', 'display_name': u'YDS', 'value': 47.0}] I need to create a new list of dicts from the first list to find the unique names and for each name find all the display_name's and the values. In essence the result should be: [{'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'AVG': 7.0, 'REC': 1.0, 'YDS': 7.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'AVG': 12.0, 'REC': 1.0, 'YDS': 12.0}, {'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo', 'AVG': 18.0, 'REC': 2.0, 'YDS': 36.0}, {'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne', 'AVG': 23.5, 'REC': 2.0, 'TD': 1.0, 'YDS': 47.0}] I tried with nested for loops but kept getting an error that the "dict is unhashable." What is the best solution for this data structure? A: temp = {} for rec in orig_list: temp.setdefault((rec['first_name'], rec['last_name'], rec['team']), {}).setdefault(rec['display_name'], rec['value']) persons = [] for key, person in temp.iteritems(): person.update(dict(zip(('first_name', 'last_name', 'team'), key))) persons.append(person) A: Here is what I got using collections.defaultdict: from collections import defaultdict j = defaultdict(dict) for player in origlist: j[(player['first_name'],player['last_name'],player['team'])].update({player['display_name']: player['value']}) This gives me the following output for j.items(): [((u'Mike', u'Walsh', u'TeamTwo'), {u'AVG': 12.0, u'REC': 1.0, u'YDS': 12.0}), ((u'Jake', u'Sarson', u'TeamOne'), {u'AVG': 7.0, u'REC': 1.0, u'YDS': 7.0}), ((u'Steve', u'Mottola', u'TeamTwo'), {u'AVG': 18.0, u'REC': 2.0, u'YDS': 36.0}), ((u'Craig', u'Schubert', u'TeamOne'), {u'AVG': 23.5, u'REC': 2.0, u'TD': 1.0, u'YDS': 47.0})] From the j.items() then I go build the final list: nl0 = [] for k,v in j.items(): o = {'first_name': k[0], 'last_name': k[1], 'team': k[2]} o.update(v) nl0.append(o) o = {} And the result is what I need: [{u'AVG': 12.0, u'REC': 1.0, u'YDS': 12.0, 'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo'}, {u'AVG': 7.0, u'REC': 1.0, u'YDS': 7.0, 'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne'}, {u'AVG': 18.0, u'REC': 2.0, u'YDS': 36.0, 'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo'}, {u'AVG': 23.5, u'REC': 2.0, u'TD': 1.0, u'YDS': 47.0, 'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne'}] Is this a good example of how to use collections.defaultdict?
How to create new list of dicts in python by consolidating dicts in another list?
In Python, I have a list of dicts as follows: orig_list = [ {'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'display_name': u'AVG', 'value': 7.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'display_name': u'AVG', 'value': 12.0}, {'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'display_name': u'AVG', 'value': 7.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'display_name': u'AVG', 'value': 12.0}, {'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo', 'display_name': u'AVG', 'value': 18.0}, {'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo', 'display_name': u'AVG', 'value': 18.0}, {'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne', 'display_name': u'AVG', 'value': 23.5}, {'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo', 'display_name': u'REC', 'value': 2.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'display_name': u'REC', 'value': 1.0}, {'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'display_name': u'REC', 'value': 1.0}, {'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne', 'display_name': u'REC', 'value': 2.0}, {'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne', 'display_name': u'TD', 'value': 1.0}, {'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo', 'display_name': u'YDS', 'value': 36.0}, {'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'display_name': u'YDS', 'value': 7.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'display_name': u'YDS', 'value': 12.0}, {'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne', 'display_name': u'YDS', 'value': 47.0}] I need to create a new list of dicts from the first list to find the unique names and for each name find all the display_name's and the values. In essence the result should be: [{'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'AVG': 7.0, 'REC': 1.0, 'YDS': 7.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'AVG': 12.0, 'REC': 1.0, 'YDS': 12.0}, {'first_name': u'Steve', 'last_name': u'Mottola', 'team': u'TeamTwo', 'AVG': 18.0, 'REC': 2.0, 'YDS': 36.0}, {'first_name': u'Craig', 'last_name': u'Schubert', 'team': u'TeamOne', 'AVG': 23.5, 'REC': 2.0, 'TD': 1.0, 'YDS': 47.0}] I tried with nested for loops but kept getting an error that the "dict is unhashable." What is the best solution for this data structure?
[ "temp = {}\nfor rec in orig_list:\n temp.setdefault((rec['first_name'], rec['last_name'], rec['team']), {}).setdefault(rec['display_name'], rec['value'])\n\npersons = []\nfor key, person in temp.iteritems():\n person.update(dict(zip(('first_name', 'last_name', 'team'), key)))\n persons.append(person)\n\n",...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003770022_python.txt
Q: sqlalchemy REST serialization Reading the doc of sqlalchemy, i saw the serialization part. I'm wondering about a possibility to use an xml serializer for matching sa models with Rest webservices like Jax-RS There is a django extension which deal with that : django_roa Do you know if that kind of thing has already been developped for sqlalchemy or if is it possible to do it?? Thanks A: Its a long way till full RFC2616 compliance, but for a prototype, I do something like this: from sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relation, backref, sessionmaker from sqlalchemy.sql.expression import desc import web import json DB_PATH = 'sqlite:////tmp/test.db' Base = declarative_base() class LocalClient(Base): __tablename__ = 'local_clients' __jsonexport__ = ['id', 'name', 'password'] id = Column(Integer, primary_key=True) name = Column(String, unique=True, nullable=False) password = Column(String) def __init__(self, name, password): self.name = name self.password = password def __repr__(self): return "<LocalClient('%s', '%s')>" % (self.name, self.password) urls = ( '/a/LocalClient', 'LocalClientsController' ) class Encoder(json.JSONEncoder): '''This class contains the JSON serializer function for user defined types''' def default(self, obj): '''This function uses the __jsonexport__ list of relevant attributes to serialize the objects that inherits Base''' if isinstance(obj, Base): return dict(zip(obj.__jsonexport__, [getattr(obj, v) for v in obj.__jsonexport__])) return json.JSONEncoder.default(self, obj) class LocalClientsController: '''The generic RESTful Local Clients Controller''' def GET(self): '''Returns a JSON list of LocalClients''' engine = create_engine(DB_PATH, echo=False) Session = sessionmaker(bind=engine) session = Session() clis = session.query(LocalClient) return json.dumps([c for c in clis], cls=Encoder) A: sqlalchemy.ext.serializer exists to support pickling (with pickle module) of queries, expressions and other internal SQLAlchemy objects, it doesn't deal with model objects. In no way it will help you to serialize model objects to XML. Probably something like pyxser will be useful for you.
sqlalchemy REST serialization
Reading the doc of sqlalchemy, i saw the serialization part. I'm wondering about a possibility to use an xml serializer for matching sa models with Rest webservices like Jax-RS There is a django extension which deal with that : django_roa Do you know if that kind of thing has already been developped for sqlalchemy or if is it possible to do it?? Thanks
[ "Its a long way till full RFC2616 compliance, but for a prototype, I do something like this:\nfrom sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey, UniqueConstraint\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relation, backref, sessionmaker\nfrom ...
[ 2, 1 ]
[]
[]
[ "python", "rest", "sqlalchemy", "xml_serialization" ]
stackoverflow_0001740817_python_rest_sqlalchemy_xml_serialization.txt
Q: python+win32: detect window drag Is there a way to detect when a window that doesn't belong to my application is being dragged in windows using python/pywin32? I want to set it up so that when I drag a window whose title matches a pattern near the desktop edge, it snaps to the edge when the mouse is let go. I could write code to snap all windows with that title to the desktop whenever the mouse is released, but I want to only move the particular window that was being dragged. A: So far the only possible solution I see is to use SetWindowsHookEx. Pywin32 doesn't interface this, so I think I'll have to do something like this: Write a C extension module. It has a function like setCallback which takes a python function to be called when the drag event happens. Write a C DLL that contains the actual hook into windows. This DLL will somehow have to call the python function that is currently set. I'm not sure how to do these, or if it's correct, though.. A: pyHook seems to have done some of the work necessary, as it's hooked keyboard and mouse events. What I will probably do is keep a constant record of all the windows I care about, along with their positions. Then, on mouse up, I'll detect if any of the windows moved, and if so, and it's near where the mouse was let go, on the title-bar, I'll assume it was dragged there and snap it. Code to hook follows. import pyHook def mouseUp(event): if event.Injected: return True print "Mouse went up" return True hookManager = pyHook.HookManager() hookManager.MouseLeftUp = mouseUp hookManager.HookMouse() You also need a main loop, which I have since I'm using gtk already, or you can do: import pythoncom pythoncom.PumpMessages()
python+win32: detect window drag
Is there a way to detect when a window that doesn't belong to my application is being dragged in windows using python/pywin32? I want to set it up so that when I drag a window whose title matches a pattern near the desktop edge, it snaps to the edge when the mouse is let go. I could write code to snap all windows with that title to the desktop whenever the mouse is released, but I want to only move the particular window that was being dragged.
[ "So far the only possible solution I see is to use SetWindowsHookEx. Pywin32 doesn't interface this, so I think I'll have to do something like this:\n\nWrite a C extension module. It has a function like setCallback which takes a python function to be called when the drag event happens. \nWrite a C DLL that contains...
[ 2, 2 ]
[]
[]
[ "python", "pywin32", "winapi", "windows" ]
stackoverflow_0003753612_python_pywin32_winapi_windows.txt
Q: Properties in Python whats the reason to use the variable the self._age? A similar name that doesn't link to the already used self.age? class newprops(object): def getage(self): return 40 def setage(self, value): self._age = value age = property(getage, setage, None, None) A: self.age is already occupied by the property, you need to give another name to the actual variable, which is _age here. BTW, since Python 2.6, you could write this with decorators: def newprops(object): @property def age(self): return 40 @age.setter def age(self, value): self._age = value A: Some object oriented languages have what is called private attributes, which cannot be accessed from outside the class methods. This is important because some attributes are not meant to be changed directly, instead, they are meant to be changed as a function of something else, or validated before they are changed. In Python you don't have private attributes, but you can implement something similar by using getters and setters to a variable which starts with underscore - Python's convention for private methods and attributes. For instance. The hypotenuse of a rectangular triangle is given by h=sqrt(a*a+b*b), so you cannot change h directly because the relationship must hold. Also, say that a name must me in the format LASTNAME COMMA FIRSTNAME, then you have to verify that this is the case before you assign self.lastname. The property getter allows you to get the hypotenuse, but forbids you from setting it. The property setter allows you to set a property but you can make checks before actually setting the property. So: class Person(object) def __init__(self): # The actual attribute is _name self._name = None @property def name(self): # when I ask for the name, I mean to get _name return self._name @name.setter def name(self, value): # before setting name I can ensure that it has the right format if regex_name.match(value): # assume you have a regular expression to check for the name self._name = value else: raise ValueError('invalid name') Another example: class Triangle(object): def __init__(self, a, b): # here a and b do not need to be private because # we can change them at will. However, you could # make them private and ensure that they are floats # when they are changed self.a = a self.b = b @property def h(self): return math.sqrt(a*a+b*b) # notice there is no h.setter - you cannot set h directly A: Your example is actually nonsense because the getter returns a constant. A separate underscore-named variable in usually used in conjunction with properties, which can be 1) read-only class C(object): @property def age(self): return self._age In this case, instance.age can only be read but not assigned to. The convention is to write to self._age internally. 2) read-write class C(object): @property def age(self): return self._age @age.setter def age(self, value): assert value >= 0 self._age = value Having getter and setter only makes sense if you have to do extra calculations or checks when assigning the value. If not, you could simply declare the variable without the underscore, as properties and instance variables are accessed in the same way (in terms of code). That's why _age and the property age of course must be named differently. A: What you wrote would never be written in python. Often times, though, there are actions that need to be performed when saving a property (such as serialization), and this can be transparently cached in a property. Since the protocol for calling a property and accessing a member are the same, the python style is to wait as long as possible to turn member variables into properties.
Properties in Python
whats the reason to use the variable the self._age? A similar name that doesn't link to the already used self.age? class newprops(object): def getage(self): return 40 def setage(self, value): self._age = value age = property(getage, setage, None, None)
[ "self.age is already occupied by the property, you need to give another name to the actual variable, which is _age here.\nBTW, since Python 2.6, you could write this with decorators:\ndef newprops(object):\n\n @property\n def age(self):\n return 40\n\n @age.setter\n def age(self, value):\n ...
[ 12, 7, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003781834_python.txt
Q: pywin32 captive installation (avoid py*.dll getting installed in system32 directory) I have python as an embedded scripting environment in my application. I supply the python bits (python26.dll, DLLs & Lib folders) with my application. All this to avoid asking users to install python (you know how it goes in big corporations). All works nice except pywin32. It installs pythoncom26.dll and pywintypes26.dll to the system32 directory. I want to keep these dlls in my Python directory. One option is to add my Python directory to the PATH env variable. But would like to avoid it for obvious reasons (windows DLL search path priorities issues). Is there a way to tell Windows (a windows API is also fine) to look at my directories to load these pywin32 dlls? From what I understand these dlls get called by Windows COM. Thanks. Edit1: Note that python is deployed embedded with my application. A: I previously used py2exe to freeze the application and all the DLLs. Then use Innosetup to create an installer. Work like a charm.
pywin32 captive installation (avoid py*.dll getting installed in system32 directory)
I have python as an embedded scripting environment in my application. I supply the python bits (python26.dll, DLLs & Lib folders) with my application. All this to avoid asking users to install python (you know how it goes in big corporations). All works nice except pywin32. It installs pythoncom26.dll and pywintypes26.dll to the system32 directory. I want to keep these dlls in my Python directory. One option is to add my Python directory to the PATH env variable. But would like to avoid it for obvious reasons (windows DLL search path priorities issues). Is there a way to tell Windows (a windows API is also fine) to look at my directories to load these pywin32 dlls? From what I understand these dlls get called by Windows COM. Thanks. Edit1: Note that python is deployed embedded with my application.
[ "I previously used py2exe to freeze the application and all the DLLs. Then use Innosetup to create an installer. Work like a charm.\n" ]
[ 0 ]
[]
[]
[ "python", "python_embedding", "pywin32" ]
stackoverflow_0003781873_python_python_embedding_pywin32.txt
Q: Python decorators that are part of a base class cannot be used to decorate member functions in inherited classes Python decorators are fun to use, but I appear to have hit a wall due to the way arguments are passed to decorators. Here I have a decorator defined as part of a base class (the decorator will access class members hence it will require the self parameter). class SubSystem(object): def UpdateGUI(self, fun): #function decorator def wrapper(*args): self.updateGUIField(*args) return fun(*args) return wrapper def updateGUIField(self, name, value): if name in self.gui: if type(self.gui[name]) == System.Windows.Controls.CheckBox: self.gui[name].IsChecked = value #update checkbox on ui elif type(self.gui[name]) == System.Windows.Controls.Slider: self.gui[name].Value = value # update slider on ui ... I've omitted the rest of the implementation. Now this class is a base class for various SubSystems that will inherit from it - some of the inherited classes will need to use the UpdateGUI decorator. class DO(SubSystem): def getport(self, port): """Returns the value of Digital Output port "port".""" pass @SubSystem.UpdateGUI def setport(self, port, value): """Sets the value of Digital Output port "port".""" pass Once again I have omitted the function implementations as they are not relevant. In short the problem is that while I can access the decorator defined in the base class from the inherited class by specifiying it as SubSystem.UpdateGUI, I ultimately get this TypeError when trying to use it: unbound method UpdateGUI() must be called with SubSystem instance as first argument (got function instance instead) This is because I have no immediately identifiable way of passing the self parameter to the decorator! Is there a way to do this? Or have I reached the limits of the current decorator implementation in Python? A: You need to make UpdateGUI a @classmethod, and make your wrapper aware of self. A working example: class X(object): @classmethod def foo(cls, fun): def wrapper(self, *args, **kwargs): self.write(*args, **kwargs) return fun(self, *args, **kwargs) return wrapper def write(self, *args, **kwargs): print(args, kwargs) class Y(X): @X.foo def bar(self, x): print("x:", x) Y().bar(3) # prints: # (3,) {} # x: 3 A: It might be easier to just pull the decorator out of the SubSytem class: (Note that I'm assuming that the self that calls setport is the same self that you wish to use to call updateGUIField.) def UpdateGUI(fun): #function decorator def wrapper(self,*args): self.updateGUIField(*args) return fun(self,*args) return wrapper class SubSystem(object): def updateGUIField(self, name, value): # if name in self.gui: # if type(self.gui[name]) == System.Windows.Controls.CheckBox: # self.gui[name].IsChecked = value #update checkbox on ui # elif type(self.gui[name]) == System.Windows.Controls.Slider: # self.gui[name].Value = value # update slider on ui print(name,value) class DO(SubSystem): @UpdateGUI def setport(self, port, value): """Sets the value of Digital Output port "port".""" pass do=DO() do.setport('p','v') # ('p', 'v') A: You've sort of answered the question in asking it: what argument would you expect to get as self if you call SubSystem.UpdateGUI? There isn't an obvious instance that should be passed to the decorator. There are several things you could do to get around this. Maybe you already have a subSystem that you've instantiated somewhere else? Then you could use its decorator: subSystem = SubSystem() subSystem.UpdateGUI(...) But maybe you didn't need the instance in the first place, just the class SubSystem? In that case, use the classmethod decorator to tell Python that this function should receive its class as the first argument instead of an instance: @classmethod def UpdateGUI(cls,...): ... Finally, maybe you don't need access to either the instance or the class! In that case, use staticmethod: @staticmethod def UpdateGUI(...): ... Oh, by the way, Python convention is to reserve CamelCase names for classes and to use mixedCase or under_scored names for methods on that class. A: You need to use an instance of SubSystem to do your decorating or use a classmethod as kenny suggests. subsys = SubSystem() class DO(SubSystem): def getport(self, port): """Returns the value of Digital Output port "port".""" pass @subsys.UpdateGUI def setport(self, port, value): """Sets the value of Digital Output port "port".""" pass You decide which to do by deciding if you want all subclass instances to share the same GUI interface or if you want to be able to let distinct ones have distinct interfaces. If they all share the same GUI interface, use a class method and make everything that the decorator accesses a class instance. If they can have distinct interfaces, you need to decide if you want to represent the distinctness with inheritance (in which case you would also use classmethod and call the decorator on the subclasses of SubSystem) or if it is better represented as distinct instances. In that case make one instance for each interface and call the decorator on that instance.
Python decorators that are part of a base class cannot be used to decorate member functions in inherited classes
Python decorators are fun to use, but I appear to have hit a wall due to the way arguments are passed to decorators. Here I have a decorator defined as part of a base class (the decorator will access class members hence it will require the self parameter). class SubSystem(object): def UpdateGUI(self, fun): #function decorator def wrapper(*args): self.updateGUIField(*args) return fun(*args) return wrapper def updateGUIField(self, name, value): if name in self.gui: if type(self.gui[name]) == System.Windows.Controls.CheckBox: self.gui[name].IsChecked = value #update checkbox on ui elif type(self.gui[name]) == System.Windows.Controls.Slider: self.gui[name].Value = value # update slider on ui ... I've omitted the rest of the implementation. Now this class is a base class for various SubSystems that will inherit from it - some of the inherited classes will need to use the UpdateGUI decorator. class DO(SubSystem): def getport(self, port): """Returns the value of Digital Output port "port".""" pass @SubSystem.UpdateGUI def setport(self, port, value): """Sets the value of Digital Output port "port".""" pass Once again I have omitted the function implementations as they are not relevant. In short the problem is that while I can access the decorator defined in the base class from the inherited class by specifiying it as SubSystem.UpdateGUI, I ultimately get this TypeError when trying to use it: unbound method UpdateGUI() must be called with SubSystem instance as first argument (got function instance instead) This is because I have no immediately identifiable way of passing the self parameter to the decorator! Is there a way to do this? Or have I reached the limits of the current decorator implementation in Python?
[ "You need to make UpdateGUI a @classmethod, and make your wrapper aware of self. A working example:\nclass X(object):\n @classmethod\n def foo(cls, fun):\n def wrapper(self, *args, **kwargs):\n self.write(*args, **kwargs)\n return fun(self, *args, **kwargs)\n return wrapper...
[ 28, 3, 3, 2 ]
[]
[]
[ "decorator", "inheritance", "ironpython", "python" ]
stackoverflow_0003782040_decorator_inheritance_ironpython_python.txt
Q: Python Sort Two Dimensional Dictionary By First Key I have a 2D dictionary in python indexed by two IPs. I want to group the dictionary by the first key. For example, the before would look like this: myDict["182.12.17.50"]["175.12.13.14"] = 14 myDict["182.15.12.30"]["175.12.13.15"] = 10 myDict["182.12.17.50"]["185.23.15.69"] = 30 myDict["182.15.12.30"]["145.33.34.56"] = 230 so for key1, key2 in myDict: print key1 +" " +key2 +" " +myDict[key1, key2] would print 182.12.17.50 175.12.13.14 14 182.15.12.30 175.12.13.15 10 182.12.17.50 185.23.15.69 30 182.15.12.30 145.33.34.56 230 But I want to sort it so it would print 182.12.17.50 175.12.13.14 14 182.12.17.50 185.23.15.69 30 182.15.12.30 175.12.13.15 10 182.15.12.30 145.33.34.56 230 Any idea how this could be accomplished? A: Well, there are a variety of options. One of them would be to sort the keys before printing, something like this: for key1 in sorted(myDict): for key2 in myDict[key1]: print key1 +" " +key2 +" " +myDict[key1][key2] Another option would be to use the sorteddict class from the blist module (disclaimer: I'm the author :) ), which will always return the keys in sorted order. In either cases, since the keys are IP addresses, you might want to write a custom "key" function to pass to sort/sorted/sorteddict so they will sorted by their numeric value rather than lexicographically as a string. A: Dicts have no order, but what you can get is a sorted list of items. >>> sorted((k, sorted(v.items())) for k,v in myDict.items()) [('182.12.17.50', [('175.12.13.14', 14), ('185.23.15.69', 30)]), ('182.15.12.30', [('145.33.34.56', 230), ('175.12.13.15', 10)])] A: You can pass a custom comparison function into Sorted. http://docs.python.org/library/functions.html#sorted With it, you can specify which key to compare and how. A: I guess, I have not understood the problem very well. Wouldn't the output of above dictionary look like this: >>> myDict {'182.12.17.50': {'185.23.15.69': 30, '175.12.13.14': 14}, '182.15.12.30': {'175.12.13.15': 10, '145.33.34.56': 230}} and then you could use OrderedDict to create a sorted dictionary. A: Dictionaries are an unordered type and in your example I don't see a reason why you would want the dict to be ordered. If you need to create an ordered series of the dictionary's contents, i.e. its items, you can do that simply by applying sorted: # Returns sorted list of item tuples sorted(myDict.iteritems()) Or check out OrderedDict if your Python version supports it and you know what it means to have a sorted dictionary.
Python Sort Two Dimensional Dictionary By First Key
I have a 2D dictionary in python indexed by two IPs. I want to group the dictionary by the first key. For example, the before would look like this: myDict["182.12.17.50"]["175.12.13.14"] = 14 myDict["182.15.12.30"]["175.12.13.15"] = 10 myDict["182.12.17.50"]["185.23.15.69"] = 30 myDict["182.15.12.30"]["145.33.34.56"] = 230 so for key1, key2 in myDict: print key1 +" " +key2 +" " +myDict[key1, key2] would print 182.12.17.50 175.12.13.14 14 182.15.12.30 175.12.13.15 10 182.12.17.50 185.23.15.69 30 182.15.12.30 145.33.34.56 230 But I want to sort it so it would print 182.12.17.50 175.12.13.14 14 182.12.17.50 185.23.15.69 30 182.15.12.30 175.12.13.15 10 182.15.12.30 145.33.34.56 230 Any idea how this could be accomplished?
[ "Well, there are a variety of options. One of them would be to sort the keys before printing, something like this:\nfor key1 in sorted(myDict):\n for key2 in myDict[key1]:\n print key1 +\" \" +key2 +\" \" +myDict[key1][key2]\n\nAnother option would be to use the sorteddict class from the blist module...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0003781527_dictionary_python_sorting.txt
Q: How do I get the request parameters from urls.py? Hi I have an application that works fine when I type the url from the browser. it works something like http://mysite/service?id=1234, if I type that on the browser it works fine, however we have another service that accepts parameters from a mobile phone, this service would then call the same url, and post the parameter onto it. I know it gets as far as urls.py bacause I've put a logging mechanism there, but it doesn't quite make it into the views, i have a logging bit in the view as well. so that's why I wanted to get the exact request path that the urls.py recieves for me to be able to figure out if the service is screwing something up. is this possible at all? A: When you say post, do you mean post, or are you using this crucial, extremely specific verb randomly? Because if the request is indeed a post, there will most likely be no ?id=1234 as part of the URL -- the parameters will instead go in the body of the post; the query-string part of the URL is normally used only for GET requests, not POST requests. Then again, it is quite possible that you're just using extremely specific verbs randomly, since you do say "call the url" which is guaranteed nonsense (one "calls" a function: there is no concept at all of "calling a URL" in the operation of the web;-)... but I'm giving you the benefit of the doubt since, just in case you're using technical terminology correctly, the use of POST would in fact totally explain why the query-string part of the URL, which apparently you expect to be present, might instead most likely be totally absent (with the parameters info transmuted instead into a post-body!). A: Judging from your urls.py: If the view that isn't hit is the ws one, have you tried (r'^ws$','www.views.ws'), You forgot to include the urls are you testing with, so it's hard to say. If you're on a unixy system I recommend kodos to test out the regular expression of an urlpattern against an actual url.
How do I get the request parameters from urls.py?
Hi I have an application that works fine when I type the url from the browser. it works something like http://mysite/service?id=1234, if I type that on the browser it works fine, however we have another service that accepts parameters from a mobile phone, this service would then call the same url, and post the parameter onto it. I know it gets as far as urls.py bacause I've put a logging mechanism there, but it doesn't quite make it into the views, i have a logging bit in the view as well. so that's why I wanted to get the exact request path that the urls.py recieves for me to be able to figure out if the service is screwing something up. is this possible at all?
[ "When you say post, do you mean post, or are you using this crucial, extremely specific verb randomly? Because if the request is indeed a post, there will most likely be no ?id=1234 as part of the URL -- the parameters will instead go in the body of the post; the query-string part of the URL is normally used only ...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003775365_django_python.txt
Q: wxPython GUI BoxSizers Ok I have an application I am coding and am trying to get a layout simpler to this: Notice how the text is left justified and the input boxes are all aligned, I see this in the wxPython demo code, but they all use the flexgrid sizer and I am trying to only use BoxSizers (due to them being simpler and because I only understand a little of sizers and even struggle with using BoxSizers, in 6 months I would have an even harder time) I have tried having the input and text in two vertical sizers and then putting those in a horizontal sizer, didn't work because the text was not aligned with the inputs. I also tried doing that and also having each text, input pairing in a sizer, even worse. Any suggestions? A: Here's a simple example using just BoxSizers: import wx class MyForm(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial") # Add a panel so it looks the correct on all platforms panel = wx.Panel(self, wx.ID_ANY) # create the labels lblOne = wx.StaticText(panel, label="labelOne", size=(60,-1)) lblTwo = wx.StaticText(panel, label="lblTwo", size=(60,-1)) lblThree = wx.StaticText(panel, label="lblThree", size=(60,-1)) # create the text controls txtOne = wx.TextCtrl(panel) txtTwo = wx.TextCtrl(panel) txtThree = wx.TextCtrl(panel) # create some sizers mainSizer = wx.BoxSizer(wx.VERTICAL) lineOneSizer = wx.BoxSizer(wx.HORIZONTAL) lineTwoSizer = wx.BoxSizer(wx.HORIZONTAL) lineThreeSizer = wx.BoxSizer(wx.HORIZONTAL) # add widgets to sizers lineOneSizer.Add(lblOne, 0, wx.ALL|wx.ALIGN_LEFT, 5) lineOneSizer.Add(txtOne, 0, wx.ALL, 5) lineTwoSizer.Add(lblTwo, 0, wx.ALL|wx.ALIGN_LEFT, 5) lineTwoSizer.Add(txtTwo, 0, wx.ALL, 5) lineThreeSizer.Add(lblThree, 0, wx.ALL|wx.ALIGN_LEFT, 5) lineThreeSizer.Add(txtThree, 0, wx.ALL, 5) mainSizer.Add(lineOneSizer) mainSizer.Add(lineTwoSizer) mainSizer.Add(lineThreeSizer) panel.SetSizer(mainSizer) # Run the program if __name__ == "__main__": app = wx.App(False) frame = MyForm() frame.Show() app.MainLoop() But this is kind of messy, so here's a refactored version: import wx class MyForm(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial") # create the main sizer self.mainSizer = wx.BoxSizer(wx.VERTICAL) # Add a panel so it looks the correct on all platforms self.panel = wx.Panel(self, wx.ID_ANY) lbls = ["labelOne", "lblTwo", "lblThree"] for lbl in lbls: self.buildLayout(lbl) self.panel.SetSizer(self.mainSizer) #---------------------------------------------------------------------- def buildLayout(self, text): """""" lblSize = (60,-1) lbl = wx.StaticText(self.panel, label=text, size=lblSize) txt = wx.TextCtrl(self.panel) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(lbl, 0, wx.ALL|wx.ALIGN_LEFT, 5) sizer.Add(txt, 0, wx.ALL, 5) self.mainSizer.Add(sizer) # Run the program if __name__ == "__main__": app = wx.App(False) frame = MyForm() frame.Show() app.MainLoop() A: For most layouts other than the most basic you usually can't escape using a number of different types of sizers in order to realize your design. Here is a good tutorial on sizers.
wxPython GUI BoxSizers
Ok I have an application I am coding and am trying to get a layout simpler to this: Notice how the text is left justified and the input boxes are all aligned, I see this in the wxPython demo code, but they all use the flexgrid sizer and I am trying to only use BoxSizers (due to them being simpler and because I only understand a little of sizers and even struggle with using BoxSizers, in 6 months I would have an even harder time) I have tried having the input and text in two vertical sizers and then putting those in a horizontal sizer, didn't work because the text was not aligned with the inputs. I also tried doing that and also having each text, input pairing in a sizer, even worse. Any suggestions?
[ "Here's a simple example using just BoxSizers:\nimport wx\n\nclass MyForm(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, wx.ID_ANY, \"Tutorial\")\n\n # Add a panel so it looks the correct on all platforms\n panel = wx.Panel(self, wx.ID_ANY)\n\n # create the labels\...
[ 3, 1 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003775071_python_user_interface_wxpython.txt
Q: Python: interact with complex data warehouse We've worked hard to work up a full dimensional database model of our problem, and now it's time to start coding. Our previous projects have used hand-crafted queries constructed by string manipulation. Is there any best/standard practice for interfacing between python and a complex database layout? I've briefly evaluated SQLAlchemy, SQLObject, and Django-ORM, but (I may easily be missing something) they seem tuned for tiny web-type (OLTP) transactions, where I'm doing high-volume analytical (OLAP) transactions. Some of my requirements, that may be somewhat different than usual: load large amounts of data relatively quickly update/insert small amounts of data quickly and easily handle large numbers of rows easily (300 entries per minute over 5 years) allow for modifications in the schema, for future requirements Writing these queries is easy, but writing the code to get the data all lined up is tedious, especially as the schema evolves. This seems like something that a computer might be good at? A: Don't get confused by your requirements. One size does not fit all. load large amounts of data relatively quickly Why not use the databases's native loaders for this? Use Python to prepare files, but use database tools to load. You'll find that this is amazingly fast. update/insert small amounts of data quickly and easily That starts to bend the rules of a data warehouse. Unless you're talking about Master Data Management to update reporting attributes of a dimension. That's what ORM's and web frameworks are for. handle large numbers of rows easily (300 entries per minute over 5 years) Again, that's why you use a pipeline of Python front-end processing, but the actual INSERT's are done by database tools. Not Python. alter schema (along with python interface) easily, for future requirements You have almost no use for automating this. It's certainly your lowest priority task for "programming". You'll often do this manually in order to preserve data properly. BTW, "hand-crafted queries constructed by string manipulation" is probably the biggest mistake ever. These are hard for the RDBMS parser to handle -- they're slower than using queries that have bind variables inserted. A: I'm using SQLAlchemy with a pretty big datawarehouse and I'm using it for the full ETL process with success. Specially in certain sources where I have some complex transformation rules or with some heterogeneous sources (such as web services). I'm not using the Sqlalchemy ORM but rather using its SQL Expression Language because I don't really need to map anything with objects in the ETL process. Worth noticing that when I'm bringing a verbatim copy of some of the sources I rather use the db tools for that -such as PostgreSQL dump utility-. You can't beat that. SQL Expression Language is the closest you will get with SQLAlchemy (or any ORM for the matter) to handwriting SQL but since you can programatically generate the SQL from python you will save time, specially if you have some really complex transformation rules to follow. One thing though, I rather modify my schema by hand. I don't trust any tool for that job. A: SQLAlchemy definitely. Compared to SQLAlchemy, all other ORMs look like child's toy. Especially the Django-ORM. What's Hibernate to Java, SQLAlchemy is to Python.
Python: interact with complex data warehouse
We've worked hard to work up a full dimensional database model of our problem, and now it's time to start coding. Our previous projects have used hand-crafted queries constructed by string manipulation. Is there any best/standard practice for interfacing between python and a complex database layout? I've briefly evaluated SQLAlchemy, SQLObject, and Django-ORM, but (I may easily be missing something) they seem tuned for tiny web-type (OLTP) transactions, where I'm doing high-volume analytical (OLAP) transactions. Some of my requirements, that may be somewhat different than usual: load large amounts of data relatively quickly update/insert small amounts of data quickly and easily handle large numbers of rows easily (300 entries per minute over 5 years) allow for modifications in the schema, for future requirements Writing these queries is easy, but writing the code to get the data all lined up is tedious, especially as the schema evolves. This seems like something that a computer might be good at?
[ "Don't get confused by your requirements. One size does not fit all.\n\nload large amounts of data relatively quickly\n\nWhy not use the databases's native loaders for this? Use Python to prepare files, but use database tools to load. You'll find that this is amazingly fast. \n\nupdate/insert small amounts of d...
[ 6, 3, 2 ]
[]
[]
[ "data_warehouse", "django_models", "olap", "python", "sqlalchemy" ]
stackoverflow_0003782386_data_warehouse_django_models_olap_python_sqlalchemy.txt
Q: Character encoding is violated I am trying to parse a file encoded in utf-8. No operation has problem apart from write to file (or at least I think so). A minimum working example follows: from lxml import etree parser = etree.HTMLParser() tree = etree.parse('example.txt', parser) tree.write('aaaaaaaaaaaaaaaaa.html') example.txt: <html> <body> <invalid html here/> <interesting attrib1="yes"> <group> <line> δεδομένα1 </line> </group> <group> <line> δεδομένα2 </line> </group> <group> <line> δεδομένα3 </line> </group> </interesting> </body> </html> I am already aware of a similar previous question but I could not solve the problem either without specifying the output encoding, or using utf8 or iso-8859-7. I have concluded that the file is in utf8 since it displays correctly at Chrome when choosing this encoding. My editor (Kate) agrees. I get no runtime error, but the output is not as desired. Example output with tree.write('aaaaaaaaaaaaaaaaa.html', encoding='utf-8'): <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body> <invalid html="" here=""/><interesting attrib1="yes"><group><line> δεδομένα1 </line></group><group><line> δεδομένα2 </line></group><group><line> δεδομένα3 </line></group></interesting></body></html> A: The obvious problem is that HTMLParser treats the input file as ANSI by default, i.e. the UTF-8 bytes are misinterpreted as 8-bit character codes. You can simply pass the encoding to fix this: parser = etree.HTMLParser(encoding = "utf-8") If you want to check what I meant with the misinterpretation, let Python print repr(tree.xpath("//line")[0].text) with and without HTMLParser's encoding parameter.
Character encoding is violated
I am trying to parse a file encoded in utf-8. No operation has problem apart from write to file (or at least I think so). A minimum working example follows: from lxml import etree parser = etree.HTMLParser() tree = etree.parse('example.txt', parser) tree.write('aaaaaaaaaaaaaaaaa.html') example.txt: <html> <body> <invalid html here/> <interesting attrib1="yes"> <group> <line> δεδομένα1 </line> </group> <group> <line> δεδομένα2 </line> </group> <group> <line> δεδομένα3 </line> </group> </interesting> </body> </html> I am already aware of a similar previous question but I could not solve the problem either without specifying the output encoding, or using utf8 or iso-8859-7. I have concluded that the file is in utf8 since it displays correctly at Chrome when choosing this encoding. My editor (Kate) agrees. I get no runtime error, but the output is not as desired. Example output with tree.write('aaaaaaaaaaaaaaaaa.html', encoding='utf-8'): <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body> <invalid html="" here=""/><interesting attrib1="yes"><group><line> δεδομένα1 </line></group><group><line> δεδομένα2 </line></group><group><line> δεδομένα3 </line></group></interesting></body></html>
[ "The obvious problem is that HTMLParser treats the input file as ANSI by default, i.e. the UTF-8 bytes are misinterpreted as 8-bit character codes. You can simply pass the encoding to fix this:\nparser = etree.HTMLParser(encoding = \"utf-8\")\n\nIf you want to check what I meant with the misinterpretation, let Pyth...
[ 1 ]
[]
[]
[ "encoding", "lxml", "python" ]
stackoverflow_0003780829_encoding_lxml_python.txt
Q: Can not get the Auth Token for GData After Authentication on App Engine I would like to pull the Auth Token for the Gdata auth so that I can write to a google calendar. I am having issues getting the token after authentication so that I can send the token to the calendar service. I am using the default login screen provided by appengine (/_ah/login) and I am able to login and authenticate, however, I am unable to pull the Auth Token out of the self.request.uri because the URL is being rewritten: Example: Login Screen Redirect from kiddushfund.appspot.com/admin https://www.google.com/accounts/ServiceLogin?service=ah&continue=http://appname.appspot.com/_ah/login%3Fcontinue%3Dhttp://appname.appspot.com/admin&ltmpl=gm&ahname=App+Name&sig=65e70293a754da54fe06ecbedbb59213 This is after authentication and the URL was pulled out of firebug http://appname.appspot.com/_ah/login?continue=http://appname.appspot.com/admin&auth=DQAAAL0AAAD9X_Noig8blUlg_KA02UbjgBC2yWl8XKXIVA3SI5ZQ7pJOyL4SyYPpKu5jOLAw0ol0rSUVBENBMmWC2DkH6sTxx3AlSF4UI_LcByDlacBV3Fy1At80h_ML97fLeu0LLQbgzuLxY_wTHBb5svkCVDOeVABFKf98qvZ62SGl0PrDTxs1P3lCF04ooDdFilDecGUoED6hbnjd9P7-6eqxOO9nrBCSk571uyWZCLIA-1I5f3Om_MqAIPmi_5mqLXOSv0I This is the final URL after the authentication but I'm not able to pull the token anymore http://appname.appspot.com/admin This seems like a really simple problem and any help would be appreciated. Thanks. from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import users from google.appengine.ext import webapp import atom import settings import os import urllib import urllib2 import cookielib import gdata.service import gdata.auth import gdata.alt.appengine import gdata.calendar import gdata.calendar.service class Auth(webapp.RequestHandler): def __init__(self): self.calendar_client = gdata.calendar.service.CalendarService() gdata.alt.appengine.run_on_appengine(self.calendar_client) def get(self): user = users.get_current_user() if user: token_request_url = None auth_token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri) if auth_token: self.calendar_client.SetAuthSubToken(self.calendar_client.upgrade_to_session_token(auth_token)) if not isinstance(self.calendar_client.token_store.find_token( 'http://www.google.com/calendar/feeds/'),gdata.auth.AuthSubToken): token_request_url = gdata.auth.generate_auth_sub_url(self.request.uri, ('http://www.google.com/calendar/feeds/default/',)) #This is where I were I would look for the token but the self.request.url # is only return http://appname.appspot.admin - with no token. self.response.out.write(self.request.uri) else: self.redirect(users.create_login_url(self.request.uri)) def main(): application = webapp.WSGIApplication([('/.*', Auth),], debug=True) run_wsgi_app(application) if __name__ == '__main__': main() A: The login screen only authenticates the user to your application, it does not give you authorization to the user's gdata. You will need to have the user authorize your use of the calendar api - I suggest through oauth here: http://code.google.com/apis/gdata/docs/auth/overview.html#OAuth. You only need to do this once, and then store the oauth token for that user for all subsequent calls. A: There are limitations about number of tokens outstanding - e.g. numbers of users possible. What about number of ClientLogin tokens outstanding?
Can not get the Auth Token for GData After Authentication on App Engine
I would like to pull the Auth Token for the Gdata auth so that I can write to a google calendar. I am having issues getting the token after authentication so that I can send the token to the calendar service. I am using the default login screen provided by appengine (/_ah/login) and I am able to login and authenticate, however, I am unable to pull the Auth Token out of the self.request.uri because the URL is being rewritten: Example: Login Screen Redirect from kiddushfund.appspot.com/admin https://www.google.com/accounts/ServiceLogin?service=ah&continue=http://appname.appspot.com/_ah/login%3Fcontinue%3Dhttp://appname.appspot.com/admin&ltmpl=gm&ahname=App+Name&sig=65e70293a754da54fe06ecbedbb59213 This is after authentication and the URL was pulled out of firebug http://appname.appspot.com/_ah/login?continue=http://appname.appspot.com/admin&auth=DQAAAL0AAAD9X_Noig8blUlg_KA02UbjgBC2yWl8XKXIVA3SI5ZQ7pJOyL4SyYPpKu5jOLAw0ol0rSUVBENBMmWC2DkH6sTxx3AlSF4UI_LcByDlacBV3Fy1At80h_ML97fLeu0LLQbgzuLxY_wTHBb5svkCVDOeVABFKf98qvZ62SGl0PrDTxs1P3lCF04ooDdFilDecGUoED6hbnjd9P7-6eqxOO9nrBCSk571uyWZCLIA-1I5f3Om_MqAIPmi_5mqLXOSv0I This is the final URL after the authentication but I'm not able to pull the token anymore http://appname.appspot.com/admin This seems like a really simple problem and any help would be appreciated. Thanks. from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import users from google.appengine.ext import webapp import atom import settings import os import urllib import urllib2 import cookielib import gdata.service import gdata.auth import gdata.alt.appengine import gdata.calendar import gdata.calendar.service class Auth(webapp.RequestHandler): def __init__(self): self.calendar_client = gdata.calendar.service.CalendarService() gdata.alt.appengine.run_on_appengine(self.calendar_client) def get(self): user = users.get_current_user() if user: token_request_url = None auth_token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri) if auth_token: self.calendar_client.SetAuthSubToken(self.calendar_client.upgrade_to_session_token(auth_token)) if not isinstance(self.calendar_client.token_store.find_token( 'http://www.google.com/calendar/feeds/'),gdata.auth.AuthSubToken): token_request_url = gdata.auth.generate_auth_sub_url(self.request.uri, ('http://www.google.com/calendar/feeds/default/',)) #This is where I were I would look for the token but the self.request.url # is only return http://appname.appspot.admin - with no token. self.response.out.write(self.request.uri) else: self.redirect(users.create_login_url(self.request.uri)) def main(): application = webapp.WSGIApplication([('/.*', Auth),], debug=True) run_wsgi_app(application) if __name__ == '__main__': main()
[ "The login screen only authenticates the user to your application, it does not give you authorization to the user's gdata. \nYou will need to have the user authorize your use of the calendar api - I suggest through oauth here: http://code.google.com/apis/gdata/docs/auth/overview.html#OAuth. \nYou only need to do ...
[ 3, 0 ]
[]
[]
[ "gdata", "gdata_api", "google_app_engine", "google_data_api", "python" ]
stackoverflow_0002100699_gdata_gdata_api_google_app_engine_google_data_api_python.txt
Q: Django Form validation including the use of session data The use case I am try to address is a requirement for a user to have downloaded a file before being permitted to proceed to the next stage in a form process. In order to achieve this, I have a Django Form to capture the user's general information which POSTS to Django view 'A'. The Form is displayed using a template which also includes an iFrame with a simple embedded button which links to the URL of Django view 'B'. View 'B' simply sets a session variable to indicate that the download has occurred, and returns the URL of the file for download, thereby triggering the download. As part of the validation of Form 'A' (the main Form), I need to check whether the session variable indicating file download is set. My question is, is this best done using Form 'A' validation process, and if so, how is this best achieved? If this is not a good approach, where should validation of this event take place? A: You could override the __init__ method for your form so that it takes request as an argument. class MyForm(forms.Form): def __init__(self, request, *args, **kwargs) self.request = request super(MyForm, self).__init__(*args, **kwargs) def clean(self): if not self.request.session.get('file_downloaded', False): raise ValidationError('File not downloaded!') def my_view(request): form = MyForm(request, data=request.POST) This keeps all the validation logic in the form. A: Why not, it looks OK to me. The most convenient way of accessing request inside Form, that I know, is embedding it (i.e. Form) inside a function: def formX(request): class FormX(forms.Form): def clean(self): if not request.session.get('file_downloaded', False): raise ValidationError('File not downloaded!') return FormX (Note that regarding clean(), this is pseudocode - I was writing out of my head and I probably don't remember details of form cleaning) Then in view you just write: def my_view(request): form = formX(request)(...)
Django Form validation including the use of session data
The use case I am try to address is a requirement for a user to have downloaded a file before being permitted to proceed to the next stage in a form process. In order to achieve this, I have a Django Form to capture the user's general information which POSTS to Django view 'A'. The Form is displayed using a template which also includes an iFrame with a simple embedded button which links to the URL of Django view 'B'. View 'B' simply sets a session variable to indicate that the download has occurred, and returns the URL of the file for download, thereby triggering the download. As part of the validation of Form 'A' (the main Form), I need to check whether the session variable indicating file download is set. My question is, is this best done using Form 'A' validation process, and if so, how is this best achieved? If this is not a good approach, where should validation of this event take place?
[ "You could override the __init__ method for your form so that it takes request as an argument.\nclass MyForm(forms.Form):\n def __init__(self, request, *args, **kwargs)\n self.request = request\n super(MyForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n if not self.request.sess...
[ 13, 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003778148_django_django_forms_python.txt
Q: How do I stop 'print' from outputting to the browser with Google App Engine? I'm new to GAE, and have not been able to figure out how to configure 'print' statements to the logging console rather than the browser. For example: class Feed(webapp.RequestHandler): def post(self): feeditem = Feeditem() feeditem.author = self.request.get('from') feeditem.content = self.request.get('content') feeditem.put() notify_friends(feeditem) self.redirect('/') def notify_friends(feeditem): """Alerts friends of a new feeditem""" print 'Feeditem = ', feeditem When I do something like the above, the print in notify_friends outputs to the browser and somehow prevents the self.redirect('/') in the post method that called it. Commenting it out corrects the issue. Is there a way to change this behavior? EDIT: Google App Engine tag removed as this is general. A: You should instead use the logging module, like so: import logging def notify_friends(feeditem): """Alerts friends of a new feeditem""" logging.info('Feeditem = %s', feeditem) There are a variety of logging levels you can use, from debug to critical. By default, though, the App Engine SDK only shows you log messages at level info and above, so that's what I've suggested here. You can ask it to show you debug messages if you want, but you'll probably be overwhelmed with useless (to you) logging information, at least when running in the SDK. See the logging module docs for more info. Oh, and the nice thing about using the logging module is that you'll have access to your log messages in production, under the "Logs" section of your app's the App Engine dashboard. A: This is not just a problem with GAE. It is a general issue. You can't print out HTML and then try to have a redirect header. The answer to your question is no, you can't change the behavior. What exactly are you trying to achieve? You might be able to get what you want a different way.
How do I stop 'print' from outputting to the browser with Google App Engine?
I'm new to GAE, and have not been able to figure out how to configure 'print' statements to the logging console rather than the browser. For example: class Feed(webapp.RequestHandler): def post(self): feeditem = Feeditem() feeditem.author = self.request.get('from') feeditem.content = self.request.get('content') feeditem.put() notify_friends(feeditem) self.redirect('/') def notify_friends(feeditem): """Alerts friends of a new feeditem""" print 'Feeditem = ', feeditem When I do something like the above, the print in notify_friends outputs to the browser and somehow prevents the self.redirect('/') in the post method that called it. Commenting it out corrects the issue. Is there a way to change this behavior? EDIT: Google App Engine tag removed as this is general.
[ "You should instead use the logging module, like so:\nimport logging\ndef notify_friends(feeditem):\n \"\"\"Alerts friends of a new feeditem\"\"\" \n logging.info('Feeditem = %s', feeditem)\n\nThere are a variety of logging levels you can use, from debug to critical. By default, though, the App Engine SDK...
[ 3, 2 ]
[]
[]
[ "debugging", "logging", "python" ]
stackoverflow_0003782966_debugging_logging_python.txt
Q: Basic GUI for Python? Possible Duplicate: Practical GUI toolkit? Hi, I'm just getting my head around Python, and have been building some stuff from tutorials, examples, etc. As my programs are getting more complex after a few weeks' tinkering, I'm getting overwhelmed by the pile of data my console is serving me (working on an app with lots of input/output currently) and would like to move into something a bit more visual to organize my feedback. I've found a few visual modules, but it seems like tkinter is the standard/easiest to start with. I just need a configurable window, some text and basic shapes for now. Any heads up before I get my hands dirty (if it makes any difference - remember, I'm working on something that updates/redraws periodically)? Thanks. A: If you are working with scientifical data you should check Traits and Traits UI The Traits UI package is a set of user interface tools designed to complement Traits. In the simplest case, it can automatically generate a user interface for editing a Traits-based object, with no additional coding on the part of the programmer-user. In more sophisticated uses, it can implement a Model-View-Controller (MVC) design pattern for Traits-based objects. It comes in the enthough python edition together with other, more conventional, modules for data representation (ie matplotlib) storage (ie pyTables...) and gui building. A: easygui is perhaps - no definitely the easiest GUI module for python I have worked with. A Google search shows that it can be downloaded from here. I installed my version a while back and don't need to use it too often and therefore am not sure whether the above download is what I have (it shouldn't matter too much), but if you have such concerns, then you can download the version I have from this page Hope this Helps
Basic GUI for Python?
Possible Duplicate: Practical GUI toolkit? Hi, I'm just getting my head around Python, and have been building some stuff from tutorials, examples, etc. As my programs are getting more complex after a few weeks' tinkering, I'm getting overwhelmed by the pile of data my console is serving me (working on an app with lots of input/output currently) and would like to move into something a bit more visual to organize my feedback. I've found a few visual modules, but it seems like tkinter is the standard/easiest to start with. I just need a configurable window, some text and basic shapes for now. Any heads up before I get my hands dirty (if it makes any difference - remember, I'm working on something that updates/redraws periodically)? Thanks.
[ "If you are working with scientifical data you should check Traits and Traits UI\n\nThe Traits UI package is a set of user\n interface tools designed to complement\n Traits. In the simplest case, it can\n automatically generate a user\n interface for editing a Traits-based\n object, with no additional coding o...
[ 0, 0 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0003782832_python_user_interface.txt
Q: Why does python gstreamer crash without "gobject.threads_init()" at the top of my script? I have written a python script to use gstreamer (pygst and gst modules) to calculate replaygain tags, and it was crashing inconsistently with various gobject errors. I found somewhere that you could fix this by putting the following boilerplate at the top of your script: import gobject gobject.threads_init() I tried it, and it worked. Can anyone explain why these lines are necessary, and why pygst doesn't do this itself? A: Because, you can use gobject in a non threading environment. This is not unusual. When you use gobject in a threading environment, you need to explicitly initialize by calling gobject.threads_init(). This will also ensure that the when "C" functions are called, the GIL is freed. Python, Threads, the GIL, and C++ Explain Python extensions multithreading Also from the function document : The threads_init() function initializes the use of Python threading in the gobject module. This function is different than the gtk.gdk.threads_init() function as that function also initializes the gdk threads. Basically, you tell gobject module explicitly that you are going to use threading and initialize it accordingly.
Why does python gstreamer crash without "gobject.threads_init()" at the top of my script?
I have written a python script to use gstreamer (pygst and gst modules) to calculate replaygain tags, and it was crashing inconsistently with various gobject errors. I found somewhere that you could fix this by putting the following boilerplate at the top of your script: import gobject gobject.threads_init() I tried it, and it worked. Can anyone explain why these lines are necessary, and why pygst doesn't do this itself?
[ "Because, you can use gobject in a non threading environment. This is not unusual.\nWhen you use gobject in a threading environment, you need to explicitly initialize by calling gobject.threads_init(). This will also ensure that the when \"C\" functions are called, the GIL is freed.\n\nPython, Threads, the GIL, and...
[ 14 ]
[]
[]
[ "gobject", "gstreamer", "python", "thread_safety" ]
stackoverflow_0003782962_gobject_gstreamer_python_thread_safety.txt
Q: Calling a Java program from a CGI script fails I have a Python CGI script from which I am trying to call a Java program to perform a task. The Java program uses JExcelAPI. When I run the Python script from the browser, it fails with error messages that it can't find the class definitions for the classes from JExcelAPI. I suppose this happens because the Python CGI script is run under the apache user, and the apache user does not have the appropriate environment variables set (namely the CLASSPATH variable). I have tried calling the program with the -classpath /path/to/JExcelAPI switch, but that does not work either. Can you help me find the way to make the apache user aware of the JExcelAPI? Is there a way to set the CLASSPATH environment variable for the apache user? Thanks A: Several solutions come to mind : Create a bash script which calls the java program. You can set all the variables you like and debug on the commandline, e.g. sudo -u apache /usr/local/bin/java-task-wrapper. This simplifies calling it from a cgi considerably and the overhead of bash is negligeable compared to spinning up a JVM. Create a standalone executable jar with tools like uberjar. No more classpah issues as everything is contained : java -jar java-task-standalone.jar exec java -cp /path/to/JExcelAPI:/my/program/classes com.acme.MainClass There is usually a variant of exec which takes an additional array or hashmap to add environment variables. Some notes: setting the CLASSPATH variable globally is not done anymore because it leads to many conflicts. In a wrapper script it is Ok as possibilities to clash is reduced. JVM's take a long time to start and the execution will be slow since the JIT gets no chance to do its magic. Running your script in a lightweight webserver like jetty or winstone or listening on a socket will eliminate the startup cost and enabe the JIT to make things fast.
Calling a Java program from a CGI script fails
I have a Python CGI script from which I am trying to call a Java program to perform a task. The Java program uses JExcelAPI. When I run the Python script from the browser, it fails with error messages that it can't find the class definitions for the classes from JExcelAPI. I suppose this happens because the Python CGI script is run under the apache user, and the apache user does not have the appropriate environment variables set (namely the CLASSPATH variable). I have tried calling the program with the -classpath /path/to/JExcelAPI switch, but that does not work either. Can you help me find the way to make the apache user aware of the JExcelAPI? Is there a way to set the CLASSPATH environment variable for the apache user? Thanks
[ "Several solutions come to mind :\n\nCreate a bash script which calls the java program. You can set all the variables you like and debug on the commandline, e.g. sudo -u apache /usr/local/bin/java-task-wrapper. This simplifies calling it from a cgi considerably and the overhead of bash is negligeable compared to sp...
[ 2 ]
[]
[]
[ "apache", "cgi", "java", "linux", "python" ]
stackoverflow_0003783121_apache_cgi_java_linux_python.txt
Q: Parameter names in Python functions that take single object or iterable I have some functions in my code that accept either an object or an iterable of objects as input. I was taught to use meaningful names for everything, but I am not sure how to comply here. What should I call a parameter that can a sinlge object or an iterable of objects? I have come up with two ideas, but I don't like either of them: FooOrManyFoos - This expresses what goes on, but I could imagine that someone not used to it could have trouble understanding what it means right away param - Some generic name. This makes clear that it can be several things, but does explain nothing about what the parameter is used for. Normally I call iterables of objects just the plural of what I would call a single object. I know this might seem a little bit compulsive, but Python is supposed to be (among others) about readability. A: I have some functions in my code that accept either an object or an iterable of objects as input. This is a very exceptional and often very bad thing to do. It's trivially avoidable. i.e., pass [foo] instead of foo when calling this function. The only time you can justify doing this is when (1) you have an installed base of software that expects one form (iterable or singleton) and (2) you have to expand it to support the other use case. So. You only do this when expanding an existing function that has an existing code base. If this is new development, Do Not Do This. I have come up with two ideas, but I don't like either of them: [Only two?] FooOrManyFoos - This expresses what goes on, but I could imagine that someone not used to it could have trouble understanding what it means right away What? Are you saying you provide NO other documentation, and no other training? No support? No advice? Who is the "someone not used to it"? Talk to them. Don't assume or imagine things about them. Also, don't use Leading Upper Case Names. param - Some generic name. This makes clear that it can be several things, but does explain nothing about what the parameter is used for. Terrible. Never. Do. This. I looked in the Python library for examples. Most of the functions that do this have simple descriptions. http://docs.python.org/library/functions.html#isinstance isinstance(object, classinfo) They call it "classinfo" and it can be a class or a tuple of classes. You could do that, too. You must consider the common use case and the exceptions. Follow the 80/20 rule. 80% of the time, you can replace this with an iterable and not have this problem. In the remaining 20% of the cases, you have an installed base of software built around an assumption (either iterable or single item) and you need to add the other case. Don't change the name, just change the documentation. If it used to say "foo" it still says "foo" but you make it accept an iterable of "foo's" without making any change to the parameters. If it used to say "foo_list" or "foo_iter", then it still says "foo_list" or "foo_iter" but it will quietly tolerate a singleton without breaking. 80% of the code is the legacy ("foo" or "foo_list") 20% of the code is the new feature ("foo" can be an iterable or "foo_list" can be a single object.) A: I guess I'm a little late to the party, but I'm suprised that nobody suggested a decorator. def withmany(f): def many(many_foos): for foo in many_foos: yield f(foo) f.many = many return f @withmany def process_foo(foo): return foo + 1 processed_foo = process_foo(foo) for processed_foo in process_foo.many(foos): print processed_foo I saw a similar pattern in one of Alex Martelli's posts but I don't remember the link off hand. A: It sounds like you're agonizing over the ugliness of code like: def ProcessWidget(widget_thing): # Infer if we have a singleton instance and make it a # length 1 list for consistency if isinstance(widget_thing, WidgetType): widget_thing = [widget_thing] for widget in widget_thing: #... My suggestion is to avoid overloading your interface to handle two distinct cases. I tend to write code that favors re-use and clear naming of methods over clever dynamic use of parameters: def ProcessOneWidget(widget): #... def ProcessManyWidgets(widgets): for widget in widgets: ProcessOneWidget(widget) Often, I start with this simple pattern, but then have the opportunity to optimize the "Many" case when there are efficiencies to gain that offset the additional code complexity and partial duplication of functionality. If this convention seems overly verbose, one can opt for names like "ProcessWidget" and "ProcessWidgets", though the difference between the two is a single easily missed character. A: You can use *args magic (varargs) to make your params always be iterable. Pass a single item or multiple known items as normal function args like func(arg1, arg2, ...) and pass iterable arguments with an asterisk before, like func(*args) Example: # magic *args function def foo(*args): print args # many ways to call it foo(1) foo(1, 2, 3) args1 = (1, 2, 3) args2 = [1, 2, 3] args3 = iter((1, 2, 3)) foo(*args1) foo(*args2) foo(*args3) A: Can you name your parameter in a very high-level way? people who read the code are more interested in knowing what the parameter represents ("clients") than what their type is ("list_of_tuples"); the type can be defined in the function documentation string, which is a good thing since it might change, in the future (the type is sometimes an implementation detail). A: I would do 1 thing, def myFunc(manyFoos): if not type(manyFoos) in (list,tuple): manyFoos = [manyFoos] #do stuff here so then you don't need to worry anymore about its name. in a function you should try to achieve to have 1 action, accept the same parameter type and return the same type. Instead of filling the functions with ifs you could have 2 functions. A: Since you don't care exactly what kind of iterable you get, you could try to get an iterator for the parameter using iter(). If iter() raises a TypeError exception, the parameter is not iterable, so you then create a list or tuple of the one item, which is iterable and Bob's your uncle. def doIt(foos): try: iter(foos) except TypeError: foos = [foos] for foo in foos: pass # do something here The only problem with this approach is if foo is a string. A string is iterable, so passing in a single string rather than a list of strings will result in iterating over the characters in a string. If this is a concern, you could add an if test for it. At this point it's getting wordy for boilerplate code, so I'd break it out into its own function. def iterfy(iterable): if isinstance(iterable, basestring): iterable = [iterable] try: iter(iterable) except TypeError: iterable = [iterable] return iterable def doIt(foos): for foo in iterfy(foos): pass # do something Unlike some of those answering, I like doing this, since it eliminates one thing the caller could get wrong when using your API. "Be conservative in what you generate but liberal in what you accept." To answer your original question, i.e. what you should name the parameter, I would still go with "foos" even though you will accept a single item, since your intent is to accept a list. If it's not iterable, that is technically a mistake, albeit one you will correct for the caller since processing just the one item is probably what they want. Also, if the caller thinks they must pass in an iterable even of one item, well, that will of course work fine and requires very little syntax, so why worry about correcting their misapprehension? A: I would go with a name explaining that the parameter can be an instance or a list of instances. Say one_or_more_Foo_objects. I find it better than the bland param.
Parameter names in Python functions that take single object or iterable
I have some functions in my code that accept either an object or an iterable of objects as input. I was taught to use meaningful names for everything, but I am not sure how to comply here. What should I call a parameter that can a sinlge object or an iterable of objects? I have come up with two ideas, but I don't like either of them: FooOrManyFoos - This expresses what goes on, but I could imagine that someone not used to it could have trouble understanding what it means right away param - Some generic name. This makes clear that it can be several things, but does explain nothing about what the parameter is used for. Normally I call iterables of objects just the plural of what I would call a single object. I know this might seem a little bit compulsive, but Python is supposed to be (among others) about readability.
[ "\nI have some functions in my code that accept either an object or an iterable of objects as input.\n\nThis is a very exceptional and often very bad thing to do. It's trivially avoidable.\ni.e., pass [foo] instead of foo when calling this function.\nThe only time you can justify doing this is when (1) you have an...
[ 7, 4, 3, 2, 1, 1, 1, 0 ]
[ "I'm working on a fairly big project now and we're passing maps around and just calling our parameter map. The map contents vary depending on the function that's being called. This probably isn't the best situation, but we reuse a lot of the same code on the maps, so copying and pasting is easier.\nI would say inst...
[ -1 ]
[ "naming_conventions", "python" ]
stackoverflow_0003683116_naming_conventions_python.txt
Q: How do I make a Python script (installed as a service) survive a logout? I followed the instructions in this answer about writing a Python script to be used as a service. I placed my looping code in def main(). I installed the service with python my_script.py install. I was able to Start and Stop the service through services.msc in Windows XP. It's a logging program that is intended to write logs as long as Windows is running. It shouldn't care about who or whether anyone logs in or out. My problem is that the service will stop when I logout. How do I make it survive logouts? A: The system generates CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT signals when the user closes the console, logs off, or shuts down the system so that the process has an opportunity to clean up before termination. To ensure that you detach your service from all this, you will need to use the control handler to set it that way: win32api.SetConsoleCtrlHandler(lambda x: True, True) Check out : http://msdn.microsoft.com/en-us/library/ms685049(v=VS.85).aspx Just checked out that there is recipe that illustrates this very well for you. http://code.activestate.com/recipes/551780-win-services-helper/
How do I make a Python script (installed as a service) survive a logout?
I followed the instructions in this answer about writing a Python script to be used as a service. I placed my looping code in def main(). I installed the service with python my_script.py install. I was able to Start and Stop the service through services.msc in Windows XP. It's a logging program that is intended to write logs as long as Windows is running. It shouldn't care about who or whether anyone logs in or out. My problem is that the service will stop when I logout. How do I make it survive logouts?
[ "The system generates CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT signals when the user closes the console, logs off, or shuts down the system so that the process has an opportunity to clean up before termination. To ensure that you detach your service from all this, you will need to use the contro...
[ 2 ]
[]
[]
[ "logout", "python", "service", "windows_xp" ]
stackoverflow_0003783269_logout_python_service_windows_xp.txt
Q: How to submit web forms using Python? First of all, sorry if this question is a little vague and rambling! I'm ok with Python, but I've never done anything HTTP related before. I'm trying to automate submitting a web form, and from reading some of this page I understand that I need to do a POST request. I also found a code snippet demonstrating the urllib module: import urllib params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) print f.read() But I still don't really understand what I'm doing. I need to trigger "submit" somehow, and I assume the actual data I'm submitting will go in the params somewhere? A: The code there should do what you want. Whatever data you want to use should go into the params as you have in your example. When the params are included as an argument to urlopen a POST request will be used (instead of a GET). By just calling urlopen I believe the POST request will be submitted. If you want the response however you will need to use f.read().
How to submit web forms using Python?
First of all, sorry if this question is a little vague and rambling! I'm ok with Python, but I've never done anything HTTP related before. I'm trying to automate submitting a web form, and from reading some of this page I understand that I need to do a POST request. I also found a code snippet demonstrating the urllib module: import urllib params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) print f.read() But I still don't really understand what I'm doing. I need to trigger "submit" somehow, and I assume the actual data I'm submitting will go in the params somewhere?
[ "The code there should do what you want.\nWhatever data you want to use should go into the params as you have in your example. When the params are included as an argument to urlopen a POST request will be used (instead of a GET).\nBy just calling urlopen I believe the POST request will be submitted. If you want the...
[ 0 ]
[]
[]
[ "form_submit", "python", "webforms" ]
stackoverflow_0003783260_form_submit_python_webforms.txt
Q: What is the fastest way to read in a large data file of text columns? I have a data file of almost 9 million lines (soon to be more than 500 million lines) and I'm looking for the fastest way to read it in. The five aligned columns are padded and separated by spaces, so I know where on each line to look for the two fields that I want. My Python routine takes 45 secs: import sys,time start = time.time() filename = 'test.txt' # space-delimited, aligned columns trans=[] numax=0 for line in open(linefile,'r'): nu=float(line[-23:-11]); S=float(line[-10:-1]) if nu>numax: numax=nu trans.append((nu,S)) end=time.time() print len(trans),'transitions read in %.1f secs' % (end-start) print 'numax =',numax whereas the routine I've come up with in C is a more pleasing 4 secs: #include <stdio.h> #include <stdlib.h> #include <time.h> #define BPL 47 #define FILENAME "test.txt" #define NTRANS 8858226 int main(void) { size_t num; unsigned long i; char buf[BPL]; char* sp; double *nu, *S; double numax; FILE *fp; time_t start,end; nu = (double *)malloc(NTRANS * sizeof(double)); S = (double *)malloc(NTRANS * sizeof(double)); start = time(NULL); if ((fp=fopen(FILENAME,"rb"))!=NULL) { i=0; numax=0.; do { if (i==NTRANS) {break;} num = fread(buf, 1, BPL, fp); buf[BPL-1]='\0'; sp = &buf[BPL-10]; S[i] = atof(sp); buf[BPL-11]='\0'; sp = &buf[BPL-23]; nu[i] = atof(sp); if (nu[i]>numax) {numax=nu[i];} ++i; } while (num == BPL); fclose(fp); end = time(NULL); fprintf(stdout, "%d lines read; numax = %12.6f\n", (int)i, numax); fprintf(stdout, "that took %.1f secs\n", difftime(end,start)); } else { fprintf(stderr, "Error opening file %s\n", FILENAME); free(nu); free(S); return EXIT_FAILURE; } free(nu); free(S); return EXIT_SUCCESS; } Solutions in Fortran, C++ and Java take intermediate amounts of time (27 secs, 20 secs, 8 secs). My question is: have I made any outrageous blunders in the above (particularly the C-code)? And is there any way to speed up the Python routine? I quickly realised that storing my data in an array of tuples was better than instantiating a class for each entry. A: Some points: Your C routine is cheating; it is being tipped off with the filesize, and is pre-allocating ... Python: consider using array.array('d') ... one each for S and nu. Then try pre-allocation. Python: write your routine as a function and call it -- accessing function-local variables is rather faster than accessing module-global variables. A: In the C implementation, you could try swapping the fopen()/fread()/fclose() library functions for the lower-level system calls open()/read()/close(). A speedup may come from the fact that fread() does a lot of buffering, whereas read() does not. Additionally, calling read() less often with bigger chunks will reduce the number of system calls and therefore you'll have less switching between userspace and kernelspace. What the kernel does when you issue a read() system call (doesn't matter if it was invoked from the fread() library function) is read the data from the disk and then copy it to the userspace. The copying part becomes expensive if you issue the system call very often in your code. By reading in larger chunks you'll end up with less context switches and less copying. Keep in mind though that read() isn't guaranteed to return a block of the exact number of bytes you wanted. This is why in a reliable and proper implementation you always have to check the return value of the read(). A: An approach that could probably be applied to the C, C++ and python version would be to use memory map the file. The most signficant benefit is that it can reduce the amount of double-handling of data as it is copied from one buffer to another. In many cases there are also benefits due to the reduction in the number of system calls for I/O. A: You have the 1 and the BPL arguments the wrong way around in fread() (the way you have it, it could read a partial line, which you don't test for). You should also be testing the return value of fread() before you try and use the returned data. You can might be able to speed the C version up a bit by reading more than a line at a time #define LINES_PER_READ 1000 char buf[LINES_PER_READ][BPL]; /* ... */ while (i < NTRANS && (num = fread(buf, BPL, LINES_PER_READ, fp)) > 0) { int line; for (line = 0; i < NTRANS && line < num; line++) { buf[line][BPL-1]='\0'; sp = &buf[line][BPL-10]; S[i] = atof(sp); buf[line][BPL-11]='\0'; sp = &buf[line][BPL-23]; nu[i] = atof(sp); if (nu[i]>numax) {numax=nu[i];} ++i; } } On systems supporting posix_fadvise(), you should also do this upfront, after opening the file: posix_fadvise(fileno(fp), 0, 0, POSIX_FADV_SEQUENTIAL);
What is the fastest way to read in a large data file of text columns?
I have a data file of almost 9 million lines (soon to be more than 500 million lines) and I'm looking for the fastest way to read it in. The five aligned columns are padded and separated by spaces, so I know where on each line to look for the two fields that I want. My Python routine takes 45 secs: import sys,time start = time.time() filename = 'test.txt' # space-delimited, aligned columns trans=[] numax=0 for line in open(linefile,'r'): nu=float(line[-23:-11]); S=float(line[-10:-1]) if nu>numax: numax=nu trans.append((nu,S)) end=time.time() print len(trans),'transitions read in %.1f secs' % (end-start) print 'numax =',numax whereas the routine I've come up with in C is a more pleasing 4 secs: #include <stdio.h> #include <stdlib.h> #include <time.h> #define BPL 47 #define FILENAME "test.txt" #define NTRANS 8858226 int main(void) { size_t num; unsigned long i; char buf[BPL]; char* sp; double *nu, *S; double numax; FILE *fp; time_t start,end; nu = (double *)malloc(NTRANS * sizeof(double)); S = (double *)malloc(NTRANS * sizeof(double)); start = time(NULL); if ((fp=fopen(FILENAME,"rb"))!=NULL) { i=0; numax=0.; do { if (i==NTRANS) {break;} num = fread(buf, 1, BPL, fp); buf[BPL-1]='\0'; sp = &buf[BPL-10]; S[i] = atof(sp); buf[BPL-11]='\0'; sp = &buf[BPL-23]; nu[i] = atof(sp); if (nu[i]>numax) {numax=nu[i];} ++i; } while (num == BPL); fclose(fp); end = time(NULL); fprintf(stdout, "%d lines read; numax = %12.6f\n", (int)i, numax); fprintf(stdout, "that took %.1f secs\n", difftime(end,start)); } else { fprintf(stderr, "Error opening file %s\n", FILENAME); free(nu); free(S); return EXIT_FAILURE; } free(nu); free(S); return EXIT_SUCCESS; } Solutions in Fortran, C++ and Java take intermediate amounts of time (27 secs, 20 secs, 8 secs). My question is: have I made any outrageous blunders in the above (particularly the C-code)? And is there any way to speed up the Python routine? I quickly realised that storing my data in an array of tuples was better than instantiating a class for each entry.
[ "Some points:\n\nYour C routine is cheating; it is being tipped off with the filesize, and is pre-allocating ...\nPython: consider using array.array('d') ... one each for S and nu. Then try pre-allocation.\nPython: write your routine as a function and call it -- accessing function-local variables is rather faster t...
[ 4, 3, 3, 1 ]
[ "Another possible speed-up, given the number of times you need to do it, is to use pointers to S and nu instead of indexing into arrays, e.g.,\ndouble *pS = S, *pnu = nu;\n...\n*pS++ = atof(sp);\n*pnu = atof(sp);\n...\n\nAlso, since you are always converting from char to double at the same locations in buf, pre-com...
[ -1 ]
[ "c", "dataset", "io", "python" ]
stackoverflow_0003779073_c_dataset_io_python.txt
Q: How do I use Avro to process a stream that I cannot seek? I am using Avro 1.4.0 to read some data out of S3 via the Python avro bindings and the boto S3 library. When I open an avro.datafile.DataFileReader on the file like objects returned by boto it immediately fails when it tries to seek(). For now I am working around this by reading the S3 objects into temporary files. I would like to be able to stream through any python object that supports read(). Can anybody provide advice? A: I am not very clear on this and this may not be the answer. I was of the impression that diter = datafile.DataFileReader(..) returns an iterator so that you could do the following for data in diter: .... Correct me, if I am wrong here. Revisiting my answer: You are right, datafile.DataFileReader does not play well with a reader for which seek would fail. it uses avro.io.BinaryDecoder which accepts a reader. class BinaryDecoder(object): """Read leaf values.""" def __init__(self, reader): """ reader is a Python object on which we can call read, seek, and tell. """ self._reader = reader What you can do is create your own reader class that does provide these functions - read , seek and tell but internally utilizes boto S3 library to read of data.
How do I use Avro to process a stream that I cannot seek?
I am using Avro 1.4.0 to read some data out of S3 via the Python avro bindings and the boto S3 library. When I open an avro.datafile.DataFileReader on the file like objects returned by boto it immediately fails when it tries to seek(). For now I am working around this by reading the S3 objects into temporary files. I would like to be able to stream through any python object that supports read(). Can anybody provide advice?
[ "I am not very clear on this and this may not be the answer.\nI was of the impression that \nditer = datafile.DataFileReader(..) \n\nreturns an iterator so that you could do the following\nfor data in diter:\n ....\n\nCorrect me, if I am wrong here.\nRevisiting my answer:\nYou are right, datafile.DataFileReader ...
[ 2 ]
[]
[]
[ "avro", "boto", "hadoop", "python" ]
stackoverflow_0003783453_avro_boto_hadoop_python.txt
Q: 'else' statement in list comprehensions I've got a variable that could either be a string or a tuple (I don't know ahead of time) and I need to work with it as a list. Essentially, I want to transform the following into a list comprehension. variable = 'id' final = [] if isinstance(variable, str): final.append(variable) elif isinstance(variable, tuple): final = list(variable) I was thinking something along the lines of the following (which gives me a syntax error). final = [var for var in variable if isinstance(variable, tuple) else variable] I've seen this question but it's not the same because the asker could use the for loop at the end; mine only applies if it's a tuple. NOTE: I would like the list comprehension to work if I use isinstance(variable, list) as well as the tuple one. A: I think you want: final = [variable] if isinstance(variable, str) else list(variable) A: You just need to rearrange it a bit. final = [var if isinstance(variable, tuple) else variable for var in variable] Or maybe I misunderstood and you really want final = variable if not isinstance(variable, tuple) else [var for var in variable]
'else' statement in list comprehensions
I've got a variable that could either be a string or a tuple (I don't know ahead of time) and I need to work with it as a list. Essentially, I want to transform the following into a list comprehension. variable = 'id' final = [] if isinstance(variable, str): final.append(variable) elif isinstance(variable, tuple): final = list(variable) I was thinking something along the lines of the following (which gives me a syntax error). final = [var for var in variable if isinstance(variable, tuple) else variable] I've seen this question but it's not the same because the asker could use the for loop at the end; mine only applies if it's a tuple. NOTE: I would like the list comprehension to work if I use isinstance(variable, list) as well as the tuple one.
[ "I think you want:\nfinal = [variable] if isinstance(variable, str) else list(variable)\n\n", "You just need to rearrange it a bit.\nfinal = [var if isinstance(variable, tuple) else variable for var in variable]\n\nOr maybe I misunderstood and you really want\nfinal = variable if not isinstance(variable, tuple) e...
[ 5, 2 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003783579_list_comprehension_python.txt
Q: Selecting a Python Web Framework This may seem like a subjective question. But it is not (that's not the idea, at least). I'm developing an Advertising software (like AdWords, AdBrite, etc) and i've decide to use Python. And would like to use one of those well known web frameworks (Django, Cherrypy, pylons, etc). The question is: Given that it will have just a few Models (seven or eight), which has the best cache support? and What is the most efficient retrieving data from a MySQL database? Thanks! A: check out Flask. Its easy, its fast, works on top of Werkzeug, uses Jinja2 templating and SQLAlchemy for the model domain. http://flask.pocoo.org/ A: Performance should be more or less equal. If you want to keep it simple look at cherrypy, pylons and other lightweight frameworks. -> http://wiki.python.org/moin/WebFrameworks gives a nice overview. A: If you want to use Python to do complex SQL queries on your database, e.g. eagerloading or filtering on the fly you might be wanting SQLAlchemy. TurboGears 2 is a framework which comes with SQLAlchemy as standard, check out their caching page for more info on the second part of your answer. A: CherryPy is the only framework I'm aware of that does real HTTP caching out of the box (but look at "beaker" for a WSGI component solution). Many of the others give you tools to store arbitrary objects in Memcached or other storage. A: I am only familiar with Django, and can tell you that it has a very robust middleware handler and very straightforward cache management. Also, the ORM (object-relational mapper; connect objects to databases) can have Postgre or MySQL as the engine, so you are free to choose the fastest one (I think that other frameworks use SQLAlchemy's ORM, which is also super cool and fast) Check: Middleware Cache
Selecting a Python Web Framework
This may seem like a subjective question. But it is not (that's not the idea, at least). I'm developing an Advertising software (like AdWords, AdBrite, etc) and i've decide to use Python. And would like to use one of those well known web frameworks (Django, Cherrypy, pylons, etc). The question is: Given that it will have just a few Models (seven or eight), which has the best cache support? and What is the most efficient retrieving data from a MySQL database? Thanks!
[ "check out Flask. Its easy, its fast, works on top of Werkzeug, uses Jinja2 templating and SQLAlchemy for the model domain. http://flask.pocoo.org/\n", "Performance should be more or less equal. If you want to keep it simple look at cherrypy, pylons and other lightweight frameworks.\n-> http://wiki.python.org/moi...
[ 7, 2, 1, 1, 0 ]
[]
[]
[ "cherrypy", "django", "mysql", "pylons", "python" ]
stackoverflow_0003781802_cherrypy_django_mysql_pylons_python.txt
Q: Python Exception handling in Google App Engine I have exception handling in my app engine app. The code work perfectly fine on the dev server. But when I upload the file on the app engine server, I get a syntax error. Here is the traceback: Exception in request: Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/handlers/base.py", line 68, in get_response callback, callback_args, callback_kwargs = resolver.resolve(request.path) File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/urlresolvers.py", line 162, in resolve sub_match = pattern.resolve(new_path) File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/urlresolvers.py", line 118, in resolve return self.callback, args, kwargs File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/urlresolvers.py", line 125, in _get_callback self._callback = getattr(__import__(mod_name, {}, {}, ['']), func_name) File "/base/data/home/apps/foundationofwikipedia/1-1.345018280774164953/src/views.py", line 6, in <module> import search_list File "/base/data/home/apps/foundationofwikipedia/1-1.345018280774164953/src/search_list.py", line 32 except Exception as error: ^ SyntaxError: invalid syntax I do not understand this as the code works fine in the dev server. It is probably something trivial. HELP! A: You're running python 2.6+ on your dev server. App Engine runs on python 2.5.2, which doesn't have the except Exception as foo: syntax. Replace as with a ,, and while you're at it, install Python 2.5 on your dev machine.
Python Exception handling in Google App Engine
I have exception handling in my app engine app. The code work perfectly fine on the dev server. But when I upload the file on the app engine server, I get a syntax error. Here is the traceback: Exception in request: Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/handlers/base.py", line 68, in get_response callback, callback_args, callback_kwargs = resolver.resolve(request.path) File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/urlresolvers.py", line 162, in resolve sub_match = pattern.resolve(new_path) File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/urlresolvers.py", line 118, in resolve return self.callback, args, kwargs File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/urlresolvers.py", line 125, in _get_callback self._callback = getattr(__import__(mod_name, {}, {}, ['']), func_name) File "/base/data/home/apps/foundationofwikipedia/1-1.345018280774164953/src/views.py", line 6, in <module> import search_list File "/base/data/home/apps/foundationofwikipedia/1-1.345018280774164953/src/search_list.py", line 32 except Exception as error: ^ SyntaxError: invalid syntax I do not understand this as the code works fine in the dev server. It is probably something trivial. HELP!
[ "You're running python 2.6+ on your dev server. App Engine runs on python 2.5.2, which doesn't have the except Exception as foo: syntax. Replace as with a ,, and while you're at it, install Python 2.5 on your dev machine.\n" ]
[ 5 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003783758_django_google_app_engine_python.txt
Q: Is there a Pythonic way to make this logic more elegant? I'm new to Python, and I've been playing around with it for simple tasks. I have a bunch of CSVs which I need to manipulate in complex ways, but I'm breaking this up into smaller tasks for the sake of learning Python. For now, given a list of strings, I want to remove user-defined title prefixes of any names in the strings. Any string which contains a name will contain only a name, with or without a title prefix. I have the following, and it works, but it just feels unnecessarily complicated. Is there a more Pythonic way to do this? Thanks! # Return new list without title prefixes for strings in a list of strings. def strip_titles(line, title_prefixes): new_csv_line = [] for item in line: for title_prefix in title_prefixes: if item.startswith(title_prefix): new_csv_line.append(item[len(title_prefix)+1:]) break else: if title_prefix == title_prefixes[len(title_prefixes)-1]: new_csv_line.append(item) else: continue return new_csv_line if __name__ == "__main__": test_csv_line = ['Mr. Richard Stallman', 'I like cake', 'Mrs. Margaret Thatcher', 'Jean-Claude Van Damme'] test_prefixes = ['Mr.', 'Ms.', 'Mrs.'] print strip_titles(test_csv_line, test_prefixes) A: [re.sub(r'^(Mr|Ms|Mrs)\.\s+', '', s) for s in test_csv_line] A: Assuming that prefixes is variable, perhaps as an aspect of localization, or you prefer not to use a regular expression for some other reason, you could do something like this (untested code): def strip_title(string, prefixes): for prefix in prefixes: if string.startswith(prefix + ' '): return string[len(prefix) + 1:] return string stripped = (list(strip_title(cell, prefixes) for cell in line) for line in lines) This is not particularly efficient, since the algorithm ends up doing a lot of redundant checking (e.g. checking three times if the line starts with M). This sort of thing is a big reason to use regular expressions. Alternatively, you could dynamically build a regular expression, by escaping each prefix and joining them with | branches: def TitleStripper(prefixes): import re escaped_titles = (re.escape(prefix) for prefix in prefixes) prefix_re = re.compile('^({0}) '.format('|'.join(escaped_titles))) def strip_title(string): return prefix_re.sub('', string, 1) return strip_title The function TitleStripper creates a closure function strip_title that works like the previous one but is built for a particular set of prefixes. After you call strip_title = TitleStripper(prefixes) you can just call strip_title(string). Mostly due to the use of regular expressions, this will be a bit faster than the first method, perhaps at the expense of clarity. If you really only ever need to check for three prefixes, either of these methods is overkill, and you should just use a static RE as explained in another answer. A: A more Pythonic approach would be to replace the "end of list" check with an else: clause to the for item in line: loop. The else gets executed if the for loop completes without being interrupted: # Return new list without title prefixes for strings in a list of strings. def strip_titles(line, title_prefixes): new_csv_line = [] for item in line: for title_prefix in title_prefixes: if item.startswith(title_prefix): new_csv_line.append(item[len(title_prefix)+1:]) break else: new_csv_line.append(item) return new_csv_line The logic is otherwise the same as yours.
Is there a Pythonic way to make this logic more elegant?
I'm new to Python, and I've been playing around with it for simple tasks. I have a bunch of CSVs which I need to manipulate in complex ways, but I'm breaking this up into smaller tasks for the sake of learning Python. For now, given a list of strings, I want to remove user-defined title prefixes of any names in the strings. Any string which contains a name will contain only a name, with or without a title prefix. I have the following, and it works, but it just feels unnecessarily complicated. Is there a more Pythonic way to do this? Thanks! # Return new list without title prefixes for strings in a list of strings. def strip_titles(line, title_prefixes): new_csv_line = [] for item in line: for title_prefix in title_prefixes: if item.startswith(title_prefix): new_csv_line.append(item[len(title_prefix)+1:]) break else: if title_prefix == title_prefixes[len(title_prefixes)-1]: new_csv_line.append(item) else: continue return new_csv_line if __name__ == "__main__": test_csv_line = ['Mr. Richard Stallman', 'I like cake', 'Mrs. Margaret Thatcher', 'Jean-Claude Van Damme'] test_prefixes = ['Mr.', 'Ms.', 'Mrs.'] print strip_titles(test_csv_line, test_prefixes)
[ "[re.sub(r'^(Mr|Ms|Mrs)\\.\\s+', '', s) for s in test_csv_line]\n\n", "Assuming that prefixes is variable, perhaps as an aspect of localization, or you prefer not to use a regular expression for some other reason, you could do something like this (untested code):\ndef strip_title(string, prefixes):\n for prefi...
[ 9, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003783728_python.txt
Q: How do I generate a connection reset programatically? I'm sure you've seen the "the connection was reset" message displayed when trying to browse web pages. (The text is from Firefox, other browsers differ.) I need to generate that message/error/condition on demand, to test workarounds. So, how do I generate that condition programmatically? (How to generate a TCP RST from PHP -- or one of the other web-app languages?) Caveats and Conditions: It cannot be a general IP block. The test client must still be able to see the test server when not triggering the condition. Ideally, it would be done at the web-application level (Python, PHP, Coldfusion, Javascript, etc.). Access to routers is problematic. Access to Apache config is a pain. Ideally, it would be triggered by fetching a specific web-page. Bonus if it works on a standard, commercial web host. Update: Sending RST is not enough to cause this condition. See my partial answer, below. I've a solution that works on a local machine, Now need to get it working on a remote host. A: I would recommend doing this via a custom socket via CLI as messing with the apache process could be messy: #!/usr/bin/php -q <?php set_time_limit (0); $sock = socket_create(AF_INET, SOCK_STREAM, 0); socket_bind($sock, '1.1.1.1', 8081) or die('Could not bind to address'); socket_listen($sock); $client = socket_accept($sock); sleep(1); $pid = getmypid(); exec("kill -9 $pid"); ?> This will generate the desired error in Firefox as the connection is closed before read. If you feel insanely daring, you could throw this into a web script but I wouldn't even venture trying that unless you own the box and know what you're doing admin wise. A: I believe you need to close the low-level socket fairly abruptly. You won't be able to do it from Javascript. For the other languages you'll generally need to get a handle on the underlying socket object and close() it manually. I also doubt you can do this through Apache since it is Apache and not your application holding the socket. At best your efforts are likely to generate a HTTP 500 error which is not what you're after. A: Update: This script worked well enough to test our connection-reset workaround, so it's a partial answer. If someone comes up with the full solution that works on a remote host, I'll gladly mark that as the answer. The following script works every time when running and tested on the same machine. But when running on a remote host, the browser gets the following last 3 packets: Source Dest Protocol Info <server> <client> TCP 8081 > 1835 [RST] Seq=2 Len=0 <server> <client> TCP 8081 > 1835 [RST] Seq=2 Len=0 <server> <client> TCP http > 1834 [ACK] Seq=34 Ack=1 Win=6756 Len=0 As you can see, the RST flag is set and sent. But Firefox fails silently with a blank page -- no messages of any kind. Script: <?php $time_lim = 30; $listen_port = 8081; echo '<h1>Testing generation of a connection reset condition.</h1> <p><a target="_blank" href="http://' .$_SERVER["HTTP_HOST"]. ':' .$listen_port. '/"> Click here to load page that gets reset. You have ' . $time_lim . ' seconds.</a> </p> ' ; flush (); ?> <?php //-- Warning! If the script blocks, below, this is not counted against the time limit. set_time_limit ($time_lim); $socket = @socket_create_listen ($listen_port); if (!$socket) { print "Failed to create socket!\n"; exit; } socket_set_nonblock ($socket); //-- Needed, or else script executes until a client interacts with the socket. while (true) { //-- Use @ to suppress warnings. Exception handling didn't work. $client = @socket_accept ($socket); if ($client) break; } /*--- If l_onoff is non-zero and l_linger is zero, all the unsent data will be discarded and RST (reset) is sent to the peer in the case of a connection- oriented socket. */ $linger = array ('l_linger' => 0, 'l_onoff' => 1); socket_set_option ($socket, SOL_SOCKET, SO_LINGER, $linger); //--- If we just close, the Browser gets the RST flag but fails silently (completely blank). socket_close ($socket); echo "<p>Done.</p>"; ?>
How do I generate a connection reset programatically?
I'm sure you've seen the "the connection was reset" message displayed when trying to browse web pages. (The text is from Firefox, other browsers differ.) I need to generate that message/error/condition on demand, to test workarounds. So, how do I generate that condition programmatically? (How to generate a TCP RST from PHP -- or one of the other web-app languages?) Caveats and Conditions: It cannot be a general IP block. The test client must still be able to see the test server when not triggering the condition. Ideally, it would be done at the web-application level (Python, PHP, Coldfusion, Javascript, etc.). Access to routers is problematic. Access to Apache config is a pain. Ideally, it would be triggered by fetching a specific web-page. Bonus if it works on a standard, commercial web host. Update: Sending RST is not enough to cause this condition. See my partial answer, below. I've a solution that works on a local machine, Now need to get it working on a remote host.
[ "I would recommend doing this via a custom socket via CLI as messing with the apache process could be messy:\n#!/usr/bin/php -q\n<?php\n\nset_time_limit (0);\n\n$sock = socket_create(AF_INET, SOCK_STREAM, 0);\n\nsocket_bind($sock, '1.1.1.1', 8081) or die('Could not bind to address');\n\nsocket_listen($sock);\n\n$cl...
[ 2, 1, 1 ]
[]
[]
[ "php", "python", "sockets", "tcp", "web_applications" ]
stackoverflow_0003773566_php_python_sockets_tcp_web_applications.txt
Q: django/python imports performance Can somebody please proof why it's a bad practice to use solution like this: In django views in 98% cases you need to use from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ anyway in my project my every view has these imports and everything is used almost in every second function of a view: from datetime import datetime from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.core import paginator from django.db import connection from django.db.models import Q from django.http import HttpResponseRedirect, Http404, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.utils.translation import ugettext as _ Now add some models and forms, and I have 50 lines of bullshit that is impossible to read at all. First thing that came to my head is of course to make more views, to split some operation and etc and etc.. but still about 30 lines of imports killing my orientation in code. Then I just decided to put everything that being used in views by 95% of a time, to directory /project/app/imports/view.py. Now I have all common stuff just with ONE import, but my co-worker attacked me, that it's highly hard to read this kind of code, because you can't see what is imported, and why the hell it's so hard to open one more tab in your IDE..??? [especially this goes to vim users, they have FRAMES, and he is using vim] I did the same with models, my models has it's own dir, because it's over 50 them in there, and those files are not small - about 150 lines each.. Even these files have few models inside.. so I'm just doing something like : from myapp.models.mymodel import * and there are some places where I just doing: from myapp.models import * [init.py of myapp/imports dir takes place in here] Problems: 1) ok so first problem is namespace, this kind of model importing is maybe really ridiculous.. but decision with views and forms, is just nothing but lazziness to open one more tab in your IDE 2) performance problem? my co-worker really arguing a lot with this argument, that "every import takes 256kb of ram"?? (by running compiled .pyc file? no i don't believe that ;) The question in fact is about performance problem because of imports. p.s. I'm really new in python (just 3 month), and I open to OBJECTIVE arguments for all probs and cons about this solution. UPDATE Once I asked question about how to move imports to standalone file so nobody complained about this =) question is here A: 1) it's nothing but laziness to not prefix your imported names with the module it came from. It's nothing but laziness to not be willing to scroll past the imports to the code. How exactly does having that mess of imports in another file make it any easier to read through? I would leave it in the original file where they are actually used. This improves readability because if I need to know where something came from, then I can just go to the top of the file and check it out (using the emacs mark ring to go right back). It also makes it easier to maintain the list because I just have to do a quick search to see where something is used (or not used). 2) On my machine, it takes ~812 microseconds to import a module. $ python -mtimeit -s'import os' 'reload(os)' 1000 loops, best of 3: 808 usec per loop This will of course vary greatly with where on your PYTHONPATH it is. If performance is that tight, you might be able to squeeze some out by juggling that around. YMMV. I'm not sure where your coworker is getting the 256kb from. That would depend on the size of the code objects involved. >>> import sys >>> sys.getsizeof(sys) 24 >>> sys.getsizeof(sys.modules['__main__']) 24 As you can see, the actual module object only takes 24 bytes on my 32 bit machine. I have a feeling that will be system dependent though. >>> def sizeofmodule(mod): ... return sum(sys.getsizeof(getattr(mod, o)) for o in dir(mod)) ... >>> sizeofmodule(itertools) 8662 >>> sizeofmodule(sys) 10275 >>> sizeofmodule(operator) 5230 A: Keep in mind that you can import a set of subpackages. So from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.core import paginator from django.db import connection from django.db.models import Q from django.http import HttpResponseRedirect, Http404, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.utils.translation import ugettext as _ can become from django import conf, contrib, db, http, shortcuts, template, utils from django.core import urlresolvers, paginator which is brief, lets you avoid writing django everywhere, and leaves it pretty obvious where something like urlresolvers.reverse is coming from. This also has the advantage of not mapping general names like reverse to highly specific functionality, leaving you with more readable code. A: Some points to consider: The time it takes to import a module is, in almost all cases, completely irrelevant: it only happens once. Your Django view module isn't being imported and re-evaluated for every request; it's loaded once and then reused. If your modules are being reloaded constantly, something is catastrophically wrong. Every import is not taking 256kb of memory. Perhaps each individual file, loaded once, is (though I'd doubt that as well), but importing the same file repeatedly is not taking 256kb each and every time; it's merely creating a reference. If memory use is in question, simply profile it--load 10000 of something and see how much memory is used. For Django modules, you don't always need to create a directory for each; I import each model class from models/__init__.py (eg. from Customer import Customer), so I can say from myapp.models import Profile, Customer, Book, .... The tendency for Django views to need a dozen lines of imports at the top really is a problem. It turns into boilerplate, code which you copy and paste every time you start a new file. Source code requiring boilerplate is a major flaw. At the same time, I strongly advise against what some people might recommend: import django and then using fully-qualified module names. The result is typing things like django.core.urlresolvers.reverse. When you find yourself regularly copying and pasting function names because they're so long, something has gone wrong. There's no single, clear, obviously-correct solution to this. Putting the things which are consistently used in another module is a valid solution, but there are legitimate problems with it: it's hard to see what's being imported, and where the results of the import are used. You'll probably find fewer gut-reaction objections if you import the "collection of modules" module itself--import djangohelpers or import djangohelpers as dh. Then, you're writing things like dh.paginator. It gives the names a clear scope, and makes it much easier to see where it's being used and where particular function names are coming from, which you lose with "import *". (You probably do want to import things like Q and _ as bare names, though.)
django/python imports performance
Can somebody please proof why it's a bad practice to use solution like this: In django views in 98% cases you need to use from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ anyway in my project my every view has these imports and everything is used almost in every second function of a view: from datetime import datetime from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.core import paginator from django.db import connection from django.db.models import Q from django.http import HttpResponseRedirect, Http404, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.utils.translation import ugettext as _ Now add some models and forms, and I have 50 lines of bullshit that is impossible to read at all. First thing that came to my head is of course to make more views, to split some operation and etc and etc.. but still about 30 lines of imports killing my orientation in code. Then I just decided to put everything that being used in views by 95% of a time, to directory /project/app/imports/view.py. Now I have all common stuff just with ONE import, but my co-worker attacked me, that it's highly hard to read this kind of code, because you can't see what is imported, and why the hell it's so hard to open one more tab in your IDE..??? [especially this goes to vim users, they have FRAMES, and he is using vim] I did the same with models, my models has it's own dir, because it's over 50 them in there, and those files are not small - about 150 lines each.. Even these files have few models inside.. so I'm just doing something like : from myapp.models.mymodel import * and there are some places where I just doing: from myapp.models import * [init.py of myapp/imports dir takes place in here] Problems: 1) ok so first problem is namespace, this kind of model importing is maybe really ridiculous.. but decision with views and forms, is just nothing but lazziness to open one more tab in your IDE 2) performance problem? my co-worker really arguing a lot with this argument, that "every import takes 256kb of ram"?? (by running compiled .pyc file? no i don't believe that ;) The question in fact is about performance problem because of imports. p.s. I'm really new in python (just 3 month), and I open to OBJECTIVE arguments for all probs and cons about this solution. UPDATE Once I asked question about how to move imports to standalone file so nobody complained about this =) question is here
[ "1) it's nothing but laziness to not prefix your imported names with the module it came from. It's nothing but laziness to not be willing to scroll past the imports to the code. How exactly does having that mess of imports in another file make it any easier to read through? I would leave it in the original file whe...
[ 5, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003782945_django_python.txt
Q: Python "switch statement" and string formatting I'm trying to do switch statement (with dictionary) and the answer needs to be a formatted string, so for example: descriptions = { 'player_joined_clan': "%(player)s joined clan %(clan)s." % {"player": token1, "clan": token2}, #etc... } Now, this would work if those both tokens were always defined, which is not the case. Plus I believe it is formatting all the strings in the dictionary, which is not needed, it should only format the one that will be needed. So, I came up with this very unusual and partially dumb solution using lambda descriptions = { 'player_joined_clan': lambda x: "%(player)s joined clan %(clan)s." % {"player": token1, "clan": token2}, } Which I can then call with descriptions["player_joined_clan"](0), it will work as expected but ehh, so ugly and unintuitive... I'm clearly missing something here. Any tips appreciated, thanks in advance. A: If I'm understanding correctly, I'd recommend a collections.defaultdict. This isn't really what I'd call a "switch" statement, but I think the end result is close to what you're looking for. I can best explain with full code, data, and application. Obviously, the key line is the defualtdict line. >>> import collections >>> >>> descriptions = { ... 'player_joined_clan' : '%(player)s joined clan %(clan)s', ... 'player_left' : '%(player)s left', ... 'player_hit_player' : '%(player)s (of %(clan)s) hit %(player2)s (of %(clan2)s)', ... } >>> >>> data = [ ... {'player': 'PlayerA'}, ... {'player': 'PlayerB', 'clan' : 'ClanB'}, ... {'clan' : 'ClanC'}, ... {'clan' : 'ClanDA', 'player2': 'PlayerDB'}, ... ] >>> >>> for item in data: ... print item ... item = collections.defaultdict(lambda : '"<unknown>"', **item) ... for key in descriptions: ... print ' %s: %s' % (key, descriptions[key] % item) ... print ... {'player': 'PlayerA'} player_joined_clan: PlayerA joined clan "<unknown>" player_left: PlayerA left player_hit_player: PlayerA (of "<unknown>") hit "<unknown>" (of "<unknown>") {'clan': 'ClanB', 'player': 'PlayerB'} player_joined_clan: PlayerB joined clan ClanB player_left: PlayerB left player_hit_player: PlayerB (of ClanB) hit "<unknown>" (of "<unknown>") {'clan': 'ClanC'} player_joined_clan: "<unknown>" joined clan ClanC player_left: "<unknown>" left player_hit_player: "<unknown>" (of ClanC) hit "<unknown>" (of "<unknown>") {'clan': 'ClanDA', 'player2': 'PlayerDB'} player_joined_clan: "<unknown>" joined clan ClanDA player_left: "<unknown>" left player_hit_player: "<unknown>" (of ClanDA) hit PlayerDB (of "<unknown>") Or, if you want it more customizable than simply a lambda with one string, you can define your own defaultdict class, such as: class my_defaultdict(collections.defaultdict): def __missing__(self, key): return '<unknown %s>' % key change the line to use your class instead of the default one: #item = collections.defaultdict(lambda : '"<unknown>"', **item) item = my_defaultdict(**item) and, voila, the output: {'player': 'PlayerA'} player_joined_clan: PlayerA joined clan <unknown clan> player_left: PlayerA left player_hit_player: PlayerA (of <unknown clan>) hit <unknown player2> (of <unknown clan2>) {'clan': 'ClanB', 'player': 'PlayerB'} player_joined_clan: PlayerB joined clan ClanB player_left: PlayerB left player_hit_player: PlayerB (of ClanB) hit <unknown player2> (of <unknown clan2>) {'clan': 'ClanC'} player_joined_clan: <unknown player> joined clan ClanC player_left: <unknown player> left player_hit_player: <unknown player> (of ClanC) hit <unknown player2> (of <unknown clan2>) {'clan': 'ClanDA', 'player2': 'PlayerDB'} player_joined_clan: <unknown player> joined clan ClanDA player_left: <unknown player> left player_hit_player: <unknown player> (of ClanDA) hit PlayerDB (of <unknown clan2>) See the documentation for collections.defaultdict for more examples. Edit: I forgot that this __missing__ functionality was added to the standard dict class in python 2.5. So an even simpler approach doesn't even involve collections.defaultdict-- just subclass dict: class my_defaultdict(dict): def __missing__(self, key): return '<unknown %s>' % key A: I would think that you want the descriptions dictionary to contain only the format strings, e.g.: descriptions = { 'player_joined_clan': "%(player)s joined clan %(clan)s.", #etc... } Then you'd have a function that received a description key and a dictionary of event-specific data, that would produce the formatted message, something like: def getMessage( key, eventDataDict ): return descriptions[key] % eventDataDict In fact, I think that the way you have written your example, token1 etc. would be evaluated at the time of the declaration of descriptions -- when I presume what you want is for the message to be formatted for different values of these variables at different times. A: I think what you want to do is add another layer that selects a formatter based on the presence or absence of the various dictionary keys. So you could use something like formatters = { set('player', 'team'): "{player} joined {team}".format, set('player'): "Hello {player}.".format, set('team'): "{team} FTW!".format, set(): "Something happened.".format} to establish which format string will be used. Note that I'm using the new-style format strings that work with str.format rather than the old-style ones. They're recommended over the older template % data ones. And then to get a formatting function you can do fmt = descriptions[set(eventDataDict.keys())] and then call formatted_greeting = fmt(eventDataDict) This is inferior to a case statement in that there's no default case; if you need that you could wrap the access of descriptions in a try ... except KeyError construct, probably all within a function called e.g. format_description. You might want to subclass dict and make this a method of that class, depending on how your code is structured.
Python "switch statement" and string formatting
I'm trying to do switch statement (with dictionary) and the answer needs to be a formatted string, so for example: descriptions = { 'player_joined_clan': "%(player)s joined clan %(clan)s." % {"player": token1, "clan": token2}, #etc... } Now, this would work if those both tokens were always defined, which is not the case. Plus I believe it is formatting all the strings in the dictionary, which is not needed, it should only format the one that will be needed. So, I came up with this very unusual and partially dumb solution using lambda descriptions = { 'player_joined_clan': lambda x: "%(player)s joined clan %(clan)s." % {"player": token1, "clan": token2}, } Which I can then call with descriptions["player_joined_clan"](0), it will work as expected but ehh, so ugly and unintuitive... I'm clearly missing something here. Any tips appreciated, thanks in advance.
[ "If I'm understanding correctly, I'd recommend a collections.defaultdict.\nThis isn't really what I'd call a \"switch\" statement, but I think the end result is close to what you're looking for.\nI can best explain with full code, data, and application.\nObviously, the key line is the defualtdict line.\n>>> import ...
[ 3, 1, 1 ]
[]
[]
[ "lambda", "python", "switch_statement" ]
stackoverflow_0003783585_lambda_python_switch_statement.txt
Q: Calling PHP from Python Is it possible to run a PHP script using python? A: You can look into the subprocess class, more specifically, subprocess.call() subprocess.call(*popenargs, **kwargs) subprocess.call(["php", "path/to/script.php"]); A: You can use the Python OS module. You can run any script by calling os.system('php -f file.php') The issue would be getting return values from PHP to Python here.
Calling PHP from Python
Is it possible to run a PHP script using python?
[ "You can look into the subprocess class, more specifically, subprocess.call()\nsubprocess.call(*popenargs, **kwargs)\n\nsubprocess.call([\"php\", \"path/to/script.php\"]);\n\n", "You can use the Python OS module. You can run any script by calling \nos.system('php -f file.php')\n\nThe issue would be getting return...
[ 14, 4 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003784138_php_python.txt
Q: Python3 int, long unification implementation I just read through a PEP concerning the unification of ints and longs in Python3k in PEP 237. The approach used in this seems very interesting. The approach is to create a new type "integer" which is the abstract base class of int and long. Also, performing operations on ints which result in very large numbers will no longer result in an OverflowError, instead it'll return a long. I'd like to see and try to understand the underlying implementation of this in Python3k. How should I go about that? Which files contain the details about "type" implementations? So far I have only ventured out to read most of the non-C python stdlib modules; hence I am unclear on where exactly to look. A: Start with Include/longobject.h and Objects/longobject.h These paths are relative to the root of a Python source tree. Make sure to arm yourself with an editor suitable for browsing C code conveniently, or generate a HTML interlinked reference with GNU global. Also, it would surely help to read this article on internals of objects in Python 3, as well as its sequel.
Python3 int, long unification implementation
I just read through a PEP concerning the unification of ints and longs in Python3k in PEP 237. The approach used in this seems very interesting. The approach is to create a new type "integer" which is the abstract base class of int and long. Also, performing operations on ints which result in very large numbers will no longer result in an OverflowError, instead it'll return a long. I'd like to see and try to understand the underlying implementation of this in Python3k. How should I go about that? Which files contain the details about "type" implementations? So far I have only ventured out to read most of the non-C python stdlib modules; hence I am unclear on where exactly to look.
[ "Start with Include/longobject.h and Objects/longobject.h These paths are relative to the root of a Python source tree. Make sure to arm yourself with an editor suitable for browsing C code conveniently, or generate a HTML interlinked reference with GNU global.\nAlso, it would surely help to read this article on in...
[ 3 ]
[]
[]
[ "c", "python", "python_3.x" ]
stackoverflow_0003784273_c_python_python_3.x.txt
Q: Python, print names and values of all bound variables Is there a way to have Python print the names and values of all bound variables? (without redesigning the program to store them all in a single list) A: globals() and locals() should give you what you're looking for. A: Yes you can, it is a rather dirty way to do it, but it is good for debugging etc from pprint import pprint def getCurrentVariableState(): pprint(locals()) pprint(globals()) A: dir(...) dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns: for a module object: the module's attributes. for a class object: its attributes, and recursively the attributes of its bases. for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes. A: globals() and locals() each return a dictionary representing the symbol table in global and local scopes respectively.
Python, print names and values of all bound variables
Is there a way to have Python print the names and values of all bound variables? (without redesigning the program to store them all in a single list)
[ "globals() and locals() should give you what you're looking for.\n", "Yes you can, it is a rather dirty way to do it, but it is good for debugging etc\nfrom pprint import pprint\n\ndef getCurrentVariableState():\n pprint(locals())\n pprint(globals())\n\n", "dir(...)\n dir([object]) -> list of strings\n...
[ 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003784353_python.txt
Q: Division by Zero Errors I have a problem with this question from my professor. Here is the question: Write the definition of a function typing_speed , that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The second is the length of the time interval in seconds (an int greater than zero). The function returns the typing speed of that person in words per minute (a float ). Here is my code: def typing_speed(num_words,time_interval): if(num_words >= 0 and time_interval > 0): factor = float(60 / time_interval) print factor return float(num_words/(factor)) I know that the "factor" is getting assigned 0 because its not being rounded properly or something. I dont know how to handle these decimals properly. Float isnt doing anything apparently. Any help is appreciated, thankyou. A: When you call float on the division result, it's after the fact the division was treated as an integer division (note: this is Python 2, I assume). It doesn't help, what does help is initially specify the division as a floating-point division, for example by saying 60.0 (the float version of 60): factor = 60.0 / time_interval Another way would be divide 60 by float(time_interval) Note this sample interaction: In [7]: x = 31 In [8]: 60 / x Out[8]: 1 In [9]: 60.0 / x Out[9]: 1.935483870967742 A: Sharth meant to say: from __future__ import python Example: >>> from __future__ import division >>> 4/3 1.3333333333333333 >>>
Division by Zero Errors
I have a problem with this question from my professor. Here is the question: Write the definition of a function typing_speed , that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The second is the length of the time interval in seconds (an int greater than zero). The function returns the typing speed of that person in words per minute (a float ). Here is my code: def typing_speed(num_words,time_interval): if(num_words >= 0 and time_interval > 0): factor = float(60 / time_interval) print factor return float(num_words/(factor)) I know that the "factor" is getting assigned 0 because its not being rounded properly or something. I dont know how to handle these decimals properly. Float isnt doing anything apparently. Any help is appreciated, thankyou.
[ "When you call float on the division result, it's after the fact the division was treated as an integer division (note: this is Python 2, I assume). It doesn't help, what does help is initially specify the division as a floating-point division, for example by saying 60.0 (the float version of 60):\nfactor = 60.0 / ...
[ 11, 4 ]
[]
[]
[ "decimal", "division", "floating_point", "python" ]
stackoverflow_0003784467_decimal_division_floating_point_python.txt
Q: Online file comparison tool I want to a visualize web file compare tool,that can embed into my app,I know there some software like beyond compare,it has done great job,but it on windows & need buy licence,if someone has develop a web version,then it can cross platform, does some already achieve this? if it is python - friendly is great appreciated A: There is Trac: Trac is an enhanced wiki and issue tracking system for software development projects. ... It provides an interface to Subversion (or other version control systems)... It is written in python, and can compare source files. This looks like: http://trac.edgewall.org/changeset?old_path=%2Ftrunk%2Ftrac%2Fdb%2Fschema.py&old=7890&new_path=%2Ftrunk%2Ftrac%2Fdb%2Fschema.py&new=9406 A: Take a look at rietveld http://code.google.com/p/rietveld/ Here is an example http://codereview.appspot.com/2208048/diff/4001/Documentation/notation/fretted-strings.itely
Online file comparison tool
I want to a visualize web file compare tool,that can embed into my app,I know there some software like beyond compare,it has done great job,but it on windows & need buy licence,if someone has develop a web version,then it can cross platform, does some already achieve this? if it is python - friendly is great appreciated
[ "There is Trac: Trac is an enhanced wiki and issue tracking system for software development projects. ... It provides an interface to Subversion (or other version control systems)...\nIt is written in python, and can compare source files. This looks like:\nhttp://trac.edgewall.org/changeset?old_path=%2Ftrunk%2Ftra...
[ 1, 1 ]
[]
[]
[ "compare", "diff", "python" ]
stackoverflow_0003784622_compare_diff_python.txt
Q: Can't do an AJAX call with Python and Django I am still learning to do javascript and django and yesterday I tried to do a simple hello world ajax exercise. Server logs show that python code is being called but somehow django/python does not return anything when I check the xmlhttp.responseText and responseXML in firebug. UPDATE: I removed the checking of the http status returned so that code immediately goes to print the output from the server <html> <head> <title>Javascript example 1</title> <script type="text/javascript"> function doAjax() { xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { alert("response text: "+xmlhttp.responseText+"\n" +"response XML: "+ xmlhttp.responseXML); if (xmlhttp.responseText!="") { $("thediv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","http://127.0.0.1/test/",true); xmlhttp.send(); } function $(element){ return document.getElementById(element); } </script> </head> <body> <input type="button" value="click me" onClick=javascript:doAjax()> <br/><br/> <div id="thediv"> some test </div> </body> </html> my views.py from django.http import HttpResponse def test(request): response_string="hello" return HttpResponse(response_string,mimetype='text/plain') my urls.py from django.conf.urls.defaults import * from project1.views import test # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', (r'^test/$', test) # Example: # (r'^project1/', include('project1.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/', include(admin.site.urls)), ) UPDATE Here is the code in action A: I just tested your code. When I clicked the "click me" button, a request was indeed made to the test view. I was able to confirm this. However, unlike what you said the view is returning the HttpResponse. To verify this yourself, access the http://localhost:8000/test/ url using your web browser. See what happens. At first blush your problem seems to be JavaScript related. I don't know what exactly is going wrong but I'll try to debug the JS code and see. Update I was able to confirm that the error is indeed with the JavaScript that you are using. I found two errors. First: if (xmlhttp.readyState==4 && xmlhttp.status==0) Shouldn't the status be 200? So I changed it to: if (xmlhttp.readyState==4 && xmlhttp.status==200) Update 2 Found that I missed the $ function. The problem is that there are two if conditions. When first evaluates to true, the contents of the div are indeed updated to "hello". However the second if (xmlhttp.responseXML!="") also evaluates to true (null is != "", hence) and wipes out the contents of the div. A: Its good to use core JavaScript when learning but you should definitely use some framework such as jQuery or Prototype as you progress. Frameworks allow to keep your code concise, develop faster and also insulate you from the cross-browser compatibility issues. Using jQuery your code would have been something like this: <html> <head> <title>Javascript example 1</title> <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script> <script type="text/javascript"> function doAjax() { $.ajax({ url: 'http://localhost:8000/test/', success: function(data) { $('#thediv').html(data); //jQuery equivalent of document.getElementById('thediv').innerHTML = data } }); } </script> </head> <body> <input type="button" value="click me" onClick="javascript:doAjax()"/> <br/><br/> <div id="thediv"> some test </div> </body> </html> Since jQuery provides with a default $() function, you do not need to define them in your code in case you use the framework. Though this answer is slightly off-track, I hope it will be useful to you.
Can't do an AJAX call with Python and Django
I am still learning to do javascript and django and yesterday I tried to do a simple hello world ajax exercise. Server logs show that python code is being called but somehow django/python does not return anything when I check the xmlhttp.responseText and responseXML in firebug. UPDATE: I removed the checking of the http status returned so that code immediately goes to print the output from the server <html> <head> <title>Javascript example 1</title> <script type="text/javascript"> function doAjax() { xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { alert("response text: "+xmlhttp.responseText+"\n" +"response XML: "+ xmlhttp.responseXML); if (xmlhttp.responseText!="") { $("thediv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","http://127.0.0.1/test/",true); xmlhttp.send(); } function $(element){ return document.getElementById(element); } </script> </head> <body> <input type="button" value="click me" onClick=javascript:doAjax()> <br/><br/> <div id="thediv"> some test </div> </body> </html> my views.py from django.http import HttpResponse def test(request): response_string="hello" return HttpResponse(response_string,mimetype='text/plain') my urls.py from django.conf.urls.defaults import * from project1.views import test # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', (r'^test/$', test) # Example: # (r'^project1/', include('project1.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/', include(admin.site.urls)), ) UPDATE Here is the code in action
[ "I just tested your code. When I clicked the \"click me\" button, a request was indeed made to the test view. I was able to confirm this. However, unlike what you said the view is returning the HttpResponse. To verify this yourself, access the http://localhost:8000/test/ url using your web browser. See what happens...
[ 2, 1 ]
[]
[]
[ "django", "javascript", "python" ]
stackoverflow_0003783839_django_javascript_python.txt
Q: python backports for some methods Is there any backport for the following methods to work with python 2.4: any, all, collections.defaultdict, collections.deque A: Well, at least for any and all it's easy: def any(iterable): for element in iterable: if element: return True return False def all(iterable): for element in iterable: if not element: return False return True deque is already in 2.4. As for defaultdict, I guess you can emulate that easily with setdefault(). Quoting from Alex Martelli`s (and others') highly recommended Python Cookbook: This is what the setdefault method of dictionaries is for. Say we’re building a word-to-page-numbers index, a dictionary that maps each word to the list of page numbers where it appears. A key piece of code in that application might be: def addword(theIndex, word, pagenumber): theIndex.setdefault(word, [ ]).append(pagenumber) This code is equivalent to more verbose approaches such as: def addword(theIndex, word, pagenumber): if word in theIndex: theIndex[word].append(pagenumber) else: theIndex[word] = [pagenumber] and: def addword(theIndex, word, pagenumber): try: theIndex[word].append(pagenumber) except KeyError: theIndex[word] = [pagenumber] A: As Tim points out, all and any are trivial. defaultdict isn't much more difficult. Here's a passable implementation I believe. It's essentially a translation of the docs into code. update: removed ternary expression because I remembered that that's not in 2.4 class defaultdict(dict): def __init__(self, default_factory, *args, **kwargs): super(defaultdict, self).__init__(*args, **kwargs) self.default_factory = default_factory def __missing__(self, key): try: self[key] = self.default_factory() except TypeError: raise KeyError("Missing key %s" % (key, )) else: return self[key] def __getitem__(self, key): try: return super(defaultdict, self).__getitem__(key) except KeyError: return self.__missing__(key) If you are just using it to build a dict, then you might want to change the EAFP to LBYL for __getitem__. right now it's optimized to build the dict and then use it for a while with a lot of non-miss lookups. deque is going to be tougher. I wish I had the time to do that just because It's probably my favorite out of collections but it's non trivial. never mind. Just read Tims post all the way through. You got your wish.
python backports for some methods
Is there any backport for the following methods to work with python 2.4: any, all, collections.defaultdict, collections.deque
[ "Well, at least for any and all it's easy:\ndef any(iterable):\n for element in iterable:\n if element:\n return True\n return False\n\ndef all(iterable):\n for element in iterable:\n if not element:\n return False\n return True\n\ndeque is already in 2.4.\nAs for def...
[ 5, 5 ]
[]
[]
[ "backport", "methods", "python" ]
stackoverflow_0003785433_backport_methods_python.txt
Q: How do I find out in which file or module is my function called? Python 2.5 to 2.7: #a.py: def foo(): pass #b.py from a import foo foo() From foo(), I'd like to know that it has benn called in the "b" module. The only way I can think of right now is raising an exception, catching it and inspecting the traceback (going one level up). Is there a mare natural way of doing this? A: You can do this with the inspect module. E.g. #!/usr/bin/env python # a.py import inspect def foo(): for item in inspect.stack(): print item - #!/usr/bin/env python # b.py from a import foo foo() - $ python b.py (<frame object at 0x2026fb0>, '/home/tdb/a.py', 6, 'foo', [' for item in inspect.stack():\n'], 0) (<frame object at 0x1fe4a30>, 'b.py', 5, '<module>', ['foo()\n'], 0) A: Nevermind, it turns out the solution is: import traceback traceback.extract_stack(limit=2))[0]
How do I find out in which file or module is my function called?
Python 2.5 to 2.7: #a.py: def foo(): pass #b.py from a import foo foo() From foo(), I'd like to know that it has benn called in the "b" module. The only way I can think of right now is raising an exception, catching it and inspecting the traceback (going one level up). Is there a mare natural way of doing this?
[ "You can do this with the inspect module.\nE.g.\n#!/usr/bin/env python\n# a.py\nimport inspect\n\ndef foo():\n for item in inspect.stack():\n print item\n\n-\n#!/usr/bin/env python\n# b.py\n\nfrom a import foo\n\nfoo()\n\n-\n$ python b.py\n(<frame object at 0x2026fb0>, '/home/tdb/a.py', 6, 'foo', [' fo...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003785479_python.txt
Q: Detecting Similar images Possible Duplicate: Image comparison algorithm So basically i need to write a program that checks whether 2 images are the same or not. Consider the following 2 images: http://i221.photobucket.com/albums/dd298/ramdeen32/starry_night.jpg http://i221.photobucket.com/albums/dd298/ramdeen32/starry_night2.jpg Well they are both the same images but how do i check to see if these images are the same. I am only limited to the media functions. All i can think of right now is the width height scaling and compare the RGB for each pixel but wouldnt the color be different? Im completely lost on this one, any help is appreciated. *Note this has to be in python and use the (media library) A: Wow - that is a massive question, and one that has a vast number of possible solutions. I'm afraid I'm not a python expert, but I thought your question was interesting - so I wanted to propose a method that I would implement if I were posed with this problem. Obviously, the two images you posted are actually very different - so you will need to consider 'how much different is the same', especially when working with images and considering different image formats and compression etc. Anyway, for a solution that allows for a given difference in colour values (but not for pixels to be in the wrong places), I would do something like the following; Pick two images. Rescale the largest image to the exact same height and width as the first (even distorting the image if necessary). Possibly grayscale the images to make the next steps simpler, without losing much in the way of effectiveness. Actually, possibly running edge detection here could work too. Go through each pixel in both images and store the difference in either each of the RGB channels, or just the difference in grayscale intensity. You would end up with an array the size of the image noting the difference between the pixel intensities on the two images. Now, I don't know the exact values, but you would probably then find that if you iterate over the array you could see whether the difference between each pixel in the two images is the same (or nearly the same) across all of the pixels. Perhaps iterate over the array once to find the average difference between the pixel intensities in the two images, then iterate over the image again to see if 90% of the differences fall within a certain threshold (5% difference?). Just an idea. Of course, there might be some nice functions that I'm not aware of to make this easy, but I wouldn't hold my breath! A: ImageMagick has Python bindings and a comparison function. It should do most of the work for you, but I've never used it in Python. A: I think step 2 of John Wordsworths answer may be one of the hardest - here you are dealing with a stretched copy of the image but do you also allow rotated, cropped or in other ways distorted images? If so you are going to need a feature matching algorithm, such as used in Hugin or other panorama creation software. This will find matching features, distort to fit and then you can do the other stages of comparing. Ideally you want to recognise Van Gogh's painting from photos, even photos on mugs! It's easy for a human to do this, for a computer it needs rather more complex maths.
Detecting Similar images
Possible Duplicate: Image comparison algorithm So basically i need to write a program that checks whether 2 images are the same or not. Consider the following 2 images: http://i221.photobucket.com/albums/dd298/ramdeen32/starry_night.jpg http://i221.photobucket.com/albums/dd298/ramdeen32/starry_night2.jpg Well they are both the same images but how do i check to see if these images are the same. I am only limited to the media functions. All i can think of right now is the width height scaling and compare the RGB for each pixel but wouldnt the color be different? Im completely lost on this one, any help is appreciated. *Note this has to be in python and use the (media library)
[ "Wow - that is a massive question, and one that has a vast number of possible solutions. I'm afraid I'm not a python expert, but I thought your question was interesting - so I wanted to propose a method that I would implement if I were posed with this problem.\nObviously, the two images you posted are actually very...
[ 5, 1, 0 ]
[]
[]
[ "comparison", "image", "media", "python" ]
stackoverflow_0003783398_comparison_image_media_python.txt
Q: How to properly use and cancel subprocess in python using Django? I have a view that gets data from a form and executes a subprocess: def sync_job(request, job_id, src, dest): form = SyncJobForm() check = SyncJob.objects.get(id=job_id) check.status = True check.save() pre_sync = SyncJobCMD.objects.get(id=1) p = Popen([str(pre_sync), '-avu', str(src), str(dest)], stdout=PIPE) syncoutput,syncerror = p.communicate() check.log = syncoutput check.status = False check.save() return render_to_response('sync_form.html', {'syncoutput': syncoutput, 'form': form}, context_instance=RequestContext(request)) I would like to have an option to cancel the running process, but I have not found how to do that with subprocess. Also, what happens when a user runs a subprocess job and navigates to another page, does the process finish in the background? Is it advisable to use Shell=True in this scenario? Thanks. A: Starting from Python 2.6 you can use Popen.terminate() to kill your processes: p.terminate() In earlier versions of Python you can use os.kill(). os.kill(p.pid, signal.SIGTERM) Also, Popen.communicate() will block until your child process has terminated. This means that the response will not get sent to the user before your sync job has terminated. A: Also you could use signals (e.g. the kill signal; for more details see documentation for the signal module): import signal p.send_signal(signal.SIGKILL)
How to properly use and cancel subprocess in python using Django?
I have a view that gets data from a form and executes a subprocess: def sync_job(request, job_id, src, dest): form = SyncJobForm() check = SyncJob.objects.get(id=job_id) check.status = True check.save() pre_sync = SyncJobCMD.objects.get(id=1) p = Popen([str(pre_sync), '-avu', str(src), str(dest)], stdout=PIPE) syncoutput,syncerror = p.communicate() check.log = syncoutput check.status = False check.save() return render_to_response('sync_form.html', {'syncoutput': syncoutput, 'form': form}, context_instance=RequestContext(request)) I would like to have an option to cancel the running process, but I have not found how to do that with subprocess. Also, what happens when a user runs a subprocess job and navigates to another page, does the process finish in the background? Is it advisable to use Shell=True in this scenario? Thanks.
[ "Starting from Python 2.6 you can use Popen.terminate() to kill your processes:\np.terminate()\n\nIn earlier versions of Python you can use os.kill().\nos.kill(p.pid, signal.SIGTERM)\n\nAlso, Popen.communicate() will block until your child process has terminated. This means that the response will not get sent to th...
[ 0, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0003784052_django_django_views_python.txt
Q: Linux / Bash using PS -f for specific PID returns in different format than PS -f, also queston about using Grep to parse this I have a need, for a python script I'm creating, to first get just the PID of a process (based on its name) and then to get from that process, usings its PID, its time duration, which, from the printout below, would be "00:00:00" root 5686 1 0 Sep23 ? 00:00:00 process-name I am using this to get just the PID, by the process's name: ps -ef |grep `whoami`| grep process-name | cut -c10-15 So, this works fine and I am assuming that the cut parameters (-c10-15) would work universally as the placement of the PID shouldn't change (I just got this from a snippet I found) However, when I try to do something similar to get just the TIME value, such as this it returns it differently ps -f 5686 returns: root 5686 1 0 Sep23 ? S 0:00 /path/to/process So when I try a cut, as below, I don't think it would work properly as I'm not sure the spacing on this return is consistent and also its showing the time value differently than before (not the original "00:00:00" style of printout. ps -f 5686 | cut -c40-47 I'm using this in my python script to record the PID of a specific process type (by name) so that I can later shut down that instance of the progra when needed. Any advice on what I can do to correct my approach is appreciated A: Use the -o option to control what data is output and in what order. e.g. $ ps -o pid,time,comm PID TIME COMMAND 3029 00:00:01 zsh 22046 00:00:00 ps or $ ps -o pid,time,comm --no-headers 3029 00:00:01 zsh 22046 00:00:00 ps This will make it easier to parse. I would suggest parsing the output with python using (pid, time, cmd) = result.split(2) Alternatively use the pgrep command to only list processes that match given criteria. A: What about using ps ux | awk '/$PROCESS_NAME/ && !/awk/ {print $2, $10}' It should give you PID and TIME (adapted from here) EDIT: Version with -ef ps -ef | awk '/$PROCESS_NAME/ && !/awk/ {print $2, $7}' A: If you want consistent representation of the CPU time, read /proc/<pid>/stat and read the utime and stime fields. Read man 5 proc to get the full layout of that file, but the easy bit is that you need the 14th and 15th values, and they're represented in "jiffies" (typically 100 per second), e.g. % ps -e 2398 2398 ? 00:04:29 ypbind 00:04:29 is 269 seconds % awk '{ print ($14 + $15) / 100 }' < /proc/2398/stat 269.26 or, in a Bash script without spawning a sub-process: #!/bin/sh read -a procstat /proc/pid/stat let cpu=(procstat[13] + procstat[14]) / 100
Linux / Bash using PS -f for specific PID returns in different format than PS -f, also queston about using Grep to parse this
I have a need, for a python script I'm creating, to first get just the PID of a process (based on its name) and then to get from that process, usings its PID, its time duration, which, from the printout below, would be "00:00:00" root 5686 1 0 Sep23 ? 00:00:00 process-name I am using this to get just the PID, by the process's name: ps -ef |grep `whoami`| grep process-name | cut -c10-15 So, this works fine and I am assuming that the cut parameters (-c10-15) would work universally as the placement of the PID shouldn't change (I just got this from a snippet I found) However, when I try to do something similar to get just the TIME value, such as this it returns it differently ps -f 5686 returns: root 5686 1 0 Sep23 ? S 0:00 /path/to/process So when I try a cut, as below, I don't think it would work properly as I'm not sure the spacing on this return is consistent and also its showing the time value differently than before (not the original "00:00:00" style of printout. ps -f 5686 | cut -c40-47 I'm using this in my python script to record the PID of a specific process type (by name) so that I can later shut down that instance of the progra when needed. Any advice on what I can do to correct my approach is appreciated
[ "Use the -o option to control what data is output and in what order.\ne.g.\n$ ps -o pid,time,comm\n PID TIME COMMAND\n 3029 00:00:01 zsh\n22046 00:00:00 ps\n\nor\n$ ps -o pid,time,comm --no-headers\n 3029 00:00:01 zsh\n22046 00:00:00 ps\n\nThis will make it easier to parse. I would suggest parsing the output ...
[ 3, 0, 0 ]
[]
[]
[ "bash", "command_line", "linux", "pid", "python" ]
stackoverflow_0003785768_bash_command_line_linux_pid_python.txt
Q: Send file using POST from a Python script This is an almost-duplicate of Send file using POST from a Python script, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean. A: Best thing I can think of is to encode it yourself. How about this subroutine? from urllib2 import Request, urlopen from binascii import b2a_base64 def b64open(url, postdata): req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'}) return urlopen(req) conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Égalité Fraternité") # returns a file-like object (Okay, so this code just sends POST-data. But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right? Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.) A: PyCURL provides an interface to CURL from Python. http://curl.haxx.se/libcurl/python/ Curl will do all you need. It can transfer binary files properly, and supports many encodings. However, you have to make sure that the proper character encoding as a custom header when POSTing files. Specifically, you may need to do a 'file upload' style POST: http://curl.haxx.se/docs/httpscripting.html (Section 4.3) With curl (or any other HTTP client) you may have to set the content encoding: Content-Type: text/html; charset=UTF-8 Also, be aware that the request headers must be ascii, and this includes the url (so make sure you properly escape your possibly unicode URLs. There are unicode escapes for the HTTP headers) This was recently fixed in Python: http://bugs.python.org/issue3300 I hope this helps, there is more info on the topic, including setting your default character set on your server, etc. A: Just use this library and send in files. http://github.com/seisen/urllib2_file/
Send file using POST from a Python script
This is an almost-duplicate of Send file using POST from a Python script, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.
[ "Best thing I can think of is to encode it yourself. How about this subroutine?\nfrom urllib2 import Request, urlopen\nfrom binascii import b2a_base64\n\ndef b64open(url, postdata):\n req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})\n return urlopen(req)\n\nconn = b64open...
[ 5, 1, 1 ]
[]
[]
[ "encoding", "post", "python" ]
stackoverflow_0000150517_encoding_post_python.txt
Q: SQLite error when loading two python scripts simultaneously I have two python scripts that have to run simultaneously because they interact with each other. One script is a 'server' script running locally and the other is client script that connects to it via a socket. Normally I just open a couple terminal tabs and run the server script in one and the client in the other. After starting and stopping each script over and over, I wanted to make a bash alias to run both scripts with just one command and came up with this: gnome-terminal --tab -e "python server.py" --tab -e "python client.py" However, now the server script is raising an sqlite OperationalError saying that one of my data tables doesn't exist. But when I run the scripts manually everything works fine. I have no clue what is going on, but I thought that maybe running the scripts together wasn't giving the server script enough time to initialize and make its connection to the database. So I put a time.sleep(5) in the client script, but as soon as it starts I get the same error. Anyone have an idea what could be happening? Or does anyone know of any alternatives for starting two python scripts with one command? A: Try combining the two commands into one: gnome-terminal --tab -x bash -c "python server.py & sleep 5; python client.py" I think it is better to put the sleep command (if needed) outside client since there may be situations where the server is already started and the client does not have to sleep. The -x flag means -x, --execute Execute the remainder of the command line inside the terminal. The command calls bash: bash -c "python server.py & sleep 5; python client.py" bash in turn, has a -c flag which means -c string If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the posi‐ tional parameters, starting with $0. You might want to experiment with gnome-terminal --tab -e "python server.py & sleep 5; python client.py" That might work too. When you run bash first, then your ~/.bashrc is read. Without calling bash, I think by default, /bin/sh is called instead. If you get "socket.error: [Errno 98] Address already in use", it probably means that your server has already been started, and running the server a second time fails.
SQLite error when loading two python scripts simultaneously
I have two python scripts that have to run simultaneously because they interact with each other. One script is a 'server' script running locally and the other is client script that connects to it via a socket. Normally I just open a couple terminal tabs and run the server script in one and the client in the other. After starting and stopping each script over and over, I wanted to make a bash alias to run both scripts with just one command and came up with this: gnome-terminal --tab -e "python server.py" --tab -e "python client.py" However, now the server script is raising an sqlite OperationalError saying that one of my data tables doesn't exist. But when I run the scripts manually everything works fine. I have no clue what is going on, but I thought that maybe running the scripts together wasn't giving the server script enough time to initialize and make its connection to the database. So I put a time.sleep(5) in the client script, but as soon as it starts I get the same error. Anyone have an idea what could be happening? Or does anyone know of any alternatives for starting two python scripts with one command?
[ "Try combining the two commands into one:\ngnome-terminal --tab -x bash -c \"python server.py & sleep 5; python client.py\"\n\nI think it is better to put the sleep command (if needed) outside client since there may be situations where the server is already started and the client does not have to sleep.\n\nThe -x f...
[ 0 ]
[]
[]
[ "gnome_terminal", "python", "sqlite" ]
stackoverflow_0003786194_gnome_terminal_python_sqlite.txt
Q: Good python XML parser to work with namespace heavy documents Python elementTree seems unusable with namespaces. What are my alternatives? BeautifulSoup is pretty rubbish with namespaces too. I don't want to strip them out. Examples of how a particular python library gets namespaced elements and their collections are all +1. Edit: Could you provide code to deal with this real world use-case using your library of choice? How would you go about getting strings 'Line Break', '2.6' and a list ['PYTHON', 'XML', 'XML-NAMESPACES'] <?xml version="1.0" encoding="UTF-8"?> <zs:searchRetrieveResponse xmlns="http://unilexicon.com/vocabularies/" xmlns:zs="http://www.loc.gov/zing/srw/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:lom="http://ltsc.ieee.org/xsd/LOM"> <zs:records> <zs:record> <zs:recordData> <srw_dc:dc xmlns:srw_dc="info:srw/schema/1/dc-schema"> <name>Line Break</name> <dc:title>Processing XML namespaces using Python</dc:title> <dc:description>How to get contents string from an element, how to get a collection in a list...</dc:description> <lom:metaMetadata> <lom:identifier> <lom:catalog>Python</lom:catalog> <lom:entry>2.6</lom:entry> </lom:identifier> </lom:metaMetadata> <lom:classification> <lom:taxonPath> <lom:taxon> <lom:id>PYTHON</lom:id> </lom:taxon> </lom:taxonPath> </lom:classification> <lom:classification> <lom:taxonPath> <lom:taxon> <lom:id>XML</lom:id> </lom:taxon> </lom:taxonPath> </lom:classification> <lom:classification> <lom:taxonPath> <lom:taxon> <lom:id>XML-NAMESPACES</lom:id> </lom:taxon> </lom:taxonPath> </lom:classification> </srw_dc:dc> </zs:recordData> </zs:record> <!-- ... more records ... --> </zs:records> </zs:searchRetrieveResponse> A: lxml is namespace-aware. >>> from lxml import etree >>> et = etree.XML("""<root xmlns="foo" xmlns:stuff="bar"><bar><stuff:baz /></bar></root>""") >>> etree.tostring(et, encoding=str) # encoding=str only needed in Python 3, to avoid getting bytes '<root xmlns="foo" xmlns:stuff="bar"><bar><stuff:baz/></bar></root>' >>> et.xpath("f:bar", namespaces={"b":"bar", "f": "foo"}) [<Element {foo}bar at ...>] Edit: On your example: from lxml import etree # remove the b prefix in Python 2 # needed in python 3 because # "Unicode strings with encoding declaration are not supported." et = etree.XML(b"""...""") ns = { 'lom': 'http://ltsc.ieee.org/xsd/LOM', 'zs': 'http://www.loc.gov/zing/srw/', 'dc': 'http://purl.org/dc/elements/1.1/', 'voc': 'http://www.schooletc.co.uk/vocabularies/', 'srw_dc': 'info:srw/schema/1/dc-schema' } # according to docs, .xpath returns always lists when querying for elements # .find returns one element, but only supports a subset of XPath record = et.xpath("zs:records/zs:record", namespaces=ns)[0] # in this example, we know there's only one record # but else, you should apply the following to all elements the above returns name = record.xpath("//voc:name", namespaces=ns)[0].text print("name:", name) lom_entry = record.xpath("zs:recordData/srw_dc:dc/" "lom:metaMetadata/lom:identifier/" "lom:entry", namespaces=ns)[0].text print('lom_entry:', lom_entry) lom_ids = [id.text for id in record.xpath("zs:recordData/srw_dc:dc/" "lom:classification/lom:taxonPath/" "lom:taxon/lom:id", namespaces=ns)] print("lom_ids:", lom_ids) Output: name: Frank Malina lom_entry: 2.6 lom_ids: ['PYTHON', 'XML', 'XML-NAMESPACES'] A: How about: http://docs.python.org/library/pyexpat.html A: libxml (http://xmlsoft.org/) Best, faster lib for xml parsing. There are implementation for python.
Good python XML parser to work with namespace heavy documents
Python elementTree seems unusable with namespaces. What are my alternatives? BeautifulSoup is pretty rubbish with namespaces too. I don't want to strip them out. Examples of how a particular python library gets namespaced elements and their collections are all +1. Edit: Could you provide code to deal with this real world use-case using your library of choice? How would you go about getting strings 'Line Break', '2.6' and a list ['PYTHON', 'XML', 'XML-NAMESPACES'] <?xml version="1.0" encoding="UTF-8"?> <zs:searchRetrieveResponse xmlns="http://unilexicon.com/vocabularies/" xmlns:zs="http://www.loc.gov/zing/srw/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:lom="http://ltsc.ieee.org/xsd/LOM"> <zs:records> <zs:record> <zs:recordData> <srw_dc:dc xmlns:srw_dc="info:srw/schema/1/dc-schema"> <name>Line Break</name> <dc:title>Processing XML namespaces using Python</dc:title> <dc:description>How to get contents string from an element, how to get a collection in a list...</dc:description> <lom:metaMetadata> <lom:identifier> <lom:catalog>Python</lom:catalog> <lom:entry>2.6</lom:entry> </lom:identifier> </lom:metaMetadata> <lom:classification> <lom:taxonPath> <lom:taxon> <lom:id>PYTHON</lom:id> </lom:taxon> </lom:taxonPath> </lom:classification> <lom:classification> <lom:taxonPath> <lom:taxon> <lom:id>XML</lom:id> </lom:taxon> </lom:taxonPath> </lom:classification> <lom:classification> <lom:taxonPath> <lom:taxon> <lom:id>XML-NAMESPACES</lom:id> </lom:taxon> </lom:taxonPath> </lom:classification> </srw_dc:dc> </zs:recordData> </zs:record> <!-- ... more records ... --> </zs:records> </zs:searchRetrieveResponse>
[ "lxml is namespace-aware.\n>>> from lxml import etree\n>>> et = etree.XML(\"\"\"<root xmlns=\"foo\" xmlns:stuff=\"bar\"><bar><stuff:baz /></bar></root>\"\"\")\n>>> etree.tostring(et, encoding=str) # encoding=str only needed in Python 3, to avoid getting bytes\n'<root xmlns=\"foo\" xmlns:stuff=\"bar\"><bar><stuff:ba...
[ 13, 1, 0 ]
[]
[]
[ "namespaces", "python", "xml", "xml_namespaces" ]
stackoverflow_0003785629_namespaces_python_xml_xml_namespaces.txt
Q: Windows Live Web Authentication on Google App Engine (GAE) using Python I'm struggling to get Windows Live Web Authentication running on Google App Engine (GAE) using Python, as I'm quite new to the language. However there are lots of examples for Facebook and Twitter, I was wondering if anyone had come up with a solution for Windows Live yet? A: From what I can tell, the SDK you're referring to is just used for authentication, not authorization. That is, it allows you to uniquely identify a user by their Windows Live ID, but not, say, programmatically import their Hotmail contacts. If this is the case, it would be easier to use the built-in OpenID support that's already available on both sides. The Windows Live OpenID provider is OpenID.Live-INT.com; instructions for authenticating using OpenID on App Engine can be found @ http://code.google.com/appengine/articles/openid.html. A: I ended up using http://anyopenid.com which provides quite a good bridge to openid, and I was able to use this with Google App Engine.
Windows Live Web Authentication on Google App Engine (GAE) using Python
I'm struggling to get Windows Live Web Authentication running on Google App Engine (GAE) using Python, as I'm quite new to the language. However there are lots of examples for Facebook and Twitter, I was wondering if anyone had come up with a solution for Windows Live yet?
[ "From what I can tell, the SDK you're referring to is just used for authentication, not authorization. That is, it allows you to uniquely identify a user by their Windows Live ID, but not, say, programmatically import their Hotmail contacts.\nIf this is the case, it would be easier to use the built-in OpenID suppor...
[ 0, 0 ]
[]
[]
[ "authentication", "google_app_engine", "python", "windows_live" ]
stackoverflow_0003567012_authentication_google_app_engine_python_windows_live.txt
Q: Dynamic base class and factories I have following code: class EntityBase (object) : __entity__ = None def __init__ (self) : pass def entity (name) : class Entity (EntityBase) : __entity__ = name def __init__ (self) : pass return Entity class Smth (entity ("SMTH")) : def __init__ (self, a, b) : self.a = a self.b = b # added after few comments --> def factory (tag) : for entity in EntityBase.__subclasses__ () : if entity.__entity__ == tag : return entity.__subclasses__ ()[0] raise FactoryError (tag, "Unknown entity") s = factory ("SMTH") (1, 2) print (s.a, s.b) # <-- Now in factory I can get all subclasses of EntityBase, find concrete subclass for "SMTH" and create it. Is this valid approach or maybe I something misunderstood and doing wrong? A: I would do this with a decorator. Also, storing the entity -> subclass map in a dictionary lets you replace a linear scan with a dict lookup. class EntityBase(object): _entity_ = None _entities_ = {} @classmethod def factory(cls, entity): try: return cls._entities_[entity] except KeyError: raise FactoryError(tag, "Unknown entity") @classmethod def register(cls, entity): def decorator(subclass): cls._entities_[entity] = subclass subclass._entity_ = entity return subclass return decorator factory = EntityBase.factory register = EntityBase.register @register('Smith') class Smith(EntityBase): def __init__(self, a, b): self.a = a self.b = b s = factory('Smith')(1, 2) I'm not sure if the __entity__ attribute is actually useful to you of if you were just using it to implement the linear scan. I left it in but if you took it out, then the classes associated with entity wouldn't even need to inherit from EntityBase and you could rename it to something like Registry. This shallows up your inheritance tree and opens the possibility of using on classes that aren't related through common descent. Depending on what your use case is, a better way to do it might just be factory = {} class Smith(object): def __init__(self, a, b): self.a = a self.b = b factory['Smith'] = Smith class Jones(object): def __init__(self, c, d): self.c = c self.d = d factory['Jones'] = Jones s = factory['Smith'](1, 2) j = factory['Jones'](3, 4) The decorator is fancier and let's us feel nice and fancy about ourselves but the dictionary is plain, useful and to the point. It is easy to understand and difficult to get wrong. Unless you really need to do something magic, then I think that that's the way to go. Why do you want to do this, anyway? A: I think this is one of the few cases where you want a Python metaclass: class Entity(object): class __metaclass__(type): ENTITIES = {} def __new__(mcs, name, bases, cdict): cls = type.__new__(mcs, name, bases, cdict) try: entity = cdict['_entity_'] mcs.ENTITIES[entity] = cls except KeyError: pass return cls @classmethod def factory(cls, name): return cls.__metaclass__.ENTITIES[name] class Smth(Entity): _entity_ = 'SMTH' def __init__(self, a, b): self.a = a self.b = b s = Entity.factory("SMTH")(1, 2) print (s.a, s.b) A few more subtle differences from your code: There's no need to create a subclass with your entity() factory function then subclass that subclass. That approach not only creates more subclasses than necessary, but also makes your code not work because EntityBase.__subclasses__() doesn't contain the Smth class. Identifiers which both begin and end with __ are reserved for Python, so I'm using the _entity_ attribute instead of __entity__. A: A metaclass can keep track of the defined classes. Register.__init__ is called when a class with this metaclass is defined. We can just add the name and object to a registry dict in the metaclass. This way you can look it up directly later. registry = {} # dict of subclasses def get_entity( name ): return registry[name] class Register(type): def __init__(cls, name, bases, dict): registry[name] = cls type.__init__(cls,name, bases, dict) class EntityBase(object): __metaclass__ = Register class OneThing(EntityBase): pass class OtherThing(OneThing): pass print registry # dict with Entitybase, OneThing, OtherThing print get_entity("OtherThing") # <class '__main__.OtherThing'> Btw, a factory instantiates classes, so the name is not fitting for a function that only returns a class.
Dynamic base class and factories
I have following code: class EntityBase (object) : __entity__ = None def __init__ (self) : pass def entity (name) : class Entity (EntityBase) : __entity__ = name def __init__ (self) : pass return Entity class Smth (entity ("SMTH")) : def __init__ (self, a, b) : self.a = a self.b = b # added after few comments --> def factory (tag) : for entity in EntityBase.__subclasses__ () : if entity.__entity__ == tag : return entity.__subclasses__ ()[0] raise FactoryError (tag, "Unknown entity") s = factory ("SMTH") (1, 2) print (s.a, s.b) # <-- Now in factory I can get all subclasses of EntityBase, find concrete subclass for "SMTH" and create it. Is this valid approach or maybe I something misunderstood and doing wrong?
[ "I would do this with a decorator. Also, storing the entity -> subclass map in a dictionary lets you replace a linear scan with a dict lookup.\nclass EntityBase(object):\n _entity_ = None\n _entities_ = {}\n\n @classmethod\n def factory(cls, entity):\n try:\n return cls._entities_[enti...
[ 9, 5, 3 ]
[ "\nthis valid approach or maybe I something misunderstood and doing wrong?\n\nIt works. So in one sense it's \"valid\".\nIt's a complete waste of code. So in one sense it's not \"valid\".\nThere aren't any use cases for this kind of construct. Now that you've built it, you can move on to solving practical proble...
[ -2 ]
[ "factory", "factory_pattern", "python" ]
stackoverflow_0003786762_factory_factory_pattern_python.txt
Q: Determine Declaring Order of Python/IronPython Functions I'm trying to take a python class (in IronPython), apply it to some data and display it in a grid. The results of the functions become columns on the grid, and I would like the order of the functions to be the order of the columns. Is there a way to determine the order of python functions of a class in the order they were declared in the source code? I'll take answers that use either IronPython or regular python. So for instance, if I have a class: class foo: def c(self): return 3 def a(self): return 2 def b(self): return 1 I would like to (without parsing the source code myself) get back a list of [c, a, b]. Any ideas? As a caveat, IronPython used to keep the references of functions in the order they declared them. In .NET 4, they changed this behavior to match python (which always lists them in alphabetical order). A: In Python 2.X (IronPython is currently on Python 2) the answer is unfortunately no. Python builds a dictionary of the class members before creating the class object. Once the class is created there is no 'record' of the order. In Python 3 metaclasses (which are used to create classes) are improved and you can use a custom object instead of a standard dictionary to collect class members as the class is built. This allows you to know the order. However, for IronPython there is a hack that might work. Python dictionaries are inherently unordered - i.e. iterating over the members of a dictionary returns them in an arbitrary (but stable) order. In IronPython it used to be the case that, as an accident of implementation, iteration would return members in the order they were inserted. (Note that this may no longer be the case.) You could try: members = list(c.__dict__) # or c.__dict__.keys() You may find that this is ordered as you hope for. Unfortunately running the code under different versions of IronPython (or other implementations of Python) is likely to return them in a different order. Another (better but harder) approach is to use the ast module (or the IronPython parser) and walk the AST to find the entries. Not very hard, but more work. A: Why can't you parse the code yourself? It's easy: import inspect import ast class Foo: def c(self): pass def a(self): pass def b(self): pass code = ast.parse(inspect.getsource(Foo)) class FunctionVisitor(ast.NodeVisitor): def visit_FunctionDef(self, node): print(node.name) FunctionVisitor().visit(code) outputs c a b A: Another solution is to use a decorator to add them into a list. def make_registry(): def register(f): register.funcs.append(f) return f register.funcs = [] return register register = make_registery() class Foo(object): @register def one(self): pass @register def two(self): pass @register def three(self): pass def utility_method_that_shouldnt_be_run_in_the_sequence(self): pass print register.funcs
Determine Declaring Order of Python/IronPython Functions
I'm trying to take a python class (in IronPython), apply it to some data and display it in a grid. The results of the functions become columns on the grid, and I would like the order of the functions to be the order of the columns. Is there a way to determine the order of python functions of a class in the order they were declared in the source code? I'll take answers that use either IronPython or regular python. So for instance, if I have a class: class foo: def c(self): return 3 def a(self): return 2 def b(self): return 1 I would like to (without parsing the source code myself) get back a list of [c, a, b]. Any ideas? As a caveat, IronPython used to keep the references of functions in the order they declared them. In .NET 4, they changed this behavior to match python (which always lists them in alphabetical order).
[ "In Python 2.X (IronPython is currently on Python 2) the answer is unfortunately no. Python builds a dictionary of the class members before creating the class object. Once the class is created there is no 'record' of the order.\nIn Python 3 metaclasses (which are used to create classes) are improved and you can use...
[ 2, 2, 1 ]
[]
[]
[ ".net_4.0", "c#", "ironpython", "python" ]
stackoverflow_0003786984_.net_4.0_c#_ironpython_python.txt
Q: Django to do its own NTLM Authentication (HTTP Headers & all) I'm considering moving from Apache to Lighttpd for an internal web application, written with python. The problem is that I'm relying on libapache2-mod-auth-ntlm-winbind ... which doesn't actually seem to be a well support & updated package (though that could be because it really does work well). I'm looking for suggestions and hints about what it would take to use django itself to handle the HTTP authentication. This would allow me to be web-server-agnostic, and could potentially be a grand learning experience. Some topical concerns: Is it reasonable to have the custom application perform true HTTP authentication? How involved is getting my python code connected to windows domain controller to this kind of authentication without prompting the user for a password? Does NTLM provide any access to user details & group memberships so that I can stop searching through yet another connection to the windows domain controller via LDAP? I would love to be able to write a module to simplify this technique which could be shared with the community. A: Partial answer: You can (and should) pass the NTLM auth off to an external helper. Basically, install Samba on the machine, configure it, join the domain, enable winbind, then use the "ntlm_auth" helper binary, probably in "pipe" mode. Authenticating an NTLM session requires a secure pipe to the domain controller, which needs credentials (e.g. a Samba/domain-member machine account). This is the quickest route to get there. Squid (the webcache) has code for doing NTLM auth using the external helper; FreeRadius does something similar. The NTLM auth itself does not provide any group info; if you're running winbind you could of course use calls to "wbinfo" to get user groups.
Django to do its own NTLM Authentication (HTTP Headers & all)
I'm considering moving from Apache to Lighttpd for an internal web application, written with python. The problem is that I'm relying on libapache2-mod-auth-ntlm-winbind ... which doesn't actually seem to be a well support & updated package (though that could be because it really does work well). I'm looking for suggestions and hints about what it would take to use django itself to handle the HTTP authentication. This would allow me to be web-server-agnostic, and could potentially be a grand learning experience. Some topical concerns: Is it reasonable to have the custom application perform true HTTP authentication? How involved is getting my python code connected to windows domain controller to this kind of authentication without prompting the user for a password? Does NTLM provide any access to user details & group memberships so that I can stop searching through yet another connection to the windows domain controller via LDAP? I would love to be able to write a module to simplify this technique which could be shared with the community.
[ "Partial answer:\nYou can (and should) pass the NTLM auth off to an external helper. Basically, install Samba on the machine, configure it, join the domain, enable winbind, then use the \"ntlm_auth\" helper binary, probably in \"pipe\" mode.\nAuthenticating an NTLM session requires a secure pipe to the domain contr...
[ 1 ]
[]
[]
[ "active_directory", "django", "ldap", "ntlm", "python" ]
stackoverflow_0003120956_active_directory_django_ldap_ntlm_python.txt
Q: Python GUI for portable app I am developing a python app, using python and sqlite and GUI to re-create a Access 2007 report generating app. Since the app is portable, I'm looking for GUI solution for python that user doesn't need to install addition things before using the app. Is there any GUI solution suits my need? Thanks! A: The only fully portable GUI for Python is the standard TkInter, if you don't want any additional install beside Python. The Themed Tk version is quite nice looking, compared to the older Tk version (the themed version is available through the ttk module). A few weeks ago, I had to answer the same question as you. I came to the conclusion that PyQt is currently the best choice for a modern, powerful, well-maintained, and portable GUI, mainly because of some of the shortcomings of its main contender (wxPython, see below). (Tk, and Themed Tk would be good for simpler needs.) Two words of warning against wxPython: it is not possible to install it via the popular Fink package manager on Mac OS X, currently, which makes it far less portable than PyQt and TkInter; it is also not yet Python 3-compatible, as far as I know. PS (Dec. 2012): PySide is currently a strong alternative to PyQt. There are a few Stackoverflow questions about the respective merits of these two Python bindings. A: wxPython is very portable
Python GUI for portable app
I am developing a python app, using python and sqlite and GUI to re-create a Access 2007 report generating app. Since the app is portable, I'm looking for GUI solution for python that user doesn't need to install addition things before using the app. Is there any GUI solution suits my need? Thanks!
[ "The only fully portable GUI for Python is the standard TkInter, if you don't want any additional install beside Python. The Themed Tk version is quite nice looking, compared to the older Tk version (the themed version is available through the ttk module).\nA few weeks ago, I had to answer the same question as you...
[ 8, 5 ]
[]
[]
[ "portable_applications", "python", "user_interface" ]
stackoverflow_0003787065_portable_applications_python_user_interface.txt
Q: Python comparison functions I have some data that lends itself to representation as a value and a comparison function, (val, f), so another value can be checked against it by seeing if f(val, another) is True. That's easy. Some of them just need >, <, or == as f, however, and I can't find a clean way of using them; I end up writing things like ScorePoint(60, lambda a, b: a <= b). That's ugly. Is there a way I can do something more like ScorePoint(60, <=)? A: The operator module is your friend: import operator ScorePoint(60, operator.le) See http://docs.python.org/library/operator.html
Python comparison functions
I have some data that lends itself to representation as a value and a comparison function, (val, f), so another value can be checked against it by seeing if f(val, another) is True. That's easy. Some of them just need >, <, or == as f, however, and I can't find a clean way of using them; I end up writing things like ScorePoint(60, lambda a, b: a <= b). That's ugly. Is there a way I can do something more like ScorePoint(60, <=)?
[ "The operator module is your friend:\nimport operator\nScorePoint(60, operator.le)\n\nSee http://docs.python.org/library/operator.html\n" ]
[ 11 ]
[ "Yes:\n LessEqual = lambda a, b: a <= b\n ScorePoint(60, LessEqual)\n\nor more concise (but less readable):\n LE = lambda a, b: a <= b\n ScorePoint(60, LE)\n\n" ]
[ -4 ]
[ "comparison", "functional_programming", "python" ]
stackoverflow_0003787633_comparison_functional_programming_python.txt
Q: Prepopulating a Django FileField I wanted to know how is it possible in django to bind an already uploaded file (stored in the file system of server) to a Model FileField. This way I want to have my edit page of that model to prepopulate the FileField with this file. Thanks A: Well I found the answer. It was quite easy actually. you just need to set the FileField value to some string and it will point to that file. The point is that the path specified should be correct otherwise you get a 404 error when trying to access it.
Prepopulating a Django FileField
I wanted to know how is it possible in django to bind an already uploaded file (stored in the file system of server) to a Model FileField. This way I want to have my edit page of that model to prepopulate the FileField with this file. Thanks
[ "Well I found the answer. It was quite easy actually. you just need to set the FileField value to some string and it will point to that file.\nThe point is that the path specified should be correct otherwise you get a 404 error when trying to access it.\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003785502_django_python.txt
Q: simple python lxml CRUD? I have been looking for a while a python module/API that does something I believe is quite simple: Read an XML file Add/Edit/Remove entries So far I've found several snippets that interface with complicated object oriented databases, but nothing dead simple as: xml = etree.parse ('file.xml') xml.add(xpath, new_node(attrs)) xml.remove(xpath) xml.edit(xpath, new_attrs(attrs)) xml.write() Most surely I'm misunderstanding the API, but some light will be very welcome. Thanks in advance ! A: Did you checkout the lxml.etree tutorial? It has enough examples to show you how to do most of what you want. A: There are solutions from the standard library too. I think clear() from xml.etree.ElementTree should work as desired. On the other hand, if you have no problem with external dependencies, I think, not sure though, that lxml provides a faster solution.
simple python lxml CRUD?
I have been looking for a while a python module/API that does something I believe is quite simple: Read an XML file Add/Edit/Remove entries So far I've found several snippets that interface with complicated object oriented databases, but nothing dead simple as: xml = etree.parse ('file.xml') xml.add(xpath, new_node(attrs)) xml.remove(xpath) xml.edit(xpath, new_attrs(attrs)) xml.write() Most surely I'm misunderstanding the API, but some light will be very welcome. Thanks in advance !
[ "Did you checkout the lxml.etree tutorial? It has enough examples to show you how to do most of what you want. \n", "There are solutions from the standard library too. I think clear() from xml.etree.ElementTree should work as desired. On the other hand, if you have no problem with external dependencies, I think, ...
[ 2, 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0003785921_lxml_python.txt
Q: Problem with Python relative imports I am using Python 2.6 and have the Facebook API installed as a python package (under /usr/lib64/python2.6/site-packages/facebook/...) which means, it is available with a plain import facebook or from facebook import .... This works well, as long as there is no name clash. For example, in my project, I try to import the Facebook API in my code at project.facebook with from .facebook import GraphAPI From my understanding, this should work because the dot explicitly tells Python to look for the package one step up in the package hierachy and not try to import the project.facebook package it is already parsing. However, it does not work: Could not import project.views. Error was: cannot import name GraphAPI project.views is another source code file that includes project.facebook (I am using Django but I'm not sure whether it has got something to do with that). I know, I could just rename my source file or use from __future__ import absolute_import (that works just fine) but I consider both to be workarounds. Is there any reason why the from .facebook import ... does not work? Update: Here is the output of ls -R in my workspace directory (which contains proj as the only project). The following content is located under /home/chris/dev/workspace/, whereas the Facebook Python API is globally installed (in /usr/lib64/python2.6/site-packages/facebook/...). ./proj/templates: ... ./proj/templates: ...> ./proj: README src static templates ./proj/src: __init__.py __init__.pyc manage.py settings.py settings.pyc settings_local.py settings_local.pyc urls.py urls.pyc proj ./proj/src/proj: __init__.py admin.py auth.py facebook.py forms.py halloffame.py helper.py image.py management middleware.pyc models.pyc openid.pyc stats.pyc twitter.pyc urls.pyc views.pyc __init__.pyc admin.pyc auth.pyc facebook.pyc forms.pyc halloffame.pyc helper.pyc image.pyc middleware.py models.py openid.py stats.py twitter.py urls.py views.py ./proj/src/proj/management: __init__.py __init__.pyc commands ./proj/src/proj/management/commands: __init__.py __init__.pyc cronjob.py cronjob.pyc ./proj/templates: ..../proj/templates: ... ./proj/templates: ... A: Apparently (according to http://docs.python.org/whatsnew/2.5.html#pep-328), there is not way around from __future__ import absolute_import, so I guess I'll just have to be happy with that __future__ import to resolve my name shadowing problem.
Problem with Python relative imports
I am using Python 2.6 and have the Facebook API installed as a python package (under /usr/lib64/python2.6/site-packages/facebook/...) which means, it is available with a plain import facebook or from facebook import .... This works well, as long as there is no name clash. For example, in my project, I try to import the Facebook API in my code at project.facebook with from .facebook import GraphAPI From my understanding, this should work because the dot explicitly tells Python to look for the package one step up in the package hierachy and not try to import the project.facebook package it is already parsing. However, it does not work: Could not import project.views. Error was: cannot import name GraphAPI project.views is another source code file that includes project.facebook (I am using Django but I'm not sure whether it has got something to do with that). I know, I could just rename my source file or use from __future__ import absolute_import (that works just fine) but I consider both to be workarounds. Is there any reason why the from .facebook import ... does not work? Update: Here is the output of ls -R in my workspace directory (which contains proj as the only project). The following content is located under /home/chris/dev/workspace/, whereas the Facebook Python API is globally installed (in /usr/lib64/python2.6/site-packages/facebook/...). ./proj/templates: ... ./proj/templates: ...> ./proj: README src static templates ./proj/src: __init__.py __init__.pyc manage.py settings.py settings.pyc settings_local.py settings_local.pyc urls.py urls.pyc proj ./proj/src/proj: __init__.py admin.py auth.py facebook.py forms.py halloffame.py helper.py image.py management middleware.pyc models.pyc openid.pyc stats.pyc twitter.pyc urls.pyc views.pyc __init__.pyc admin.pyc auth.pyc facebook.pyc forms.pyc halloffame.pyc helper.pyc image.pyc middleware.py models.py openid.py stats.py twitter.py urls.py views.py ./proj/src/proj/management: __init__.py __init__.pyc commands ./proj/src/proj/management/commands: __init__.py __init__.pyc cronjob.py cronjob.pyc ./proj/templates: ..../proj/templates: ... ./proj/templates: ...
[ "Apparently (according to http://docs.python.org/whatsnew/2.5.html#pep-328), there is not way around from __future__ import absolute_import, so I guess I'll just have to be happy with that __future__ import to resolve my name shadowing problem.\n" ]
[ 0 ]
[]
[]
[ "django", "import", "python" ]
stackoverflow_0003783538_django_import_python.txt
Q: Designing a scalable product database on Google App Engine I've built a product database that is divided in 3 parts. And each part has a "sub" part containing labels. But the more I work with it the more unstable it feels. And each addition I make it takes more and more code to get it to work. A product is built of parts, and each part is of a type. Each product, part and type has a label. And there's a label for each language. A product contains parts in 2 list. One list for default parts (one of each type) and one of optional parts. Now I want to add currency in the mix and have come to the decision to re-model the entire way I handle this. The result I want to get is a list of all product objects that contains the name, description, price, all parts and all types that match the parts. And for these the correct language labels. Like so: product - name - description (by language) - price (by currency) - parts - part (type name and part name by language) - partPrice (by currency) The problem with my current setup that is a wild mix of db.ReferenceProperty and db.ListProperty(db.key) And getting all data by is a bit of a hassle that require multiple for-loops, matching dict and datastore calls. Well it's bit of a mess. The re-model(un-tested) look like this class Products(db.model) name = db.StringProperty() imageUrl = db.StringProperty() optionalParts = db.ListProperty(db.Key) defaultParts = db.ListProperty(db.Key) active = db.BooleanProperty(default=True) @property def itemId(self): return self.key().id() class ProductPartTypes(db.Model): name= db.StringProperty() @property def itemId(self): return self.key().id() class ProductParts(db.Model): name = db.StringProperty() type = db.ReferenceProperty(ProductPartTypes) imageUrl = db.StringProperty() parts = db.ListProperty(db.Key) @property def itemId(self): return self.key().id() class Labels(db.Model) key = db.StringProperty() #want to store a key here language = db.StringProperty() label = db.StringProperty() class Price(db.Model) key = db.StringProperty() #want to store a key here language = db.StringProperty() price = db.IntegerProperty() The major thing here is that I've split the Labels and Price out. So these can contain labels and prices for any products, parts or types. So what I am curious about, is this a solid solution from a architectural point of view? Will this hold even if there's thousands of entries in each model? Also, any tips for retrieving data in a good manner are welcome. My current solution of get all data first and for-looping over them and stick them in dicts works but feels like it could fail any minute. ..fredrik A: You need to keep in mind that App Engine's datastore requires you to rethink your usual way of designing databases. It goes against intuition at first but you must denormalize your data as much as possible if you want your application to be scalable. The datastore has been designed this way. The approach I usually take is to consider first what kind of queries will need to be done in different use cases, eg. what data do I need to retrieve at the same time ? In what order ? What properties should be indexed ? If I understand correctly, your main goal is to fetch a list of products with complete details. BTW, if you have other query scenarios - ie. filtering on price, type, etc - you should take them into account too. In order to fetch all the data you need from only one query, I suggest you create one model which could look like this : class ProductPart(db.Model): product_name = db.StringProperty() product_image_url = db.StringProperty() product_active = db.BooleanProperty(default=True) product_description = db.StringListProperty(indexed=False) # Contains product description in all languages part_name = db.StringProperty() part_image_url = db.StringProperty() part_type = db.StringListProperty(indexed=False) # Contains part type in all languages part_label = db.StringListProperty(indexed=False) # Contains part label in all languages part_price = db.ListProperty(float, indexed=False) # Contains part price in all currencies part_default = db.BooleanProperty() part_optional = db.BooleanProperty() About this solution : ListProperties are set to indexed=False in order to avoid exploding indexes if you don't need to filter on them. In order to get the right description, label or type, you will have to set list values always in the same order. For example : part_label[0] is English, part_label[1] is Spanish, etc. Same idea for prices and currencies. After fetching entities from this model you will have to do some in-memory manipulations in order to get the data nicely structured the way you want, maybe in a new dictionary. Obviously, there will be a lot of redundancy in the datastore with such a design - but that's okay, since it allows you to query the datastore in a scalable fashion. Besides, this is not meant as a replacement for the architecture that you had in mind, but rather an additional Model designed specifically for the user-facing kind of queries that you need to do, ie. retrieving lists of complete product/parts information. These ProductPart entities could be populated by background tasks, replicating data located in your other normalized entities which would be the authoritative data source. Since you have plenty of data storage on App Engine, this should not be a problem. A: IMO your design mostly makes sense. I did come up with almost same design after reading your problem statement. With a few differnces I had prices with Product and ProductPart not as a separate table. Other difference was part_types. If there are not many part_type you can simply have them as python list/tuple. part_types = ('wheel', 'break', 'mirror') It also depends on kind of queries you are anticipating. If there are many queries of nature price calculation (independent of rest of product and part info) then it might make sense to design it way you have done. You have mentioned that you will get all the data first. Isn't querying possible? If you get the whole data in your app and then sort/filter in python then it would be slow. Which database are you considering? For me mongodb looks like a good option here. Finally why are you suspicious about even 1000 records? You can run a few tests on your db beforehand. Bests
Designing a scalable product database on Google App Engine
I've built a product database that is divided in 3 parts. And each part has a "sub" part containing labels. But the more I work with it the more unstable it feels. And each addition I make it takes more and more code to get it to work. A product is built of parts, and each part is of a type. Each product, part and type has a label. And there's a label for each language. A product contains parts in 2 list. One list for default parts (one of each type) and one of optional parts. Now I want to add currency in the mix and have come to the decision to re-model the entire way I handle this. The result I want to get is a list of all product objects that contains the name, description, price, all parts and all types that match the parts. And for these the correct language labels. Like so: product - name - description (by language) - price (by currency) - parts - part (type name and part name by language) - partPrice (by currency) The problem with my current setup that is a wild mix of db.ReferenceProperty and db.ListProperty(db.key) And getting all data by is a bit of a hassle that require multiple for-loops, matching dict and datastore calls. Well it's bit of a mess. The re-model(un-tested) look like this class Products(db.model) name = db.StringProperty() imageUrl = db.StringProperty() optionalParts = db.ListProperty(db.Key) defaultParts = db.ListProperty(db.Key) active = db.BooleanProperty(default=True) @property def itemId(self): return self.key().id() class ProductPartTypes(db.Model): name= db.StringProperty() @property def itemId(self): return self.key().id() class ProductParts(db.Model): name = db.StringProperty() type = db.ReferenceProperty(ProductPartTypes) imageUrl = db.StringProperty() parts = db.ListProperty(db.Key) @property def itemId(self): return self.key().id() class Labels(db.Model) key = db.StringProperty() #want to store a key here language = db.StringProperty() label = db.StringProperty() class Price(db.Model) key = db.StringProperty() #want to store a key here language = db.StringProperty() price = db.IntegerProperty() The major thing here is that I've split the Labels and Price out. So these can contain labels and prices for any products, parts or types. So what I am curious about, is this a solid solution from a architectural point of view? Will this hold even if there's thousands of entries in each model? Also, any tips for retrieving data in a good manner are welcome. My current solution of get all data first and for-looping over them and stick them in dicts works but feels like it could fail any minute. ..fredrik
[ "You need to keep in mind that App Engine's datastore requires you to rethink your usual way of designing databases. It goes against intuition at first but you must denormalize your data as much as possible if you want your application to be scalable. The datastore has been designed this way.\nThe approach I usuall...
[ 3, 1 ]
[]
[]
[ "architecture", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003785802_architecture_google_app_engine_google_cloud_datastore_python.txt
Q: How to draw same nodes with different edge colours correspond to two different graphs? Hope my question has not asked before. I have two graphs, which nodes are the same in both of them but edges are different. I want to draw both of graphs in one plot. Which means I have the same nodes, but with two different edge colours. But it gives me two different graphs. How could I have them in one graph but with different edge colours? A: If you are using Python, NetworkX and Matplotlib then you can do something like this, where you have two graphs with the same set of nodes and so you draw first the nodes and then the two set of edges in different colors. import networkx as nx G=nx.gnm_random_graph(10,20) G2=nx.gnm_random_graph(10,20) pos=nx.spring_layout(G) nx.draw_networkx_nodes(G,pos,node_size=80) nx.draw_networkx_edges(G,pos,edge_color='r') nx.draw_networkx_edges(G2,pos,edge_color='b') Take care with edges of different colors between the same endpoints, they will be indistinguishable.
How to draw same nodes with different edge colours correspond to two different graphs?
Hope my question has not asked before. I have two graphs, which nodes are the same in both of them but edges are different. I want to draw both of graphs in one plot. Which means I have the same nodes, but with two different edge colours. But it gives me two different graphs. How could I have them in one graph but with different edge colours?
[ "If you are using Python, NetworkX and Matplotlib then you can do something like this, where you have two graphs with the same set of nodes and so you draw first the nodes and then the two set of edges in different colors.\nimport networkx as nx \n\nG=nx.gnm_random_graph(10,20) \nG2=nx.gnm_random_graph(10,20) \n...
[ 1 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0003519845_networkx_python.txt
Q: Concatenate strings read from file with python? Emacs's auto-fill mode splits the line to make the document look nice. I need to join the strings read from the document. For example, (CR is the carriage return, not the real character) - Blah, Blah, and (CR) Blah, Blah, Blah, (CR) Blah, Blah (CR) - A, B, C (CR) Blah, Blah, Blah, (CR) Blah, Blah (CR) is read into string buffer array with readlines() function to produce ["Blah, Blah, and Blah, Blah, Blah, Blah, Blah", "A, B, C Blah, Blah, Blah, Blah, Blah"] I thought about having loop to check '-' to concatenate all the stored strings before it, but I expect Python has efficient way to do this. ADDED: Based on kindall's code, I could get what I want as follows. lines = ["- We shift our gears toward nextGen effort"," contribute the work with nextGen."] out = [(" " if line.startswith(" ") else "\n") + line.strip() for line in lines] print out res = ''.join(out).split('\n')[1:] print res The result is as follows. ['\n- We shift our gears toward nextGen effort', ' contribute the work with nextGen.'] ['- We shift our gears toward nextGen effort contribute the work with nextGen.'] A: As I read it, your problem is to undo hard-wrapping and restore each set of indented lines to a single soft-wrapped line. This is one way to do it: # hard-coded input, could also readlines() from a file lines = ["- Blah, Blah, and", " Blah, Blah, Blah,", " Blah, Blah", "- Blah, Blah, and", " Blah, Blah, Blah,", " Blah, Blah"] out = [(" " if line.startswith(" ") else "\n") + line.strip() for line in lines] out = ''.join(out)[1:].split('\n') print out A: I'm not sure if you want just : result = thefile.read() or maybe : result = ''.join(line.strip() for line in thefile) or something else ... A: Use file.readlines(). It returns a list of strings, each string being a line of the file: readlines(...) readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. EDIT: readlines() is not the best way to go, as has been pointed out in the comments. Disregard that suggestion and use the following one instead If you were to use the output that emacs provides as input into a python function, then I would give you this (if the emacs output is one long string): [s.replace("\n", "") for s in emacsOutput.split('-')] Hope this helps
Concatenate strings read from file with python?
Emacs's auto-fill mode splits the line to make the document look nice. I need to join the strings read from the document. For example, (CR is the carriage return, not the real character) - Blah, Blah, and (CR) Blah, Blah, Blah, (CR) Blah, Blah (CR) - A, B, C (CR) Blah, Blah, Blah, (CR) Blah, Blah (CR) is read into string buffer array with readlines() function to produce ["Blah, Blah, and Blah, Blah, Blah, Blah, Blah", "A, B, C Blah, Blah, Blah, Blah, Blah"] I thought about having loop to check '-' to concatenate all the stored strings before it, but I expect Python has efficient way to do this. ADDED: Based on kindall's code, I could get what I want as follows. lines = ["- We shift our gears toward nextGen effort"," contribute the work with nextGen."] out = [(" " if line.startswith(" ") else "\n") + line.strip() for line in lines] print out res = ''.join(out).split('\n')[1:] print res The result is as follows. ['\n- We shift our gears toward nextGen effort', ' contribute the work with nextGen.'] ['- We shift our gears toward nextGen effort contribute the work with nextGen.']
[ "As I read it, your problem is to undo hard-wrapping and restore each set of indented lines to a single soft-wrapped line. This is one way to do it:\n# hard-coded input, could also readlines() from a file\nlines = [\"- Blah, Blah, and\", \n \" Blah, Blah, Blah,\",\n \" Blah, Blah\",\n \"- ...
[ 4, 3, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003788426_python_string.txt
Q: Determine if an XMPP user is online or not I'm using the xmpppy library to write an XMPP client that can chat with users. It has its own XMPP user account and needs to know if a given user is online. However, the documentation is a bit sparse on how to do this. What would you recommend? The only solution I've seen thus far is to start up a daemon before the XMPP server starts and monitor all presence messages that are sent out - then a user is said to be online if they've sent the "I'm online"-type message but not the corresponding "I'm logging off" message. However, being new to XMPP in general, I would think there would be a nicer way to do this. A: The simple way is to support "subscribe" presence message -- this lets another user check if you're currently present (if they don't already know) by a "subscribe" attempt. Check this useful guide to get started, and the standard for many more important details (esp. on protecting your privacy, if needed, from subscribe requests from user you don't know). A: There are basically three ways to connect to an XMPP server: as a client (which you've done), as a component, and as another server. The server-to-server type (s2s) is just a federated connection, very much like how mail servers exchange email with each other. Alex described how clients keep track of presence. XMPP requires me to approve that you can receive my presence information and vice versa. For your bot this means for you to keep track of who's online the end users need to accept your presence requests. It also means that you can respond to the user's presence requests and keep them informed about if your bot is up or not. The last way is as a trusted component, and only works if you're running the server. i.e. if you're trying to do this on the jabber.org server, you're out of luck, because you're not running that server. The upsdie is you can have access to the internals of the XMPP server, like pulling lists of everyone who's online. The downside is your component / bot implementation is going to be different for every server implementation.
Determine if an XMPP user is online or not
I'm using the xmpppy library to write an XMPP client that can chat with users. It has its own XMPP user account and needs to know if a given user is online. However, the documentation is a bit sparse on how to do this. What would you recommend? The only solution I've seen thus far is to start up a daemon before the XMPP server starts and monitor all presence messages that are sent out - then a user is said to be online if they've sent the "I'm online"-type message but not the corresponding "I'm logging off" message. However, being new to XMPP in general, I would think there would be a nicer way to do this.
[ "The simple way is to support \"subscribe\" presence message -- this lets another user check if you're currently present (if they don't already know) by a \"subscribe\" attempt. Check this useful guide to get started, and the standard for many more important details (esp. on protecting your privacy, if needed, fro...
[ 2, 1 ]
[]
[]
[ "python", "xmpp", "xmpppy" ]
stackoverflow_0003737779_python_xmpp_xmpppy.txt
Q: Python socket send EOF I have a simple file transfer socket program where one socket sends file data and another socket receives the data and writes to a file I need to send an acknowledgment once transfer is finished from the destination to the source Code for destination s.accept() f = s.makefile() f.read(1024) Code for source s.connect(('localhost',6090)) f = s.makefile() f.write('abcd') f.flush() Here comes the problem, since "abcd" is not 1024 bytes, the destination will block till 1024 bytes are received The solution would be to close() the socket, but since I need a confirmation from destination, I cannot close the socket. How do I tell the destination to stop blocking? I was thinking of writing an EOF character I read online that "\x04" is EOF, but it doesn't work. Also since the data could be binary I don't want to use the readline() method. A: Design a protocol (an agreement between client and server) on how to send messages. One simple way is "the first byte is the length of the message, followed by the message". Rough example: Client Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from socket import * >>> s=socket() >>> s.connect(('localhost',5000)) >>> f=s.makefile() >>> f.write('\x04abcd') >>> f.flush() Server Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from socket import * >>> s=socket() >>> s.bind(('localhost',5000)) >>> s.listen(1) >>> c,a=s.accept() >>> f=c.makefile() >>> length=ord(f.read(1)) >>> f.read(length) 'abcd' A: Writing and reading from a socket are separate. You can try to close a socket for writing and leave it open for reading. See http://docs.python.org/library/socket.html#socket.socket.shutdown Also, what FTP does is use two sockets: one for data, and one for this "confirmation". You'd be happier using a second socket for this additional metadata. A: You don't actually want to use an 'EOF' marker if you intend to send any binary data through the pipe. What happens if your binary data happens to include that byte sequence? You could 'escape' it to prevent that from happening, but that requires you to check on both ends, and then make sure you escape your escape sequence as well. If you are doing this for some kind of production system, look around to see if there's a networking API that you can use (something like FTP, HTTP, SFTP, etc). If this is a school or small-scale project, what you need to do is write a communications protocol. The simplest might be for the sender to broadcast a single binary integer X (pick a data size, and stick with it), and then send X bytes of binary data. The receiver first snags the size, then only expects to receive that amount of data. Remember that if you need to send more bytes than the data size of X can send, you'll need to 'chunk' your data. Also consider what happens when communications are lost mid-transfer. You can set timeouts on read(), but then you need to recover gracefully if communications resumes immediately after your timeout (although junking all of the data might be considered graceful, depending on the system).
Python socket send EOF
I have a simple file transfer socket program where one socket sends file data and another socket receives the data and writes to a file I need to send an acknowledgment once transfer is finished from the destination to the source Code for destination s.accept() f = s.makefile() f.read(1024) Code for source s.connect(('localhost',6090)) f = s.makefile() f.write('abcd') f.flush() Here comes the problem, since "abcd" is not 1024 bytes, the destination will block till 1024 bytes are received The solution would be to close() the socket, but since I need a confirmation from destination, I cannot close the socket. How do I tell the destination to stop blocking? I was thinking of writing an EOF character I read online that "\x04" is EOF, but it doesn't work. Also since the data could be binary I don't want to use the readline() method.
[ "Design a protocol (an agreement between client and server) on how to send messages. One simple way is \"the first byte is the length of the message, followed by the message\". Rough example:\nClient\nPython 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32\nType \"help\", \"copyright\...
[ 7, 4, 3 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0003788439_python_sockets.txt
Q: Reusing Generators in Different Unit Tests I'm running into an issue while unit-testing a Python project that I'm working on which uses generators. Simplified, the project/unit-test looks like this: I have a setUp() function which creates a Person instance. Person is a class that has a generator, next_task(), which yields the next task that a Person has. I now have two unit-tests that test different things about the way the generator works, using a for loop. The first test works exactly as I'd expect, and the second one never even enters the loop. In both unit tests, the first line of code is: for rank, task in enumerate(self.person.next_task()): My guess is that this isn't working because the same generator function is being used in two separate unit tests. But that doesn't seem like the way that generators or unit-tests are supposed to work. Shouldn't I be able to iterate twice across the list of tasks? Also, shouldn't each unit-test be working with an essentially different instance of the Person, since the Person instance is created in setUp()? A: If you are really creating a new Person object in setUp then it should work as you expect. There are several reasons why it may not be working: 1) you are initialising the Person's tasks from another iterator, and that is exhausted by the second time you create Person. 2) You are creating a new Person object each time but the task generator is a class variable instead of an instance variable, so is shared between the class instances. 3) You think you are creating a new Person object but in reality you are not for some reason. Perhaps it is implemented as a singleton. 4) the unittest setUp method is broken. Of these I think (4) is least likely, but we would need to see more of you code before we can track down the real problem. A: The yielded results of a generator are consumed by the first for loop that uses it. Afterwards, the generator function returns and is finished - and thus empty. As the second unit test uses the very same generator object, it doesn't enter the loop. You have to create a new generator for the second unit test, or use itertools.tee to make N separate iterators out of one generator. Generators do not work the way you think. On each call to generatorObject.next(), the next yielded result is returned, but the result does not get stored anywhere. That's why generators are often used for lazy operations. If you want to reuse the results, you can use itertools.tee as I said, or convert the generator to a tuple/list of results. A hint on using itertools.tee from the documentation: This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().
Reusing Generators in Different Unit Tests
I'm running into an issue while unit-testing a Python project that I'm working on which uses generators. Simplified, the project/unit-test looks like this: I have a setUp() function which creates a Person instance. Person is a class that has a generator, next_task(), which yields the next task that a Person has. I now have two unit-tests that test different things about the way the generator works, using a for loop. The first test works exactly as I'd expect, and the second one never even enters the loop. In both unit tests, the first line of code is: for rank, task in enumerate(self.person.next_task()): My guess is that this isn't working because the same generator function is being used in two separate unit tests. But that doesn't seem like the way that generators or unit-tests are supposed to work. Shouldn't I be able to iterate twice across the list of tasks? Also, shouldn't each unit-test be working with an essentially different instance of the Person, since the Person instance is created in setUp()?
[ "If you are really creating a new Person object in setUp then it should work as you expect. There are several reasons why it may not be working:\n1) you are initialising the Person's tasks from another iterator, and that is exhausted by the second time you create Person.\n2) You are creating a new Person object ea...
[ 3, 0 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0003788878_python_unit_testing.txt
Q: Why am I getting this UnicodeEncodeError when I am inserting into the MySQL database? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 2: ordinal not in range(128) I changed my database default to be utf-8, and not "latin"....but this error still occurs. why? This is in my.cnf. Am I doing this wrong? I just want EVERYTHING TO BE UTF-8. init_connect='SET collation_connection = utf8_general_ci' init_connect='SET NAMES utf8' default-character-set=utf8 character-set-server = utf8 collation-server = utf8_general_ci default-character-set=utf8 A: MySQLdb.connect(read_default_*) options won't set the character set from default-character-set. You will need to set this explicitly: MySQLdb.connect(..., charset='utf8') Or the equivalent setting in your django databases settings. A: If you get an exception from Python then it's nothing to do with MySQL -- the error happens before the expression is sent to MySQL. I would presume that the MySQLdb driver doesn't handle unicode. If you are dealing with the raw MySQLdb interface this will be somewhat annoying (database wrappers like SQLAlchemy will handle this stuff for you), but you might want to create a function like this: def exec_sql(conn_or_cursor, sql, *args, **kw): if hasattr(conn_or_cursor): cursor = conn_or_cursor.cursor() else: cursor = conn_or_cursor cursor.execute(_convert_utf8(sql), *(_convert_utf8(a) for a in args), **dict((n, _convert_utf8(v)) for n, v in kw.iteritems())) return cursor def _convert_utf8(value): if isinstance(value, unicode): return value.encode('utf8') else: return value
Why am I getting this UnicodeEncodeError when I am inserting into the MySQL database?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 2: ordinal not in range(128) I changed my database default to be utf-8, and not "latin"....but this error still occurs. why? This is in my.cnf. Am I doing this wrong? I just want EVERYTHING TO BE UTF-8. init_connect='SET collation_connection = utf8_general_ci' init_connect='SET NAMES utf8' default-character-set=utf8 character-set-server = utf8 collation-server = utf8_general_ci default-character-set=utf8
[ "MySQLdb.connect(read_default_*) options won't set the character set from default-character-set. You will need to set this explicitly:\nMySQLdb.connect(..., charset='utf8')\n\nOr the equivalent setting in your django databases settings.\n", "If you get an exception from Python then it's nothing to do with MySQL ...
[ 2, 0 ]
[]
[]
[ "database", "django", "encoding", "mysql", "python" ]
stackoverflow_0002761378_database_django_encoding_mysql_python.txt
Q: Python copy MySQL table to SQLite3 I've got a MySQL table with about ~10m rows. I created a parallel schema in SQLite3, and I'd like to copy the table somehow. Using Python seems like an acceptable solution, but this way -- # ... mysqlcursor.execute('SELECT * FROM tbl') rows = mysqlcursor.fetchall() # or mysqlcursor.fetchone() for row in rows: # ... insert row via sqlite3 cursor ...is incredibly slow (hangs at .execute(), I wouldn't know for how long). I'd only have to do this once, so I don't mind if it takes a couple of hours, but is there a different way to do this? Using a different tool rather than Python is also acceptable. A: The simplest way might be to use mysqldump to get a SQL file of the whole db, then use the SQLite command-line tool to execute the file. A: You don't show exactly how you insert rows, but you mention execute(). You might try executemany()* instead. For example: import sqlite3 conn = sqlite3.connect('mydb') c = conn.cursor() # one '?' placeholder for each column you're inserting # "rows" needs to be a sequence of values, e.g. ((1,'a'), (2,'b'), (3,'c')) c.executemany("INSERT INTO tbl VALUES (?,?);", rows) conn.commit() *executemany() as described in the Python DB-API: .executemany(operation,seq_of_parameters) Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters. A: You can export a flat file from mysql using select into outfile and import those with sqlite's .import: mysql> SELECT * INTO OUTFILE '/tmp/export.txt' FROM sometable; sqlite> .separator "\t" sqlite> .import /tmp/export.txt sometable This handles the data export/import but not copying the schema, of course. If you really want to do this with python (maybe to transform the data), I would use a MySQLdb.cursors.SSCursor to iterate over the data - otherwise the mysql resultset gets cached in memory which is why your query is hanging on execute. So that would look something like: import MySQLdb import MySQLdb.cursors connection = MySQLdb.connect(...) cursor = connection.cursor(MySQLdb.cursors.SSCursor) cursor.execute('SELECT * FROM tbl') for row in cursor: # do something with row and add to sqlite database That will be much slower than the export/import approach.
Python copy MySQL table to SQLite3
I've got a MySQL table with about ~10m rows. I created a parallel schema in SQLite3, and I'd like to copy the table somehow. Using Python seems like an acceptable solution, but this way -- # ... mysqlcursor.execute('SELECT * FROM tbl') rows = mysqlcursor.fetchall() # or mysqlcursor.fetchone() for row in rows: # ... insert row via sqlite3 cursor ...is incredibly slow (hangs at .execute(), I wouldn't know for how long). I'd only have to do this once, so I don't mind if it takes a couple of hours, but is there a different way to do this? Using a different tool rather than Python is also acceptable.
[ "The simplest way might be to use mysqldump to get a SQL file of the whole db, then use the SQLite command-line tool to execute the file.\n", "You don't show exactly how you insert rows, but you mention execute().\nYou might try executemany()* instead.\nFor example:\nimport sqlite3\nconn = sqlite3.connect('mydb')...
[ 3, 3, 0 ]
[]
[]
[ "database", "mysql", "python", "sqlite" ]
stackoverflow_0003124162_database_mysql_python_sqlite.txt
Q: Please point to the right webdev tools I'm making a simple web app where I have some simple python scripts that do the text crunchin g I need - but I'm not quite sure how to interface it with a client who'd only want to see some HTML forms. There's so many different server side frameworks out there - but I don't think I need anything too heavy duty - just a mechanism to accept data from the forms that the user fills in, and feed it to my Python code and back. Could someone suggest what tools I should look into and what design paradigms I should follow? Simple pointers to different references around the web with a single line about their significance would also help. Best. A: At the moment, the best lightweight and yet very powerful framework for python IMO is Flask. If you want form abstraction there is a WTFlask plugin for it which is WTForms adapted for flask - http://flask.pocoo.org/. Web2py is also a very good framework for starters because it has helpers and wizards for creating/running an application, and also has something like an admin interface, offering an On-line IDE functionality. - http://www.web2py.com/ I proposed these two frameworks because you can start fast with them, they both have good documentation, both are powerful yet easy and they are pretty friendly for beginners. A: Not normally supported with cheap hosting, but mod_python on apache might be right up your alley. You could also have html talk to python through cgi (Which has been the way of doing it for years before php came along). The standard Design pattern commonly seen in web apps is Model-View-Controller, so google around. A: I've used Django (heavy and something of a non-trivial initial learning curve), and web.py (very small & simple), and over the past year, I've been pretty happy using tornado. People can argue about the async details, but that's not even why I use it. It's pretty fast, it's super quick to get started with, it comes with examples that get you doing things quickly, and -- most important to me -- It's a web server and framework in one, which means you don't have to muck with mod_python vs mod_wsgi vs cgi vs fcgi vs whatever. Deployment is really easy.
Please point to the right webdev tools
I'm making a simple web app where I have some simple python scripts that do the text crunchin g I need - but I'm not quite sure how to interface it with a client who'd only want to see some HTML forms. There's so many different server side frameworks out there - but I don't think I need anything too heavy duty - just a mechanism to accept data from the forms that the user fills in, and feed it to my Python code and back. Could someone suggest what tools I should look into and what design paradigms I should follow? Simple pointers to different references around the web with a single line about their significance would also help. Best.
[ "At the moment, the best lightweight and yet very powerful framework for python IMO is Flask. If you want form abstraction there is a WTFlask plugin for it which is WTForms adapted for flask - http://flask.pocoo.org/.\nWeb2py is also a very good framework for starters because it has helpers and wizards for creating...
[ 3, 1, 0 ]
[]
[]
[ "forms", "html", "python" ]
stackoverflow_0003790043_forms_html_python.txt
Q: How can I package a scrapy project using cxfreeze? I have a scrapy project that I would like to package all together for a customer using windows without having to manually install dependencies for them. I came across cxfreeze, but I'm not quite sure how it would work with a scrapy project. I'm thinking I would make some sort of interface and run the scrapy crawler with 'from scrapy.cmdline import execute', but I'm not sure. Thanks in advance for any help. A: Try out py2exe. It works well, you can bundle all the code in one exe. I suggest you to exclude unused packages to reduce exe size (see py2exe examples on its site) UDATE As suggested try also GUI2Exe is a Graphical User Interface frontend to all the "executable builders" available for the Python programming language. It can be used to build standalone Windows executables, Linux applications and Mac OS application bundles and plugins starting from Python scripts.
How can I package a scrapy project using cxfreeze?
I have a scrapy project that I would like to package all together for a customer using windows without having to manually install dependencies for them. I came across cxfreeze, but I'm not quite sure how it would work with a scrapy project. I'm thinking I would make some sort of interface and run the scrapy crawler with 'from scrapy.cmdline import execute', but I'm not sure. Thanks in advance for any help.
[ "Try out py2exe. It works well, you can bundle all the code in one exe.\nI suggest you to exclude unused packages to reduce exe size (see py2exe examples on its site)\nUDATE\n As suggested try also\n\nGUI2Exe is a Graphical User\n Interface frontend to all the\n \"executable builders\" available for\n the Python...
[ 1 ]
[]
[]
[ "py2exe", "python", "scrapy", "screen_scraping" ]
stackoverflow_0003790563_py2exe_python_scrapy_screen_scraping.txt
Q: Python os.walk and japanese filename crash Possible Duplicate: Python, Unicode, and the Windows console I have a folder with a filename "01 - ナナナン塊.txt" I open python at the interactive prompt in the same folder as the file and attempt to walk the folder hierachy: Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> for x in os.walk('.'): ... print(x) ... Traceback (most recent call last): File "<stdin>", line 2, in <module> File "C:\dev\Python31\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 17-21: character maps to <undefined> Clearly the encoding I'm using isn't able to deal with Japanese characters. Fine. But Python 3.1 is meant to be unicode all the way down, as I understand it, so I'm at a loss as to what I'm meant to do with this. Anyone have any ideas? A: It seems like all answers so far are from Unix people who assume the Windows console is like a Unix terminal, which it is not. The problem is that you can't write Unicode output to the Windows console using the normal underlying file I/O functions. The Windows API WriteConsole needs to be used. Python should probably be doing this transparently, but it isn't. There's a different problem if you redirect the output to a file: Windows text files are historically in the ANSI codepage, not Unicode. You can fairly safely write UTF-8 to text files in Windows these days, but Python doesn't do that by default. I think it should do these things, but here's some code to make it happen. You don't have to worry about the details if you don't want to; just call ConsoleFile.wrap_standard_handles(). You do need PyWin installed to get access to the necessary APIs. import os, sys, io, win32api, win32console, pywintypes def change_file_encoding(f, encoding): """ TextIOWrapper is missing a way to change the file encoding, so we have to do it by creating a new one. """ errors = f.errors line_buffering = f.line_buffering # f.newlines is not the same as the newline parameter to TextIOWrapper. # newlines = f.newlines buf = f.detach() # TextIOWrapper defaults newline to \r\n on Windows, even though the underlying # file object is already doing that for us. We need to explicitly say "\n" to # make sure we don't output \r\r\n; this is the same as the internal function # create_stdio. return io.TextIOWrapper(buf, encoding, errors, "\n", line_buffering) class ConsoleFile: class FileNotConsole(Exception): pass def __init__(self, handle): handle = win32api.GetStdHandle(handle) self.screen = win32console.PyConsoleScreenBufferType(handle) try: self.screen.GetConsoleMode() except pywintypes.error as e: raise ConsoleFile.FileNotConsole def write(self, s): self.screen.WriteConsole(s) def close(self): pass def flush(self): pass def isatty(self): return True @staticmethod def wrap_standard_handles(): sys.stdout.flush() try: # There seems to be no binding for _get_osfhandle. sys.stdout = ConsoleFile(win32api.STD_OUTPUT_HANDLE) except ConsoleFile.FileNotConsole: sys.stdout = change_file_encoding(sys.stdout, "utf-8") sys.stderr.flush() try: sys.stderr = ConsoleFile(win32api.STD_ERROR_HANDLE) except ConsoleFile.FileNotConsole: sys.stderr = change_file_encoding(sys.stderr, "utf-8") ConsoleFile.wrap_standard_handles() print("English 漢字 Кири́ллица") This is a little tricky: if stdout or stderr is the console, we need to output with WriteConsole; but if it's not (eg. foo.py > file), that's not going to work, and we need to change the file's encoding to UTF-8 instead. The opposite in either case will not work. You can't output to a regular file with WriteConsole (it's not actually a byte API, but a UTF-16 one; PyWin hides this detail), and you can't write UTF-8 to a Windows console. Also, it really should be using _get_osfhandle to get the handle to stdout and stderr, rather than assuming they're assigned to the standard handles, but that API doesn't seem to have any PyWin binding.
Python os.walk and japanese filename crash
Possible Duplicate: Python, Unicode, and the Windows console I have a folder with a filename "01 - ナナナン塊.txt" I open python at the interactive prompt in the same folder as the file and attempt to walk the folder hierachy: Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> for x in os.walk('.'): ... print(x) ... Traceback (most recent call last): File "<stdin>", line 2, in <module> File "C:\dev\Python31\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 17-21: character maps to <undefined> Clearly the encoding I'm using isn't able to deal with Japanese characters. Fine. But Python 3.1 is meant to be unicode all the way down, as I understand it, so I'm at a loss as to what I'm meant to do with this. Anyone have any ideas?
[ "It seems like all answers so far are from Unix people who assume the Windows console is like a Unix terminal, which it is not.\nThe problem is that you can't write Unicode output to the Windows console using the normal underlying file I/O functions. The Windows API WriteConsole needs to be used. Python should pr...
[ 7 ]
[ "For hard-coded strings, you'll need to specify the encoding at the top of source files. For bytestrings input from some other source - such as os.walk -, you need to specify the byte string's encoding (see unutbu's answer).\n" ]
[ -2 ]
[ "filesystems", "python", "unicode", "windows" ]
stackoverflow_0003789924_filesystems_python_unicode_windows.txt
Q: Piecewise list comprehensions in python What is the easiest/most elegant way to do the following in python: def piecewiseProperty(aList): result = [] valueTrue = 50 valueFalse = 10 for x in aList: if hasProperty(x): result.append(valueTrue) else result.append(valueFalse) return result where hasProperty is some function with boolean return value. One shorter (but opaque, and possibly less efficient) R-like way to do it would be this trueIndexSet = set([ ind for ind,x in enumerate(aList) if hasProperty(x) ]) falseIndexSet = set(range(0:len(aList)).difference(trueIndexSet) vals = sorted( [ (ind,10) for ind in falseIndexSet ] + [ (ind,50) for ind in trueIndexSet ] ) [ x for ind,x in vals] Another much tidier approach would use dictionary lookup: [ {True:50, False:10}[hasProperty(x)] for x in aList ] Is there some clever and readable one-liner or built in function for doing this? It would basically be an if...else list comprehension. Application of this question: Just in case it's of interest, I am using this to assign sizes to nodes in a network so that they are drawn differently. I want to draw nodes named with prefix "small_" size 10 and draw the other nodes size 50. NetworkX and pygraphviz can alter the sizes of the nodes by accepting a list of sizes, one for each node. A: Use a conditional expression (pep-308): [50 if hasProperty(x) else 10 for x in alist] A: How about: [50 if hasProperty(x) else 10 for x in aList] ?
Piecewise list comprehensions in python
What is the easiest/most elegant way to do the following in python: def piecewiseProperty(aList): result = [] valueTrue = 50 valueFalse = 10 for x in aList: if hasProperty(x): result.append(valueTrue) else result.append(valueFalse) return result where hasProperty is some function with boolean return value. One shorter (but opaque, and possibly less efficient) R-like way to do it would be this trueIndexSet = set([ ind for ind,x in enumerate(aList) if hasProperty(x) ]) falseIndexSet = set(range(0:len(aList)).difference(trueIndexSet) vals = sorted( [ (ind,10) for ind in falseIndexSet ] + [ (ind,50) for ind in trueIndexSet ] ) [ x for ind,x in vals] Another much tidier approach would use dictionary lookup: [ {True:50, False:10}[hasProperty(x)] for x in aList ] Is there some clever and readable one-liner or built in function for doing this? It would basically be an if...else list comprehension. Application of this question: Just in case it's of interest, I am using this to assign sizes to nodes in a network so that they are drawn differently. I want to draw nodes named with prefix "small_" size 10 and draw the other nodes size 50. NetworkX and pygraphviz can alter the sizes of the nodes by accepting a list of sizes, one for each node.
[ "Use a conditional expression (pep-308):\n[50 if hasProperty(x) else 10 for x in alist]\n\n", "How about:\n[50 if hasProperty(x) else 10 for x in aList]\n\n?\n" ]
[ 4, 3 ]
[]
[]
[ "list", "list_comprehension", "piecewise", "python" ]
stackoverflow_0003791245_list_list_comprehension_piecewise_python.txt
Q: Saving a StackedInline foreign keyed model before primary model in Django Admin I have four models with the relationships Model PagetTemplate(models.Model): pass Model TextKey(models.Model): page_template = models.ForeignKey(PageTemplate, related_name='text_keys') Model Page(models.Model): page_template = models.ForeignKey(Pagetemplate, related_name='pages') Model Text(models.Model): key = models.ForeignKey(TextKey, related_name='text_fields') page = models.ForeignKey(Page, related_name='text_fields') the relation is like this: PageTemplate /\ / \ / \ TextKey Page \ / \ / \/ Text In the validation for page (In the clean method), I check that [key for key in page.page_template.text_keys] and [text_field.key for text_field in page.text_fields] match up so that all text keys are filled in my a text. The problem I am having is that at the time the clean is called, page.text_fields is empty. The admin code looks like. class TextInline(admin.StackedInline): model = Text extra = 0 class PageAdmin(DebugModelAdmin): inlines = [TextInline] admin.site.register(Page, PageAdmin) I wrapped admin.ModelAdmin in a logging class and know that I have the information I need when ModelAdmin.add_view is called but is overriding this the right thing to do or is there some option/method that would be better to override that I'm missing? A: Looking at S. Lott's sagacious advice on various django related threads, I decided to write an app to do this myself instead of forcing the django admin to do something that it wasn't meant to do. I would honestly just download a decent CMS for django but the ones that I can find either suck (their code is riddled with typechecking, indented with tabs, etc) or don't work on 1.2, so i'm rolling my own.
Saving a StackedInline foreign keyed model before primary model in Django Admin
I have four models with the relationships Model PagetTemplate(models.Model): pass Model TextKey(models.Model): page_template = models.ForeignKey(PageTemplate, related_name='text_keys') Model Page(models.Model): page_template = models.ForeignKey(Pagetemplate, related_name='pages') Model Text(models.Model): key = models.ForeignKey(TextKey, related_name='text_fields') page = models.ForeignKey(Page, related_name='text_fields') the relation is like this: PageTemplate /\ / \ / \ TextKey Page \ / \ / \/ Text In the validation for page (In the clean method), I check that [key for key in page.page_template.text_keys] and [text_field.key for text_field in page.text_fields] match up so that all text keys are filled in my a text. The problem I am having is that at the time the clean is called, page.text_fields is empty. The admin code looks like. class TextInline(admin.StackedInline): model = Text extra = 0 class PageAdmin(DebugModelAdmin): inlines = [TextInline] admin.site.register(Page, PageAdmin) I wrapped admin.ModelAdmin in a logging class and know that I have the information I need when ModelAdmin.add_view is called but is overriding this the right thing to do or is there some option/method that would be better to override that I'm missing?
[ "Looking at S. Lott's sagacious advice on various django related threads, I decided to write an app to do this myself instead of forcing the django admin to do something that it wasn't meant to do. I would honestly just download a decent CMS for django but the ones that I can find either suck (their code is riddled...
[ 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0003755058_django_django_admin_django_models_python.txt
Q: Python number wrapping? Consider this Python code: assert(a > 0) assert(b > 0) assert(a + b > 0) Can the third assert ever fail? In C/C++, it can if the sum overflows the maximum integer value. How is this handled in Python? A: Depends on which version of Python you're using. Prior to 2.2 or so, you could get an OverflowError. Version 2.2-2.7 promote the sum to a long (arbitrary precision) if it's too large to fit in an int. 3.0+ has only one integer type, which is arbitrary precision. A: Python will automatically promote integers to arbitrary precision. If a float becomes too large it will be inf. Thus, this would only fail if a and b are both integral and you run out of memory. A: If a + b is is larger than the maximum integer value, the result will be a long: >>> import sys >>> sys.maxint 9223372036854775807 >>> a = sys.maxint >>> b = 1 >>> a + b 9223372036854775808L # A long >>> assert a > 0 >>> assert b > 0 >>> assert a + b > 0
Python number wrapping?
Consider this Python code: assert(a > 0) assert(b > 0) assert(a + b > 0) Can the third assert ever fail? In C/C++, it can if the sum overflows the maximum integer value. How is this handled in Python?
[ "Depends on which version of Python you're using.\nPrior to 2.2 or so, you could get an OverflowError.\nVersion 2.2-2.7 promote the sum to a long (arbitrary precision) if it's too large to fit in an int.\n3.0+ has only one integer type, which is arbitrary precision.\n", "Python will automatically promote integers...
[ 9, 3, 1 ]
[ "Ok the answer to your question is generally no, however if you deal with large numbers you can have some problems, below are details on python's big numbers.\nAlso see this post for info on inf (infinity) NaN (not a number (i.e infinity / infinity = NaN) )\n\nPlease Note: This is on a 32 bit AMD machine (Though py...
[ -1 ]
[ "python" ]
stackoverflow_0003791312_python.txt
Q: Is there any other way besides browser extensions that one could have a GUI bar hover over any website a user visits? Goal I want to create a web app with a horizontal GUI bar that floats with the user as they move from site to site. e.g. A user will sign into the web at the home page and then proceed to say Google to start searching for their topic. Once they are signed in and leave the web app homepage a horizontal GUI bar will appear on each page they visit until they log out. So when a user goes to Google to start searching the GUI bar will be there. When they click on a link and go to that page, the GUI bar will be there too. Known Ways I noticed apps like Get Glue and Layers.com work by having the user install browser extensions. I would like to avoid this if possible. Additionally it can not be like the Digg Bar because it only appears when a user presses the book marklet or places digg.com in front of the site/page URL. It also can't be like the Facebook or Meebo bars because it requires the web developer to already have implemented that code on their site. Closest Example The best example of what I am trying to go after is something like Google Image search where if you click an image Google will open up the site (but grayed out) with the picture hovering above it and a left side bar with image info in it. So Google opens a site with in it self. Another example might be Stumble Upon's top GUI bar. Is my idea possible with technologies like AJAX and Python? A: The closest you can get is using (ick) frames, with one frame for your bar and one for the page. That's what Google Image Search does. It can easily get broken by frame-busting scripts though. A: Is my idea possible with technologies like AJAX and Python? If the pages you want floating under the bar belong to a different domain than yours (it seems like that's what you want), then the answer is No. This is not possible with client-sided scripting alone (eg: Javascript) because of the same origin policy. What you use on the server side, Python or Ruby or whatever is irrelevant.
Is there any other way besides browser extensions that one could have a GUI bar hover over any website a user visits?
Goal I want to create a web app with a horizontal GUI bar that floats with the user as they move from site to site. e.g. A user will sign into the web at the home page and then proceed to say Google to start searching for their topic. Once they are signed in and leave the web app homepage a horizontal GUI bar will appear on each page they visit until they log out. So when a user goes to Google to start searching the GUI bar will be there. When they click on a link and go to that page, the GUI bar will be there too. Known Ways I noticed apps like Get Glue and Layers.com work by having the user install browser extensions. I would like to avoid this if possible. Additionally it can not be like the Digg Bar because it only appears when a user presses the book marklet or places digg.com in front of the site/page URL. It also can't be like the Facebook or Meebo bars because it requires the web developer to already have implemented that code on their site. Closest Example The best example of what I am trying to go after is something like Google Image search where if you click an image Google will open up the site (but grayed out) with the picture hovering above it and a left side bar with image info in it. So Google opens a site with in it self. Another example might be Stumble Upon's top GUI bar. Is my idea possible with technologies like AJAX and Python?
[ "The closest you can get is using (ick) frames, with one frame for your bar and one for the page. That's what Google Image Search does. It can easily get broken by frame-busting scripts though.\n", "\nIs my idea possible with technologies\n like AJAX and Python?\n\nIf the pages you want floating under the bar be...
[ 1, 0 ]
[]
[]
[ "ajax", "browser", "python", "user_interface" ]
stackoverflow_0003791527_ajax_browser_python_user_interface.txt
Q: Building Python libraries on a Mac and experiencing flat namespace errors As a general rule, I rue the days whenever I have to build Python libraries on a Mac. I've generally had fairly good success using Boost::Python, and if I use distutils, most of the time everything works correctly. However, I've never been able figure out the exact combination of what works/what doesn't work. Specifically, I've often run into the dreaded problem of a symbol not being found because the library I'm trying to use doesn't have a flat namespace. I've tried switching to the MacPorts version of Python, and then using only MacPorts libraries, and no dice. The most recent problem I ran into is a tool I need to use that is dependent on the OpenCV library, which in turn is dependent on the FFMPeg library (actually, both are). Everything compiles, but when I do 'import MYLIB', I get the symbol _pix_fmt_info not found in the flat namespace. I do a DYLIB_LIBRARY_PRINT to view all the libraries loaded, and sure enough libavformat, libavcodec, libavutil, and libswscale are all loaded. So, here are my questions. The specific question, does anyone have an idea of what might be going on here. Do I need to build libffmpeg by hand? Am I doing something really stupid like forgetting a library (I checked, and I don't think I am..) More generally, is there a good approach for dealing with the flat namespace issue? Do I always have to worry about which libraries are included? Does anyone have a good recipe for getting things to just work? Sometimes I do miss the world of Linux.. edit Sorry, it looks like it was my own stupidity at fault here. I haven't figured out the exact problem, but it looks like the unfound symbol belongs to a different library than I though (i.e. not libffmpeg). I am still curious about other people's experiences with flat namespaces, however. A: I have seen this issue when I compile the "C" python bindings with the option -fvisibility=hidden parameter on mac osx I am of understanding is that, this is similar to flat namespace issue.
Building Python libraries on a Mac and experiencing flat namespace errors
As a general rule, I rue the days whenever I have to build Python libraries on a Mac. I've generally had fairly good success using Boost::Python, and if I use distutils, most of the time everything works correctly. However, I've never been able figure out the exact combination of what works/what doesn't work. Specifically, I've often run into the dreaded problem of a symbol not being found because the library I'm trying to use doesn't have a flat namespace. I've tried switching to the MacPorts version of Python, and then using only MacPorts libraries, and no dice. The most recent problem I ran into is a tool I need to use that is dependent on the OpenCV library, which in turn is dependent on the FFMPeg library (actually, both are). Everything compiles, but when I do 'import MYLIB', I get the symbol _pix_fmt_info not found in the flat namespace. I do a DYLIB_LIBRARY_PRINT to view all the libraries loaded, and sure enough libavformat, libavcodec, libavutil, and libswscale are all loaded. So, here are my questions. The specific question, does anyone have an idea of what might be going on here. Do I need to build libffmpeg by hand? Am I doing something really stupid like forgetting a library (I checked, and I don't think I am..) More generally, is there a good approach for dealing with the flat namespace issue? Do I always have to worry about which libraries are included? Does anyone have a good recipe for getting things to just work? Sometimes I do miss the world of Linux.. edit Sorry, it looks like it was my own stupidity at fault here. I haven't figured out the exact problem, but it looks like the unfound symbol belongs to a different library than I though (i.e. not libffmpeg). I am still curious about other people's experiences with flat namespaces, however.
[ "I have seen this issue when I compile the \"C\" python bindings with the option \n-fvisibility=hidden parameter\n\non mac osx\nI am of understanding is that, this is similar to flat namespace issue.\n" ]
[ 0 ]
[]
[]
[ "boost_python", "flat", "macos", "namespaces", "python" ]
stackoverflow_0003791289_boost_python_flat_macos_namespaces_python.txt
Q: How do I get all instances of VLC on dbus quickly? basically the problem is, that the only way to get all instances of VLC is to search all non-named instances for the org.freedesktop.MediaPlayer identity function and call it. (alternatively I could use the introspection API, but this wouldn't seem to solve my problem) Unfortunately many programs upon having sent a dbus call, simply do not respond, causing a long and costly timeout. When this happens multiple times it can add up. Basically the builtin timeout is excessively long. If I can decrease the dbus timeout somehow that will solve my problem, but the ideal solution would be a way. I got the idea that I could put each call to "Identify" inside a thread and that I could kill threads that take too long, but this seems not to be suggested. Also adding multithreading greatly increases the CPU load while not increasing the speed of the program all that much. here is the code that I am trying to get to run quickly (more or less) which is currently painfully slow. import dbus bus = dbus.SessionBus() dbus_proxy = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus') names = dbus_proxy.ListNames() for name in names: if name.startswith(':'): try: proxy = bus.get_object(name, '/') ident_method = proxy.get_dbus_method("Identity", dbus_interface="org.freedesktop.MediaPlayer") print ident_method() except dbus.exceptions.DBusException: pass A: Easier than spawning a bunch of threads would be to make the calls to the different services asynchronously, providing a callback handler for when a result comes back or a D-Bus error occurs. All of the calls effectively happen in parallel, and your program can proceed as soon as it gets some positive results. Here's a quick-and-dirty program that prints a list of all the services it finds. Note how quickly it gets all the positive results without having to wait for any timeouts from anything. In a real program you'd probably assign a do-nothing function to the error handler, since your goal here is to ignore the services that don't respond, but this example waits until it's heard from everything before quitting. #! /usr/bin/env python import dbus import dbus.mainloop.glib import functools import glib class VlcFinder (object): def __init__ (self, mainloop): self.outstanding = 0 self.mainloop = mainloop bus = dbus.SessionBus () dbus_proxy = bus.get_object ("org.freedesktop.DBus", "/org/freedesktop/DBus") names = dbus_proxy.ListNames () for name in dbus_proxy.ListNames (): if name.startswith (":"): proxy = bus.get_object (name, "/") iface = dbus.Interface (proxy, "org.freedesktop.MediaPlayer") iface.Identity (reply_handler = functools.partial (self.reply_cb, name), error_handler = functools.partial (self.error_cb, name)) self.outstanding += 1 def reply_cb (self, name, ver): print "Found {0}: {1}".format (name, ver) self.received_result () def error_cb (self, name, msg): self.received_result () def received_result (self): self.outstanding -= 1 if self.outstanding == 0: self.mainloop.quit () if __name__ == "__main__": dbus.mainloop.glib.DBusGMainLoop (set_as_default = True) mainloop = glib.MainLoop () finder = VlcFinder (mainloop) mainloop.run ()
How do I get all instances of VLC on dbus quickly?
basically the problem is, that the only way to get all instances of VLC is to search all non-named instances for the org.freedesktop.MediaPlayer identity function and call it. (alternatively I could use the introspection API, but this wouldn't seem to solve my problem) Unfortunately many programs upon having sent a dbus call, simply do not respond, causing a long and costly timeout. When this happens multiple times it can add up. Basically the builtin timeout is excessively long. If I can decrease the dbus timeout somehow that will solve my problem, but the ideal solution would be a way. I got the idea that I could put each call to "Identify" inside a thread and that I could kill threads that take too long, but this seems not to be suggested. Also adding multithreading greatly increases the CPU load while not increasing the speed of the program all that much. here is the code that I am trying to get to run quickly (more or less) which is currently painfully slow. import dbus bus = dbus.SessionBus() dbus_proxy = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus') names = dbus_proxy.ListNames() for name in names: if name.startswith(':'): try: proxy = bus.get_object(name, '/') ident_method = proxy.get_dbus_method("Identity", dbus_interface="org.freedesktop.MediaPlayer") print ident_method() except dbus.exceptions.DBusException: pass
[ "Easier than spawning a bunch of threads would be to make the calls to the different services asynchronously, providing a callback handler for when a result comes back or a D-Bus error occurs. All of the calls effectively happen in parallel, and your program can proceed as soon as it gets some positive results.\nH...
[ 1 ]
[]
[]
[ "dbus", "linux", "multithreading", "python" ]
stackoverflow_0003791697_dbus_linux_multithreading_python.txt
Q: what constitutes a member of a class? What constitutes a method? It seems that an acceptable answer to the question What is a method? is A method is a function that's a member of a class. I disagree with this. class Foo(object): pass def func(): pass Foo.func = func f = Foo() print "fine so far" try: f.func() except TypeError: print "whoops! func must not be a method after all" Is func a member of Foo? Is func a method of Foo? I am well aware that this would work if func had a self argument. That's obvious. I'm interested in if it's a member of foo and in if it's a method as presented. A: You're just testing it wrong: >>> class Foo(object): pass ... >>> def func(self): pass ... >>> Foo.func = func >>> f = Foo() >>> f.func() >>> You error of forgetting to have in the def the self argument has absolutely nothing to do with f.func "not being a method", of course. The peculiar conceit of having the def outside the class instead of inside it (perfectly legal Python of course, but, as I say, peculiar) has nothing to do with the case either: if you forget to have a first argument (conventionally named self) in your def statements for methods, you'll get errors in calling them, of course (a TypeError is what you get, among other cases, whenever the actual arguments specified in the call can't match the formal arguments accepted by the def, of course). A: The type error wouldn't be thrown if func had a self argument, like any other instance method. That's because when you evaluate f.func, you're actually binding f to the first argument of the function -- it then becomes a partial application which you can provide further arguments to. If you want it to be a static method, then you need the staticmethod decorator which just throws away the first parameter and passes the rest into the original function. So 2 ways of making it work: def func(self): pass -- or -- Foo.func = staticmethod(func) depending on what you're aiming for. A: As written, func is a member of Foo and a method of Foo instances such as your f. However, it can't be successfully called because it doesn't accept at least one argument. func is in f's namespace and has a _call_() method. In other words, it is enough of a method that Python tries to call it like one when you invoke it like one. If it quacks like a duck, in other words... That this call doesn't succeed is neither here nor there, in my opinion. But perhaps a proper response to "But Doctor! When I don't accept any arguments in a function defined in a class, I get confused about whether it's really a method or not!" is simply "Don't do that." :-)
what constitutes a member of a class? What constitutes a method?
It seems that an acceptable answer to the question What is a method? is A method is a function that's a member of a class. I disagree with this. class Foo(object): pass def func(): pass Foo.func = func f = Foo() print "fine so far" try: f.func() except TypeError: print "whoops! func must not be a method after all" Is func a member of Foo? Is func a method of Foo? I am well aware that this would work if func had a self argument. That's obvious. I'm interested in if it's a member of foo and in if it's a method as presented.
[ "You're just testing it wrong:\n>>> class Foo(object): pass\n... \n>>> def func(self): pass\n... \n>>> Foo.func = func\n>>> f = Foo()\n>>> f.func()\n>>> \n\nYou error of forgetting to have in the def the self argument has absolutely nothing to do with f.func \"not being a method\", of course. The peculiar conceit ...
[ 7, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003791651_python.txt
Q: Output a python script to text file I'm using a script that someone else wrote in python. It's executed from the command line with 3 arguments. example: "python script.py 1111 2222 3333" It does it's thing and works perfectly. The results are NOT saved though, and I would really like to pipe the output to a text file. Can I simply use similar dos commands to accomplish this? ie "...333 > output.txt" I don't really want to post the script here if possible since it's not really my work. A: Redirection works fine both in unix-y shells and in Windows' cmd.exe (which I suspect is what you're calling "the DOS window"... unless you're managing to run Python on Windows '95 or something!-). $ python script.py 1111 2222 3333 >output.txt where the $ is not something you type, but rather stands for "whatever prompt your shell / command window is giving you". Just to be totally unambiguous, what you do type at said prompt to get redirection is just: python script.py 1111 2222 3333 >output.txt just like what you type now (without redirection) is python script.py 1111 2222 3333 A: f = open('/path/to/file','w') f.write(string, '\n') # ... etc. Should be simple enough to add something like that to the script, just in case you'd rather not have to use the shell to pipe output each time. A: yes, if you are in a typical unixy shell, that will work exactly as you hope. If you want to modify the script to write to a file instead of to the stdout, you can read about how to use file() A: That seems to work fine for me in the DOS shell.
Output a python script to text file
I'm using a script that someone else wrote in python. It's executed from the command line with 3 arguments. example: "python script.py 1111 2222 3333" It does it's thing and works perfectly. The results are NOT saved though, and I would really like to pipe the output to a text file. Can I simply use similar dos commands to accomplish this? ie "...333 > output.txt" I don't really want to post the script here if possible since it's not really my work.
[ "Redirection works fine both in unix-y shells and in Windows' cmd.exe (which I suspect is what you're calling \"the DOS window\"... unless you're managing to run Python on Windows '95 or something!-).\n$ python script.py 1111 2222 3333 >output.txt\n\nwhere the $ is not something you type, but rather stands for \"wh...
[ 10, 6, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003791905_python.txt
Q: How do you stream data into the STDIN of a program from different local/remote processes in Python? Standard streams are associated with a program. So, suppose there is a program already running in some way (I don't care how or in what way). The goal is to create pipes to the STDIN of the program from different processes (or programs) that run either locally or remotely and stream data into it asynchronously. Available information is (1) the host address and (2) the pid of the program only. How does one implement both cases in Python in this case? Edit: I should have mentioned this presupposition. The intended operating system is Linux with a (fairly) recent kernel. A: This isn't portable, but on many Linux systems, you can write to /proc/$PID/fd/0 I think this may be one of a very limited number of potentially complicated options if you don't have any other control over the remote process. A: In most platforms (i.e., operating systems), an existing process's existing file descriptors are inviolate -- the operating system, striving to guarantee process integrity, will be designed to not allow a separate, unrelated process to alter those file descriptors. Nevertheless, if you do specify a very specific and well-identified platform (ideally including the exact version and release of the operating system in question, since security does tend to get tightened in successive releases compared with preceding ones), it's quite possible that there will be available tricks for your purposes. For example, you may be able to exploit some of the hooks which the operating system intends to be used for "remote debuggers" attaching themselves to existing processes -- if, that is, your very specific OS does offer such hooks (not all do!). But, if you want a cross-platform solution, no way. So, I recommend you edit your question, and in particular replace one of the tags with the name of the "one and only" OS you really need to support (in the Q's edited text, please be as specific as possible about the exact versions and releases you absolutely do need to support -- Python has very little indeed to do with the issue, as you need to operate at specific-OS levels, so there's no real need to similarly pinpoint the Python version).
How do you stream data into the STDIN of a program from different local/remote processes in Python?
Standard streams are associated with a program. So, suppose there is a program already running in some way (I don't care how or in what way). The goal is to create pipes to the STDIN of the program from different processes (or programs) that run either locally or remotely and stream data into it asynchronously. Available information is (1) the host address and (2) the pid of the program only. How does one implement both cases in Python in this case? Edit: I should have mentioned this presupposition. The intended operating system is Linux with a (fairly) recent kernel.
[ "This isn't portable, but on many Linux systems, you can write to\n/proc/$PID/fd/0\n\nI think this may be one of a very limited number of potentially complicated options if you don't have any other control over the remote process.\n", "In most platforms (i.e., operating systems), an existing process's existing fi...
[ 2, 1 ]
[]
[]
[ "ipc", "process", "python", "stdin", "stdout" ]
stackoverflow_0003792054_ipc_process_python_stdin_stdout.txt
Q: Storing dynamic form in a model I want to build a system using Django that will allow users to build forms, store them and have their customers use them. I know how I can go about creating the forms dynamically but I'm looking for a good way to still use the form classes and handle many different user's dynamic forms in an elegant way. I'm thinking of storing the form field information as a dictionary in the db. Is there any way in django to re-interpret this dictionary back into a form object? Or do I have to write a routine that will simply interpret and build out a form in html myself? If someone knows where to point me to the info I'd really appreciate it. A: This is a Python question more than a Django question, whence my tag edit. To reproduce the equivalent of, say: class MyForm(forms.Form): foo = forms.CharField(max_length=100) you need something like: f = type(forms.Form)('MyForm', forms.Form, d) where d is a dictionary like: d = { 'foo': forms.CharField(max_length=100) } Of course, in the end the form class will be bound to name f (you can use setattr to bind it to qualified name something.MyForm for an appropriate something, but please don't even dream of binding it to a bare name that's dynamically variables -- it would also be a nightmare to use such a barename!). So, to recreate the form class object at runtime, you need to preserve: its name MyForm a dict with the field names as keys and the field objects as values and to make point 2 work, you similarly need to preserve for each field (besides its name) the type name (so you can recover the type with a getattr from forms) and its named parameters (as a dict), so you can basically do d[fieldname] = getattr(forms, fieldtypename)(**fieldparameters) based on strings fieldname and fieldtypename and dict fieldparameters, for each field, as you rebuild dictionary d (i.e., prepare to satisfy step 2 of the above short list;-).
Storing dynamic form in a model
I want to build a system using Django that will allow users to build forms, store them and have their customers use them. I know how I can go about creating the forms dynamically but I'm looking for a good way to still use the form classes and handle many different user's dynamic forms in an elegant way. I'm thinking of storing the form field information as a dictionary in the db. Is there any way in django to re-interpret this dictionary back into a form object? Or do I have to write a routine that will simply interpret and build out a form in html myself? If someone knows where to point me to the info I'd really appreciate it.
[ "This is a Python question more than a Django question, whence my tag edit.\nTo reproduce the equivalent of, say:\nclass MyForm(forms.Form):\n foo = forms.CharField(max_length=100)\n\nyou need something like:\nf = type(forms.Form)('MyForm', forms.Form, d)\n\nwhere d is a dictionary like:\nd = { 'foo': forms.Char...
[ 3 ]
[]
[]
[ "django_forms", "python" ]
stackoverflow_0003792083_django_forms_python.txt
Q: Will reloading supervisord cause the process under its to stop? I try to figure out when I used reload command to supervisord. Will it stop the processing currently executing under it? I used below steps: mlzboy@mlzboy-mac:~/my/ide/test$ pstree -p|grep super |-supervisord(6763) mlzboy@mlzboy-mac:~/my/ide/test$ supervisorctl daemon STARTING supervisor> reload Really restart the remote supervisord process y/N? y Restarted supervisord supervisor> exit mlzboy@mlzboy-mac:~/my/ide/test$ pstree -p|grep super |-supervisord(6763) I found that the process id is not changed. So does it prove reload will not stop the processing under supervisor control? A: It doesn't kill the supervisord process, it just stops all processes, reload the configuration file, and restart processes again. If you just want to apply the new configurations use reread command. It'd just reload the configuration without stopping, and respawning processes. And running update will restart the processes (groups) that have changed.
Will reloading supervisord cause the process under its to stop?
I try to figure out when I used reload command to supervisord. Will it stop the processing currently executing under it? I used below steps: mlzboy@mlzboy-mac:~/my/ide/test$ pstree -p|grep super |-supervisord(6763) mlzboy@mlzboy-mac:~/my/ide/test$ supervisorctl daemon STARTING supervisor> reload Really restart the remote supervisord process y/N? y Restarted supervisord supervisor> exit mlzboy@mlzboy-mac:~/my/ide/test$ pstree -p|grep super |-supervisord(6763) I found that the process id is not changed. So does it prove reload will not stop the processing under supervisor control?
[ "It doesn't kill the supervisord process, it just stops all processes, reload the configuration file, and restart processes again.\nIf you just want to apply the new configurations use reread command. It'd just reload the configuration without stopping, and respawning processes.\nAnd running update will restart the...
[ 50 ]
[]
[]
[ "python", "reload", "supervisord" ]
stackoverflow_0003792081_python_reload_supervisord.txt
Q: Which python version needs from __future__ import with_statement? Using python 2.6.5, I can use the with statement without calling from __future__ import with_statement. How can I tell which version of Python supports with without specifically importing it from __future__? A: __future__ features are self-documenting. Try this: >>> from __future__ import with_statement >>> with_statement.getOptionalRelease() (2, 5, 0, 'alpha', 1) >>> with_statement.getMandatoryRelease() (2, 6, 0, 'alpha', 0) These respectively indicate the first release supporting from __future__ import with_statement and the first release to support it without using from __future__. Also, read this: >>> import __future__ >>> help(__future__) A: You only need it in Python 2.5. Older versions (<= 2.4) don't support it and newer versions (>= 2.6) have it enabled by default. So if you want to support Python >= 2.5, you can simply put the from __future__ import with_statement at the beginning. For newer versions, it will simply be ignored. A: From the doc: New in version 2.5.
Which python version needs from __future__ import with_statement?
Using python 2.6.5, I can use the with statement without calling from __future__ import with_statement. How can I tell which version of Python supports with without specifically importing it from __future__?
[ "__future__ features are self-documenting. Try this:\n>>> from __future__ import with_statement\n>>> with_statement.getOptionalRelease()\n(2, 5, 0, 'alpha', 1)\n>>> with_statement.getMandatoryRelease()\n(2, 6, 0, 'alpha', 0)\n\nThese respectively indicate the first release supporting from __future__ import with_st...
[ 51, 17, 2 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0003791903_python_python_import.txt
Q: python socket.PF_PACKET I am trying to send out an ARP request with python, working with dpkt, and I found some sample code that uses: socket.socket(socket.PF_PACKET, socket.SOCK_RAW) I understand that you need to use raw sockets to send this, but it says that socket.PF_PACKET doesn't exist. And there is nothing in the python docs about it that I have seen. So, where would this person have gotten PF_PACKET from, what would it do, and how can I get it? A: Edited my reply: PF_PACKET was introduced in Linux versions 2.0 and above. Python only wraps the socket interface of the operating system. AaronMcSmooth comment verifies that it is available on Linux. It is not available on mac though. Also it looks like AF_PACKET may get preferred in 3.2 http://bugs.python.org/issue8270
python socket.PF_PACKET
I am trying to send out an ARP request with python, working with dpkt, and I found some sample code that uses: socket.socket(socket.PF_PACKET, socket.SOCK_RAW) I understand that you need to use raw sockets to send this, but it says that socket.PF_PACKET doesn't exist. And there is nothing in the python docs about it that I have seen. So, where would this person have gotten PF_PACKET from, what would it do, and how can I get it?
[ "Edited my reply:\nPF_PACKET was introduced in Linux versions 2.0 and above. Python only wraps the socket interface of the operating system. AaronMcSmooth comment verifies that it is available on Linux. It is not available on mac though.\nAlso it looks like AF_PACKET may get preferred in 3.2 \n\nhttp://bugs.python....
[ 2 ]
[]
[]
[ "networking", "python", "raw_sockets" ]
stackoverflow_0003792407_networking_python_raw_sockets.txt
Q: How to require implementation of method in Python? I'm using duck typing in Python. def flagItem(object_to_flag, account_flagging, flag_type, is_flagged): if flag_type == Flags.OFFENSIVE: object_to_flag.is_offensive=is_flagged elif flag_type == Flags.SPAM: object_to_flag.is_spam=is_flagged object_to_flag.is_active=(not is_flagged) object_to_flag.cleanup() return object_to_flag.put() Where different objects are passed in as object_to_flag, all of which have is_active, is_spam, is_offensive attributes. They also happen to have a cleanup() method. The objects I'm passing in all have the same base class (they're db objects in Google App Engine): class User(db.Model): ... is_active = db.BooleanProperty(default = True) is_spam = db.BooleanProperty(default=False) is_offensive = db.BooleanProperty(default=False) def cleanup(): pass class Post(db.Model): ... is_active = db.BooleanProperty(default = True) is_spam = db.BooleanProperty(default=False) is_offensive = db.BooleanProperty(default=False) def cleanup(): pass How can I make the cleanup() method abstract so that I can have the same parent class for all these objects that requires the children provide implementation? Perhaps more importantly, is this 'pythonic'? Should I go this route, or should I just rely on the duck typing? My background is in Java and I'm trying to learn the Python way of doing things. Thanks! A: Use the abc module. Specifically, set your base class's metaclass to ABCMeta and use the @abstractmethod decorator on your cleanup method. The debate on whether this is "pythonic" is split. PEP 3119, which describes the standard, lists some of the pros and cons (but obviously favors ABCs). It made it into the standard library, which is a pretty good indication that many people consider it useful in some circumstances. In your case, I think it is appropriate. A: If you want to ensure that the cleanup method is implemented, you can wrap with the @abc.virtualmethod decorator. This will cause an error on instantiation of any object that hasn't overridden the virtualmethod. This also requires that you make abc.ABCMeta your class's __metaclass__. See the abc module for more info and some examples. This is not commonly done: usually there will just be docs to the effect that implementers must override the given method. However this may be more due to the newness of the abc module (new in Python 2.6) than a perceived unpythonicness of this approach. A: Why not have the cleanup method just raise an NotImplementedError when it is called? If they want your children classes to work they'll have to put some sort of implementation in place. A: Since you don't have abc available, you can do this with a simple metaclass class Abstract(type(db.Model)): def __new__(metacls, clsname, bases, clsdict): for methodname in clsdict.pop('_abstract_methods_', []): try: if not callable(clsdict[methodname]): raise TypeError("{0} must implement {1}".format(clcname, methodname)) except KeyError: raise TypeError("{0} must implement {1}".format(clcname, methodname)) return super(Abstract, metacls).__new__(metacls, clsname, bases, clsdict) class RequireCleanup(db.Model): __metaclass__ = Abstract _abstract_methods_ = ['cleanup'] def cleanup(self): pass the expression type(db.Model) resolves to whatever metaclass gets used for db.Model so we don't step on google's code. Also, we pop _abstract_methods_ out of the class dictionary before it get's passed to google's __new__ method so that we don't break anything. If db.Model already has an attribute with that name, then you will need to change it to something else. A: Although I've never used it personally, I've seen many references to Zope interfaces. This may be overkill for your task, but it may give you some direction. And it may feel comfortable to someone with a Java background.
How to require implementation of method in Python?
I'm using duck typing in Python. def flagItem(object_to_flag, account_flagging, flag_type, is_flagged): if flag_type == Flags.OFFENSIVE: object_to_flag.is_offensive=is_flagged elif flag_type == Flags.SPAM: object_to_flag.is_spam=is_flagged object_to_flag.is_active=(not is_flagged) object_to_flag.cleanup() return object_to_flag.put() Where different objects are passed in as object_to_flag, all of which have is_active, is_spam, is_offensive attributes. They also happen to have a cleanup() method. The objects I'm passing in all have the same base class (they're db objects in Google App Engine): class User(db.Model): ... is_active = db.BooleanProperty(default = True) is_spam = db.BooleanProperty(default=False) is_offensive = db.BooleanProperty(default=False) def cleanup(): pass class Post(db.Model): ... is_active = db.BooleanProperty(default = True) is_spam = db.BooleanProperty(default=False) is_offensive = db.BooleanProperty(default=False) def cleanup(): pass How can I make the cleanup() method abstract so that I can have the same parent class for all these objects that requires the children provide implementation? Perhaps more importantly, is this 'pythonic'? Should I go this route, or should I just rely on the duck typing? My background is in Java and I'm trying to learn the Python way of doing things. Thanks!
[ "Use the abc module. Specifically, set your base class's metaclass to ABCMeta and use the @abstractmethod decorator on your cleanup method.\nThe debate on whether this is \"pythonic\" is split. PEP 3119, which describes the standard, lists some of the pros and cons (but obviously favors ABCs). It made it into the s...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "abstract_methods", "duck_typing", "python" ]
stackoverflow_0003783596_abstract_methods_duck_typing_python.txt
Q: How to Build a 32-bit Python Module Distribution w/ Setup.py on x86_64 Host I need to compile a 32-bit distribution of PyEphem. It does not seem like this should be difficult, however, I'm running into some compiler issues. $ CFLAGS=-m32 python setup.py bdist -p i386 running bdist running bdist_dumb running build running build_py running build_ext building 'ephem._libastro' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -m32 -fPIC -Ilibastro-3.7.3 -I/usr/include/python2.6 -c extensions/_libastro.c -o build/temp.linux-x86_64-2.6/extensions/_libastro.o In file included from /usr/include/python2.6/Python.h:58, from extensions/_libastro.c:3: /usr/include/python2.6/pyport.h:685:2: error: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." error: command 'gcc' failed with exit status 1 The build system is running Ubuntu 10.04. Are the python header files tied to the architecture of the local hosts? Update: I found some interesting info about Python cross-compiling. A: Have you installed a 32-bit python on your machine? I think that it should be OK if you run it from 32-bit python, and make sure you're linking to the right python.h. I've never tried to cross-compile on Linux, but I have compiled against different pythons installed side by side on 64-bit Windows. Then of course, there's the nuclear option of installing a 32-bit VM and compiling from there.
How to Build a 32-bit Python Module Distribution w/ Setup.py on x86_64 Host
I need to compile a 32-bit distribution of PyEphem. It does not seem like this should be difficult, however, I'm running into some compiler issues. $ CFLAGS=-m32 python setup.py bdist -p i386 running bdist running bdist_dumb running build running build_py running build_ext building 'ephem._libastro' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -m32 -fPIC -Ilibastro-3.7.3 -I/usr/include/python2.6 -c extensions/_libastro.c -o build/temp.linux-x86_64-2.6/extensions/_libastro.o In file included from /usr/include/python2.6/Python.h:58, from extensions/_libastro.c:3: /usr/include/python2.6/pyport.h:685:2: error: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." error: command 'gcc' failed with exit status 1 The build system is running Ubuntu 10.04. Are the python header files tied to the architecture of the local hosts? Update: I found some interesting info about Python cross-compiling.
[ "Have you installed a 32-bit python on your machine? I think that it should be OK if you run it from 32-bit python, and make sure you're linking to the right python.h.\nI've never tried to cross-compile on Linux, but I have compiled against different pythons installed side by side on 64-bit Windows.\nThen of course...
[ 1 ]
[]
[]
[ "cross_compiling", "gcc", "python", "setup.py" ]
stackoverflow_0003792285_cross_compiling_gcc_python_setup.py.txt
Q: How to Install rpy2 on Mac OS X I am trying, so far unsuccessfully, at installing the rpy2 for python on my Mac OSX. I have tried Macports and DarwinPorts but have had no luck with import rpy2 within the python shell environment. I don't know much about programming in Mac and I am a wiz at installing modules on a Windoze based system, but for the life of me cannot do a simple port on my Mac at home. What I am after, if someone would be so kind, are "dumbed down" instructions for a successful install of rpy2 for Mac OSX Snow Leopard. Hopefully someone here has done this successfully and can outline the process they took? At least that is what I am hoping. Many thanks in advance! A: easy_install and rpy2 work fine together (just did it) but you need to have easy_install in sync with your specific python version. This comes down to controlling your $PATH and $PYTHONPATH environment variables so that the first Python directory that appears is the version you want and also has the easy_install version you want. Do not try to solve this by taking out the factory installed version of Python. You set your path variables in your home directory. If you are using the default bash shell, check .bash_profile for $ echo $PYTHONPATH /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ which will tell you where and in what order installed packages are searched for and $ echo $PATH /opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/bin: Rather than giving a recipe for how to set these if needed, I encourage you to consult the usual sources because a little knowledge is dangerous and rendering the shell inoperative by reasonable, but wrong, guesses is a real danger. A: First check that you installed rpy2 successfully. Look in /opt/local/var/macports/software for anything with rpy2 in the title. It maybe called py26-rpy depending on the version of Python you are running. If you see that then you just need to use the right path to Python .. check the default location of Python like this: which python This will return the location of the first Python found and will probably say /usr/bin/python but you should use the version that rpy2 was compiled against.. which lives in /opt/local/bin. Try: /opt/local/bin/python2.6 then: import rpy2
How to Install rpy2 on Mac OS X
I am trying, so far unsuccessfully, at installing the rpy2 for python on my Mac OSX. I have tried Macports and DarwinPorts but have had no luck with import rpy2 within the python shell environment. I don't know much about programming in Mac and I am a wiz at installing modules on a Windoze based system, but for the life of me cannot do a simple port on my Mac at home. What I am after, if someone would be so kind, are "dumbed down" instructions for a successful install of rpy2 for Mac OSX Snow Leopard. Hopefully someone here has done this successfully and can outline the process they took? At least that is what I am hoping. Many thanks in advance!
[ "easy_install and rpy2 work fine together (just did it) but you need to have easy_install in sync with your specific python version. This comes down to controlling your $PATH and $PYTHONPATH environment variables so that the first Python directory that appears is the version you want and also has the easy_install v...
[ 2, 1 ]
[]
[]
[ "macos", "osx_snow_leopard", "python", "rpy2" ]
stackoverflow_0003687939_macos_osx_snow_leopard_python_rpy2.txt
Q: Python regular expression slicing I am trying to get a web page using the following sample code: from urllib import urlopen print urlopen("http://www.php.net/manual/en/function.gettext.php").read() Now I can get the whole web page in a variable. I wanna get a part of the page containing something like this <div class="methodsynopsis dc-description"> <span class="type">string</span><span class="methodname"><b>gettext</b></span> ( <span class="methodparam"><span class="type">string</span> <tt class="parameter">$message</tt></span> )</div> So that i can generate a file to implement in another application. I wanna be able to extract the words "string", "gettext" and "$message". A: Why don't you try using BeautifulSoup http://www.crummy.com/software/BeautifulSoup/ Example code : from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(htmldoc) allSpans = soup.findAll('span', class="type") for element in allSpans: .... A: When extracting information from HTML, it isn't recommended to just hack some regexes together. The right way to do it is to use a proper HTML parsing module. Python has several good modules for this purpose - in particular I recommend BeautifulSoup. Don't be put off by the name - it's a serious module used by a lot of people with great success. The documentation page has a lot of examples that should help you get started with your particular needs.
Python regular expression slicing
I am trying to get a web page using the following sample code: from urllib import urlopen print urlopen("http://www.php.net/manual/en/function.gettext.php").read() Now I can get the whole web page in a variable. I wanna get a part of the page containing something like this <div class="methodsynopsis dc-description"> <span class="type">string</span><span class="methodname"><b>gettext</b></span> ( <span class="methodparam"><span class="type">string</span> <tt class="parameter">$message</tt></span> )</div> So that i can generate a file to implement in another application. I wanna be able to extract the words "string", "gettext" and "$message".
[ "Why don't you try using BeautifulSoup\n\nhttp://www.crummy.com/software/BeautifulSoup/\n\nExample code :\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(htmldoc)\nallSpans = soup.findAll('span', class=\"type\")\nfor element in allSpans:\n ....\n\n", "When extracting information from HTML, it is...
[ 2, 1 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0003792645_html_python_regex.txt
Q: What to do if collections.defaultdict is not available? Solaris python 2.4.3: from collections import defaultdict does not exist.. Please advise what could be an alternative to use multi-level dictionaries: dictOut['1']['exec'] = 'shell1.sh' dictOut['1']['onfailure'] = 'continue' ... dictOut['2']['exec'] = 'shell2.sh' dictOut['2']['onfailure'] = stop' many thanks applom A: setdefault? dictOut.setdefault('1', {})['exec'] = 'shell1.sh' A: Answered with looks-like-it-works code within the last 24 hours (found by searching for "defaultdict", choose "newest" or "active" order) A: As an alternative to setdefault, if you want extra level of dictionary goodness, try class MultiDict(dict): def __getitem__(self, item): if item not in self.iterkeys(): self[item] = MultiDict() return super(MultiDict, self).__getitem__(item) A: I just wonder why not to use single level dict with tuple as hash key?
What to do if collections.defaultdict is not available?
Solaris python 2.4.3: from collections import defaultdict does not exist.. Please advise what could be an alternative to use multi-level dictionaries: dictOut['1']['exec'] = 'shell1.sh' dictOut['1']['onfailure'] = 'continue' ... dictOut['2']['exec'] = 'shell2.sh' dictOut['2']['onfailure'] = stop' many thanks applom
[ "setdefault?\ndictOut.setdefault('1', {})['exec'] = 'shell1.sh'\n\n", "Answered with looks-like-it-works code within the last 24 hours (found by searching for \"defaultdict\", choose \"newest\" or \"active\" order)\n", "As an alternative to setdefault, if you want extra level of dictionary goodness, try\nclass ...
[ 2, 2, 2, 0 ]
[]
[]
[ "collections", "python" ]
stackoverflow_0003792258_collections_python.txt
Q: Accessing names defined in a package's `__init__.py` when running setuptools tests I've taken to putting module code directly in a packages __init__.py, even for simple packages where this ends up being the only file. So I have a bunch of packages that look like this (though they're not all called pants:) + pants/ \-- __init__.py \-- setup.py \-- README.txt \--+ test/ \-- __init__.py I started doing this because it allows me to put the code in a separate (and, critically, separately versionable) directory, and have it work in the same way as it would if the package were located in a single module.py. I keep these in my dev python lib directory, which I have added into $PYTHONPATH when working on such things. Each package is a separate git repo. edit... Compared to the typical Python package layout, as exemplified in Radomir's answer, this setup saves me from having to add each package's directory into my PYTHONPATH. .../edit This has worked out pretty well, but I've hit upon this (somewhat obscure) issue: When running tests from within the package directory, the package itself, i.e. code in __init__.py, is not guaranteed to be on the sys.path. This is not a problem under my typical environment, but if someone downloads pants-4.6.tgz and extracts a tarball of the source distribution, cds into the directory, and runs python setup.py test, the package pants itself won't normally be in their sys.path. I find this strange, because I would expect setuptools to run the tests from a parent directory of the package under test. However, for whatever reason, it doesn't do that, I guess because normally you wouldn't package things this way. Relative imports don't work because test is a top-level package, having been found as a subdirectory of the current-directory component of sys.path. I'd like to avoid having to move the code into a separate file and importing its public names into __init__.py. Mostly because that seems like pointless clutter for a simple module. I could explicitly add the parent directory to sys.path from within setup.py, but would prefer not to. For one thing, this could, at least in theory, fail, e.g. if somebody decides to run the test from the root of their filesystem (presumably a Windows drive). But mostly it just feels jerry-rigged. Is there a better way? Is it considered particularly bad form to put code in __init__.py? A: I think the standard way to package python programs would be more like this: \-- setup.py \-- README.txt \--+ pants/ \-- __init__.py \-- __main__.py ... \--+ tests/ \-- __init__.py ... \--+ some_dependency_you_need/ ... Then you avoid the problem.
Accessing names defined in a package's `__init__.py` when running setuptools tests
I've taken to putting module code directly in a packages __init__.py, even for simple packages where this ends up being the only file. So I have a bunch of packages that look like this (though they're not all called pants:) + pants/ \-- __init__.py \-- setup.py \-- README.txt \--+ test/ \-- __init__.py I started doing this because it allows me to put the code in a separate (and, critically, separately versionable) directory, and have it work in the same way as it would if the package were located in a single module.py. I keep these in my dev python lib directory, which I have added into $PYTHONPATH when working on such things. Each package is a separate git repo. edit... Compared to the typical Python package layout, as exemplified in Radomir's answer, this setup saves me from having to add each package's directory into my PYTHONPATH. .../edit This has worked out pretty well, but I've hit upon this (somewhat obscure) issue: When running tests from within the package directory, the package itself, i.e. code in __init__.py, is not guaranteed to be on the sys.path. This is not a problem under my typical environment, but if someone downloads pants-4.6.tgz and extracts a tarball of the source distribution, cds into the directory, and runs python setup.py test, the package pants itself won't normally be in their sys.path. I find this strange, because I would expect setuptools to run the tests from a parent directory of the package under test. However, for whatever reason, it doesn't do that, I guess because normally you wouldn't package things this way. Relative imports don't work because test is a top-level package, having been found as a subdirectory of the current-directory component of sys.path. I'd like to avoid having to move the code into a separate file and importing its public names into __init__.py. Mostly because that seems like pointless clutter for a simple module. I could explicitly add the parent directory to sys.path from within setup.py, but would prefer not to. For one thing, this could, at least in theory, fail, e.g. if somebody decides to run the test from the root of their filesystem (presumably a Windows drive). But mostly it just feels jerry-rigged. Is there a better way? Is it considered particularly bad form to put code in __init__.py?
[ "I think the standard way to package python programs would be more like this:\n\\-- setup.py\n\\-- README.txt\n\\--+ pants/\n \\-- __init__.py\n \\-- __main__.py\n ...\n\\--+ tests/\n \\-- __init__.py\n ...\n\\--+ some_dependency_you_need/\n ...\n\nThen you avoid the problem.\n" ]
[ 1 ]
[]
[]
[ "module", "package", "python", "setuptools", "testing" ]
stackoverflow_0003792813_module_package_python_setuptools_testing.txt
Q: wxPython - wxHtmlWindow, can the scrollbar be kept at the veyr bottom at all times? I am working on a chatroom client and am using an HTML window to process things like images and html tags and formatting. I am having trouble finding out how to make the scrollbar stay at the bottom as messages are added to the window (every message sends the bar to the top) would anyone know how I would go about doing this? A: After you add a new message, you can call Scroll on your htmlWindow to set its scrollBar position to the end. yourHtmlWindow.Scroll(-1, self.GetClientSize()[0]) If you want your scrollBar to stay at the bottom when the window is resized then you will need to Bind to wx.EVT_SIZE so that you can call Scroll on resize. def onSize(self, event): event.Skip() wx.CallAfter(yourHtmlWindow.Scroll, -1, self.GetClientSize()[0])
wxPython - wxHtmlWindow, can the scrollbar be kept at the veyr bottom at all times?
I am working on a chatroom client and am using an HTML window to process things like images and html tags and formatting. I am having trouble finding out how to make the scrollbar stay at the bottom as messages are added to the window (every message sends the bar to the top) would anyone know how I would go about doing this?
[ "After you add a new message, you can call Scroll on your htmlWindow to set its scrollBar position to the end.\nyourHtmlWindow.Scroll(-1, self.GetClientSize()[0])\n\nIf you want your scrollBar to stay at the bottom when the window is resized then you will need to Bind to wx.EVT_SIZE so that you can call Scroll on ...
[ 1 ]
[]
[]
[ "python", "wxhtmlwindow", "wxpython" ]
stackoverflow_0003791713_python_wxhtmlwindow_wxpython.txt
Q: How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? Yesterday, I asked this question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style. Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: static void Main(string[] args) { var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q; } private static IEnumerable GetRandomNumbers(int max) { Random r = new Random(); while (true) { yield return r.Next(max); } } Can you translate my LINQ to Ruby? Python? Any other functional programming language? Note: Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N. I know I'm being picky, but I'd really like to see some elegant solutions to this problem. Thanks! Edit: Why all the downvotes? Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place. Apology: I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk. A: >>> import random >>> print random.sample(xrange(100), 5) [61, 54, 91, 72, 85] This should yield 5 unique values in the range 0 — 99. The xrange object generates values as requested so no memory is used for values that aren't sampled. A: In Ruby: a = (0..100).entries.sort_by {rand}.slice! 0, 5 Update: Here is a slightly different way: a = (0...100).entries.sort_by{rand}[0...5] EDIT: and In Ruby 1.9 you can do this: Array(0..100).sample(5) A: Hmm... How about (Python): s = set() while len(s) <= N: s.update((random.random(),)) A: I will forgo the simplest solutions using the 'random' module since I take it that's not really what you are after. Here's what I think you are looking for in Python: >>> import random >>> >>> def getUniqueRandomNumbers(num, highest): ... seen = set() ... while len(seen) < num: ... i = random.randrange(0, highest) ... if i not in seen: ... seen.add(i) ... yield i ... >>> To show you how it works: >>> list(getUniqueRandomNumbers(10, 100)) [81, 57, 98, 47, 93, 31, 29, 24, 97, 10] A: Here's another Ruby solution: a = (1..5).collect { rand(100) } a & a I think, with your LINQ statement, the Distinct will remove duplicates after 5 have already been taken, so you aren't guaranteed to get 5 back. Someone can correct me if I'm wrong, though. A: EDIT : Ok, just for fun, a shorter and faster one (and still using iterators). def getRandomNumbers(max, size) : pool = set() return ((lambda x : pool.add(x) or x)(random.randrange(max)) for x in xrange(size) if len(a) < size) print [x for x in gen(100, 5)] [0, 10, 19, 51, 18] Yeah, I know, one-liners should be left to perl lovers, but I think this one is quite powerful isn't it ? Old message here : My god, how complicated is all that ! Let's be pythonic : import random def getRandomNumber(max, size, min=0) : # using () and xrange = using iterators return (random.randrange(min, max) for x in xrange(size)) print set(getRandomNumber(100, 5)) # set() removes duplicates set([88, 99, 29, 70, 23]) Enjoy EDIT : As commentators noticed, this is an exact translation of the question's code. To avoid the problem we got by removing duplicates after generating the list, resulting in too little data, you can choose another way : def getRandomNumbers(max, size) : pool = [] while len(pool) < size : tmp = random.randrange(max) if tmp not in pool : yield pool.append(tmp) or tmp print [x for x in getRandomNumbers(5, 5)] [2, 1, 0, 3, 4] A: In Ruby 1.9: Array(0..100).sample(5) A: Python with Numeric Python: from numpy import * a = random.random_integers(0, 100, 5) b = unique(a) Voilà! Sure you could do something similar in a functional programming style but... why? A: import random def makeRand(n): rand = random.Random() while 1: yield rand.randint(0,n) yield rand.randint(0,n) gen = makeRand(100) terms = [ gen.next() for n in range(5) ] print "raw list" print terms print "de-duped list" print list(set(terms)) # produces output similar to this # # raw list # [22, 11, 35, 55, 1] # de-duped list # [35, 11, 1, 22, 55] A: Well, first you rewrite LINQ in Python. Then your solution is a one-liner :) from random import randrange def Distinct(items): set = {} for i in items: if not set.has_key(i): yield i set[i] = 1 def Take(num, items): for i in items: if num > 0: yield i num = num - 1 else: break def ToArray(items): return [i for i in items] def GetRandomNumbers(max): while 1: yield randrange(max) print ToArray(Take(5, Distinct(GetRandomNumbers(100)))) If you put all the simple methods above into a module called LINQ.py, you can impress your friends. (Disclaimer: of course, this is not actually rewriting LINQ in Python. People have the misconception that LINQ is just a bunch of trivial extension methods and some new syntax. The really advanced part of LINQ, however, is automatic SQL generation so that when you're querying a database, it's the database that implements Distinct() rather than the client side.) A: Here's a transliteration from your solution to Python. First, a generator that creates Random numbers. This isn't very Pythonic, but it's a good match with your sample code. >>> import random >>> def getRandomNumbers( max ): ... while True: ... yield random.randrange(0,max) Here's a client loop that collects a set of 5 distinct values. This is -- again -- not the most Pythonic implementation. >>> distinctSet= set() >>> for r in getRandomNumbers( 100 ): ... distinctSet.add( r ) ... if len(distinctSet) == 5: ... break ... >>> distinctSet set([81, 66, 28, 53, 46]) It's not clear why you want to use a generator for random numbers -- that's one of the few things that's so simple that a generator doesn't simplify it. A more Pythonic version might be something like: distinctSet= set() while len(distinctSet) != 5: distinctSet.add( random.randrange(0,100) ) If the requirements are to generate 5 values and find distinct among those 5, then something like distinctSet= set( [random.randrange(0,100) for i in range(5) ] ) A: Maybe this will suit your needs and look a bit more linqish: from numpy import random,unique def GetRandomNumbers(total=5): while True: yield unique(random.random(total*2))[:total] randomGenerator = GetRandomNumbers() myRandomNumbers = randomGenerator.next() A: Here's another python version, more closely matching the structure of your C# code. There isn't a builtin for giving distinct results, so I've added a function to do this. import itertools, random def distinct(seq): seen=set() for item in seq: if item not in seen: seen.add(item) yield item def getRandomNumbers(max): while 1: yield random.randint(0,max) for item in itertools.islice(distinct(getRandomNumbers(100)), 5): print item
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python?
Yesterday, I asked this question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style. Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ: static void Main(string[] args) { var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q; } private static IEnumerable GetRandomNumbers(int max) { Random r = new Random(); while (true) { yield return r.Next(max); } } Can you translate my LINQ to Ruby? Python? Any other functional programming language? Note: Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N. I know I'm being picky, but I'd really like to see some elegant solutions to this problem. Thanks! Edit: Why all the downvotes? Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place. Apology: I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.
[ ">>> import random\n>>> print random.sample(xrange(100), 5)\n[61, 54, 91, 72, 85]\n\nThis should yield 5 unique values in the range 0 — 99. The xrange object generates values as requested so no memory is used for values that aren't sampled.\n", "In Ruby:\na = (0..100).entries.sort_by {rand}.slice! 0, 5\n\nUpdate:...
[ 13, 5, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0 ]
[ "I can't really read your LINQ, but I think you're trying to get 5 random numbers up to 100 and then remove duplicates.\nHere's a solution for that:\ndef random(max)\n (rand * max).to_i\nend\n\n# Get 5 random numbers between 0 and 100\na = (1..5).inject([]){|acc,i| acc << random( 100)}\n# Remove Duplicates\na = ...
[ -1 ]
[ "functional_programming", "linq", "python", "ruby" ]
stackoverflow_0000122033_functional_programming_linq_python_ruby.txt
Q: How to install a Python Recipe File (.py)? I'm new to Python. I'm currently on Py3k (Win). I'm having trouble installing a .py file. Basically, i want to use the recipes provided at the bottom of this page. So i want to put them inside a .py and import them in any of my source codes. So i copied all the recipes into a recipes.py file and copied them to C:\Python3k\Lib\site-packages. Now, the import works fine, but when i try to call any function (eg. take) from it, i got a global name 'islice' is not defined...So i figured, i should add an itertools import to recipes.py I still get the same error? Do i need to change all instances to itertools.<funcname>? how can i make the import's global? Is this a new Py3k change? Is there something i missing? Thanks in advance, :) A: There are two closely-related issues. First, within recipes.py, you need access to all of itertools. At the very least, this means you need import itertools at the top. But in this case you would need to qualify all of the itertools functions as itertools.<funcname>, as you say. (You could also use import itertools as it and then it.<funcname>.) Second, you could do from itertools import islice, count, chain but you would need to put all of the needed functions in the list. Finally, the least recommended, but probably easiest, is to do from itertools import * This is dangerous because it pollutes your namespace with everything from itertools, which is considered bad and uncontrolled, but in this case probably isn't terrible. Second, you have a similar problem in all of your code that uses recipes.py; you'll need to qualify or explicitly import everything. So, either import recipes recipes.take(...) or from recipes import take take(...)
How to install a Python Recipe File (.py)?
I'm new to Python. I'm currently on Py3k (Win). I'm having trouble installing a .py file. Basically, i want to use the recipes provided at the bottom of this page. So i want to put them inside a .py and import them in any of my source codes. So i copied all the recipes into a recipes.py file and copied them to C:\Python3k\Lib\site-packages. Now, the import works fine, but when i try to call any function (eg. take) from it, i got a global name 'islice' is not defined...So i figured, i should add an itertools import to recipes.py I still get the same error? Do i need to change all instances to itertools.<funcname>? how can i make the import's global? Is this a new Py3k change? Is there something i missing? Thanks in advance, :)
[ "There are two closely-related issues.\nFirst, within recipes.py, you need access to all of itertools. \nAt the very least, this means you need \nimport itertools\n\nat the top. But in this case you would need to qualify all of the itertools functions as itertools.<funcname>, as you say. (You could also use import ...
[ 7 ]
[]
[]
[ "installation", "python", "python_3.x", "recipe" ]
stackoverflow_0003793123_installation_python_python_3.x_recipe.txt
Q: Among MATLAB and Python, which one is good for statistical analysis? Which one among the two languages is good for statistical analysis? What are the pros and cons, other than accessibility, for each? A: MATLAB Good for beginners Good for interactive sessions Python (with SciPy) Good for slightly experienced programmers Good for creating reusable applications Good for reading and exporting data files Free of cost If SciPy doesn't provide all the functionality out of the box, then you may have to go searching on the Internet. I am not an expert on geostatistics, but here is a mail with some starting pointers. http://mail.scipy.org/pipermail/scipy-user/2007-November/014434.html I also heard that Python + R is good, but I haven't tried it. EDIT: Add link to Python + R: http://rpy.sourceforge.net/ A: The SciPy and NumPy libraries for Python add in a ton of MatLab-equivalent functionality, to the point where it might very well have surpassed MatLab as a scientific-computing resource. As a language, I'd say Python is (in my opinion) far superior - function definition, imports, et cetera are all a lot nicer to work with than MatLab's more primitive equivalents. That said, there is a lot of pre-written MatLab code out there for analysis, given that it was such a mainstay for such a long time. A: I would pick Python because it can be a powerful as Matlab but is free. Also, you can distribute your applications for free and no licensing chains. Matlab is awesome and expensive (it had a great statistical package) and it will glow smoother than Python in the beginning, but not so in the long run. Now, if you really want the best solution then check out R, the statistical package which is de facto in the community. They even have a Python port for it. R is also free software. A: You should definitely check out Sage, it is a pre-integrated Python and many of the major maths/science oriented libraries and frameworks. From the website: Mission: Creating a viable free open source alternative to Magma, Maple, Mathematica and Matlab. A: SciPy, NumPy and Matplotlib.
Among MATLAB and Python, which one is good for statistical analysis?
Which one among the two languages is good for statistical analysis? What are the pros and cons, other than accessibility, for each?
[ "MATLAB\n\nGood for beginners\nGood for interactive sessions\n\nPython (with SciPy)\n\nGood for slightly experienced programmers\nGood for creating reusable applications\nGood for reading and exporting data files\nFree of cost\n\nIf SciPy doesn't provide all the functionality out of the box, then you may have to go...
[ 8, 6, 3, 3, 2 ]
[]
[]
[ "analysis", "matlab", "python", "statistics" ]
stackoverflow_0003792465_analysis_matlab_python_statistics.txt
Q: How to make a .exe for Python with good graphics? I have a Python application and I decided to do a .exe to execute it. This is the code that I use to do the .exe: # -*- coding: cp1252 -*- from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1}}, windows = [{'script': "SoundLog.py"}], zipfile = None, packages=[r"C:\Users\Public\SoundLog\Code\Código Python\SoundLog\Auxiliar", r"C:\Users\Public\SoundLog\Code\Código Python\SoundLog\Plugins"], ) But when I run my application with the .exe, the graphics are quite different. In the image bellow you can see the application running thought python at the left and running thought the .exe at the right. How can I make the .exe one be as good as the one that runs thought python? A: I assume you mean the visual style of the toolbar and buttons. You need to add a manifest file to the EXE file or as a separate file so that Windows applies the modern style of recent comctl32.dll versions. Check out Using Windows XP Visual Styles With Controls on Windows Forms on MSDN. Read the relevant part about creating the ".exe.manifest" file. A more py2exe-specific tutorial can be found over at the wxPython site. They explain how to use setup.py to include the necessary manifest file. A: The final setup that I mounted was this: # -*- coding: cp1252 -*- from distutils.core import setup import py2exe, sys, os from glob import glob sys.argv.append('py2exe') manifest = """ <?xml version='1.0' encoding='UTF-8' standalone='yes'?> <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level='asInvoker' uiAccess='false' /> </requestedPrivileges> </security> </trustInfo> <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC90.CRT' version='9.0.21022.8' processorArchitecture='*' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" /> </dependentAssembly> </dependency> </assembly> """ setup( ## data_files = data_files, options = {'py2exe': {'bundle_files': 1}}, windows = [{'script': "SoundLog.py", 'other_resources': [(24,1,manifest)]}], zipfile = None, packages=[r"C:\Users\Public\SoundLog\Code\Código Python\SoundLog\Auxiliar", r"C:\Users\Public\SoundLog\Code\Código Python\SoundLog\Plugins"], ) Thanks for the quick answers :) A: I found that I didn't need the manifest file when I used Python 2.6 on Windows 7. But I did need it when I used Python 2.5 on XP and Vista. If you use GUI2Exe, all you need to do is check a little checkbox to include it. See the following tutorials: http://www.blog.pythonlibrary.org/2010/07/31/a-py2exe-tutorial-build-a-binary-series/ http://www.blog.pythonlibrary.org/2010/08/31/another-gui2exe-tutorial-build-a-binary-series/ There's also a Python-related manifest for anything 2.6+ due to the switch in compilers on Windows (i.e. VS2008 vs ye olde VS2003). Robin Dunn seems to have fixed the latest build of wxPython so you don't need to include that annoyance, but if you're NOT using wx, then you'll probably run into this issue when you try to create a binary. The py2exe website and the wxPython wiki both talk about the issue and how to create the SxS manifest.
How to make a .exe for Python with good graphics?
I have a Python application and I decided to do a .exe to execute it. This is the code that I use to do the .exe: # -*- coding: cp1252 -*- from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1}}, windows = [{'script': "SoundLog.py"}], zipfile = None, packages=[r"C:\Users\Public\SoundLog\Code\Código Python\SoundLog\Auxiliar", r"C:\Users\Public\SoundLog\Code\Código Python\SoundLog\Plugins"], ) But when I run my application with the .exe, the graphics are quite different. In the image bellow you can see the application running thought python at the left and running thought the .exe at the right. How can I make the .exe one be as good as the one that runs thought python?
[ "I assume you mean the visual style of the toolbar and buttons. You need to add a manifest file to the EXE file or as a separate file so that Windows applies the modern style of recent comctl32.dll versions.\nCheck out Using Windows XP Visual Styles With Controls on Windows Forms on MSDN. Read the relevant part abo...
[ 7, 1, 0 ]
[]
[]
[ "graphics", "py2exe", "python", "wxpython" ]
stackoverflow_0003764410_graphics_py2exe_python_wxpython.txt
Q: How to open SQL Compact database read only There is a SQL Compact v3.1 database that I want to quickly read. I'm doing this in python so I don't have access to managed code. I've noticed that if I use adodbapi the database file actually gets modified just by opening it. And sadly when I add 'File mode=Read Only' to the connection string I get a weird error. Here is the code I use to connect: import adodbapi adodbapi.connect('Provider=Microsoft.SQLSERVER.MOBILE.OLEDB.3.0; Data Source="awesome.sdf"; File mode = Read Only;SSCE:Temp File Directory=c:\temp\\;') And then I get the error message OperationalError: (com_error(-2147352567, 'Exception occurred.', (0, u'Microsoft OLE DB Service Components', u'Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.', None, 0, -2147217887), None), u'Error opening connection: Provider=Microsoft.SQLSERVER.MOBILE.OLEDB.3.0; Data Source="Awesome.sdf";File mode = Read Only;SSCE:Temp File Directory="c:\\\temp\\";') I added the SSCE because when I wrote a test program in C# it needed it. The following code works perfectly fine and doesn't modify the file when you do a simple SELECT query. conn = new SqlCeConnection("Data Source = awesome.spf; File mode = Read Only;SSCE:Temp File Directory=\"c:\\users\\evelio\\desktop\\\";"); conn.Open(); Thanks for the help, Evelio A: Look here: http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/bf70c615-b279-4a91-b964-0ff99adc7ab8/#674f6a79-a3b4-4601-a952-860a7e8f3169 cn.Mode = adModeRead
How to open SQL Compact database read only
There is a SQL Compact v3.1 database that I want to quickly read. I'm doing this in python so I don't have access to managed code. I've noticed that if I use adodbapi the database file actually gets modified just by opening it. And sadly when I add 'File mode=Read Only' to the connection string I get a weird error. Here is the code I use to connect: import adodbapi adodbapi.connect('Provider=Microsoft.SQLSERVER.MOBILE.OLEDB.3.0; Data Source="awesome.sdf"; File mode = Read Only;SSCE:Temp File Directory=c:\temp\\;') And then I get the error message OperationalError: (com_error(-2147352567, 'Exception occurred.', (0, u'Microsoft OLE DB Service Components', u'Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.', None, 0, -2147217887), None), u'Error opening connection: Provider=Microsoft.SQLSERVER.MOBILE.OLEDB.3.0; Data Source="Awesome.sdf";File mode = Read Only;SSCE:Temp File Directory="c:\\\temp\\";') I added the SSCE because when I wrote a test program in C# it needed it. The following code works perfectly fine and doesn't modify the file when you do a simple SELECT query. conn = new SqlCeConnection("Data Source = awesome.spf; File mode = Read Only;SSCE:Temp File Directory=\"c:\\users\\evelio\\desktop\\\";"); conn.Open(); Thanks for the help, Evelio
[ "Look here: http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/bf70c615-b279-4a91-b964-0ff99adc7ab8/#674f6a79-a3b4-4601-a952-860a7e8f3169\ncn.Mode = adModeRead\n" ]
[ 3 ]
[]
[]
[ "ado", "python", "sql_server_ce" ]
stackoverflow_0003790090_ado_python_sql_server_ce.txt
Q: Using a java library from python I have a python app and java app. The python app generates input for the java app and invokes it on the command line. I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java. Any pointers? (FYI I'm v. new to Python) Clarification (at the cost of a long question: apologies) The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app. So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM). Since there is no obvious mechanism for this I think the simple CL invocation is the best solution. A: Sorry to ressurect the thread, but there was no accepted answer... You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods: >>> from py4j.java_gateway import JavaGateway >>> gateway = JavaGateway() # connect to the JVM >>> java_object = gateway.jvm.mypackage.MyClass() # invoke constructor >>> other_object = java_object.doThat() >>> other_object.doThis(1,'abc') >>> gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method As opposed to Jython, Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The communication is done through sockets instead of JNI. Disclaimer: I am the author of Py4J A: Take a look at Jython. It's kind of like JNI, but replace C with Python, i.e. you can call Python from Java and vice versa. It's not totally clear what you're trying to do or why your current approach isn't what you want. A: Wrap your Java-Code in a Container (Servlet / EJB). So you don´t loose time in the vm-startup and you go the way to more service-oriented. For the wraping you can use jython (only make sense if you are familiar with python) Choose a communication-protocoll in which python and java can use: json (see www.json.org) rmi (Python: JPype) REST SOAP (only for the brave) Choose something you or your partners are familliar with! A: If you really want to embed your Java app within your Python process, have a look at JPype. It provides access to Java through JNI. A: How about using swig: http://www.swig.org/Doc1.3/Java.html ? A: Give JCC a try http://pypi.python.org/pypi/JCC/2.1 JCC is a code generator for calling Java directly from CPython. It supports CPython 2.3+, several JREs (Sun JDK 1.4+, Apple JRE 1.4+, and OpenJDK 1.7) on OS X, Linux, Solaris, and Windows. It's produced by the Open Source Application Foundation (OSAF, the people making Chandler) and is released under an Apache-style license. From the package description: JCC is a C++ code generator for producing the glue code necessary to call into Java classes from CPython via Java's Native Invocation Interface (JNI). JCC generates C++ wrapper classes that hide all the gory details of JNI access as well Java memory and object reference management. JCC generates CPython types that make these C++ classes accessible from a Python interpreter. JCC attempts to make these Python types pythonic by detecting iterators and property accessors. Iterators and mappings may also be declared to JCC.
Using a java library from python
I have a python app and java app. The python app generates input for the java app and invokes it on the command line. I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java. Any pointers? (FYI I'm v. new to Python) Clarification (at the cost of a long question: apologies) The py app (which I don't own) takes user input in the form of a number of configuration files. It then interprits these and farms work off to a number of (hidden) tools via a plugin mechanism. I'm looking to add support for the functionality provided by the legacy Java app. So it doesn't make sense to call the python app from the java app and I can't run the py app in a jython environment (on the JVM). Since there is no obvious mechanism for this I think the simple CL invocation is the best solution.
[ "Sorry to ressurect the thread, but there was no accepted answer...\nYou could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:\n>>> from py4j.java_gateway import JavaGateway\n>>> gateway ...
[ 70, 11, 6, 5, 4, 2 ]
[]
[]
[ "java", "jython", "python" ]
stackoverflow_0000476968_java_jython_python.txt
Q: error when plotting log'd array in matplotlib/scipy/numpy I have two arrays and I take their logs. When I do that and try to plot their scatter plot, I get this error: File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/pyplot.py", line 2192, in scatter ret = ax.scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, faceted, verts, **kwargs) File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/axes.py", line 5384, in scatter self.add_collection(collection) File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/axes.py", line 1391, in add_collection self.update_datalim(collection.get_datalim(self.transData)) File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/collections.py", line 153, in get_datalim offsets = transOffset.transform_non_affine(offsets) File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/transforms.py", line 1924, in transform_non_affine self._a.transform(points)) File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/transforms.py", line 1420, in transform return affine_transform(points, mtx) ValueError: Invalid vertices array. the code is simply: myarray_x = log(my_array[:, 0]) myarray_y = log(my_array[:, 1]) plt.scatter(myarray_x, myarray_y) any idea what could be causing this? thanks. A: I had the same problem which I fixed recently: The problem for me was that my X and Y (numpy) arrays were made up of 128 bit floats. The solution in this case was to recast the arrays to a lower precision float i.e. array = numpy.float64(array) Hope this helps :~) A: New Answer: From looking at the source, this error is thrown if the points array passed into affine_transform is of the wrong dimensions or if it is empty. Here are the relevant lines: if (!vertices || (PyArray_NDIM(vertices) == 2 && PyArray_DIM(vertices, 1) != 2) || (PyArray_NDIM(vertices) == 1 && PyArray_DIM(vertices, 0) != 2)) throw Py::ValueError("Invalid vertices array."); Take a look at the dimensions of your myarray_x and myarray_y arrays before going ahead maybe. Old Answer: My best guess it that you are taking the log of values <= 0. This will either give you nan's or -infs(in the case of being equal to 0) in your arrays which of course it can't plot. (wiso is right though - these points are just ignored) A: This runs successfully for me >>> from numpy import log, array >>> import matplotlib.pyplot as plt >>> my_array = array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) >>> my_array array([[ 1., 2.], [ 3., 4.], [ 5., 6.]]) >>> myarray_x = log(my_array[:, 0]) >>> myarray_y = log(my_array[:, 1]) >>> plt.scatter(myarray_x, myarray_y) <matplotlib.collections.CircleCollection object at 0x030C7A10> >>> plt.show() so perhaps the problem is with something you haven't shown us. Can you provide a complete piece of sample code exactly as you ran it so we can reproduce your problem?
error when plotting log'd array in matplotlib/scipy/numpy
I have two arrays and I take their logs. When I do that and try to plot their scatter plot, I get this error: File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/pyplot.py", line 2192, in scatter ret = ax.scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, faceted, verts, **kwargs) File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/axes.py", line 5384, in scatter self.add_collection(collection) File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/axes.py", line 1391, in add_collection self.update_datalim(collection.get_datalim(self.transData)) File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/collections.py", line 153, in get_datalim offsets = transOffset.transform_non_affine(offsets) File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/transforms.py", line 1924, in transform_non_affine self._a.transform(points)) File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/transforms.py", line 1420, in transform return affine_transform(points, mtx) ValueError: Invalid vertices array. the code is simply: myarray_x = log(my_array[:, 0]) myarray_y = log(my_array[:, 1]) plt.scatter(myarray_x, myarray_y) any idea what could be causing this? thanks.
[ "I had the same problem which I fixed recently:\nThe problem for me was that my X and Y (numpy) arrays were made up of 128 bit floats.\nThe solution in this case was to recast the arrays to a lower precision float i.e. \narray = numpy.float64(array)\nHope this helps :~)\n", "New Answer:\nFrom looking at the sourc...
[ 7, 5, 4 ]
[]
[]
[ "matplotlib", "numpy", "python", "scipy" ]
stackoverflow_0002693399_matplotlib_numpy_python_scipy.txt
Q: How to get random slice of python list of constant size. (smallest code) Hi I have a List say 100 items, now i want a slice of say 6 items which should be randomly selected. Any way to do it in very simple simple concise statement??? This is what i came up with (but it will fetch in sequence) mylist #100 items N=100 L=6 start=random.randint(0,N-L); mylist[start:start+L] A: You could use the shuffle() method on the list before you slice. If the order of the list matters, just make a copy of it first and slice out of the copy. mylist #100 items shuffleList = mylist L=6 shuffle(shuffleList) start=random.randint(0,len(shuffleList)-L); shuffleList[start:start+L] As above, you could also use len() instead of defining the length of the list. As THC4K suggested below, you could use the random.sample() method like below IF you want a set of random numbers from the list (which is how I read your question). mylist #100 items L=6 random.sample(mylist, L) That's a lot tidier than my first try at it!
How to get random slice of python list of constant size. (smallest code)
Hi I have a List say 100 items, now i want a slice of say 6 items which should be randomly selected. Any way to do it in very simple simple concise statement??? This is what i came up with (but it will fetch in sequence) mylist #100 items N=100 L=6 start=random.randint(0,N-L); mylist[start:start+L]
[ "You could use the shuffle() method on the list before you slice.\nIf the order of the list matters, just make a copy of it first and slice out of the copy.\n\nmylist #100 items\nshuffleList = mylist\nL=6\nshuffle(shuffleList) \nstart=random.randint(0,len(shuffleList)-L);\nshuffleList[start:start+L]\n\nAs above, yo...
[ 13 ]
[]
[]
[ "python" ]
stackoverflow_0003793786_python.txt
Q: How can you select a random element from a list, and have it be removed? Let's say I have a list of colours, colours = ['red', 'blue', 'green', 'purple']. I then wish to call this python function that I hope exists, random_object = random_choice(colours). Now, if random_object holds 'blue', I hope colours = ['red', 'green', 'purple']. Does such a function exist in python? A: Firstly, if you want it removed because you want to do this again and again, you might want to use random.shuffle() in the random module. random.choice() picks one, but does not remove it. Otherwise, try: import random # this will choose one and remove it def choose_and_remove( items ): # pick an item index if items: index = random.randrange( len(items) ) return items.pop(index) # nothing left! return None A: one way: from random import shuffle def walk_random_colors( colors ): # optionally make a copy first: # colors = colors[:] shuffle( colors ) while colors: yield colors.pop() colors = [ ... whatever ... ] for color in walk_random_colors( colors ): print( color )
How can you select a random element from a list, and have it be removed?
Let's say I have a list of colours, colours = ['red', 'blue', 'green', 'purple']. I then wish to call this python function that I hope exists, random_object = random_choice(colours). Now, if random_object holds 'blue', I hope colours = ['red', 'green', 'purple']. Does such a function exist in python?
[ "Firstly, if you want it removed because you want to do this again and again, you might want to use random.shuffle() in the random module. \nrandom.choice() picks one, but does not remove it.\nOtherwise, try:\nimport random\n\n# this will choose one and remove it\ndef choose_and_remove( items ):\n # pick an item...
[ 8, 7 ]
[]
[]
[ "python", "random" ]
stackoverflow_0003791400_python_random.txt
Q: Managing subdomains What are the best practices and solutions for managing dynamic subdomains in different technologies and frameworks? I am searching for something to implement in my Django project but those solutions that I saw, don't work. I also tried to use Apache rewrite mod to send requests from subdomain.domain.com to domain.com/subdomain but couldn't realize how to do it with Django. UPDATE: What I need is to create virtual subdomains for my main domain using usernames from the site. So, if I have a new registered user that is called jack, when I go to jack.domain.com, it would operate make some operations. Like if I just went to domain.com/users/jack. But I don't want to create an actual subdomain for each user. A: You may be able to do what you need with apache mod_rewrite. Obviously I didn't read the question clearly enough. As for how to do it in django: you could have some middleware that looks at the server name, and redirects according to that (or even sets a variable). You can't do it with the bare url routing system, as that only has path information, not hostname info.
Managing subdomains
What are the best practices and solutions for managing dynamic subdomains in different technologies and frameworks? I am searching for something to implement in my Django project but those solutions that I saw, don't work. I also tried to use Apache rewrite mod to send requests from subdomain.domain.com to domain.com/subdomain but couldn't realize how to do it with Django. UPDATE: What I need is to create virtual subdomains for my main domain using usernames from the site. So, if I have a new registered user that is called jack, when I go to jack.domain.com, it would operate make some operations. Like if I just went to domain.com/users/jack. But I don't want to create an actual subdomain for each user.
[ "You may be able to do what you need with apache mod_rewrite.\nObviously I didn't read the question clearly enough.\nAs for how to do it in django: you could have some middleware that looks at the server name, and redirects according to that (or even sets a variable). You can't do it with the bare url routing syste...
[ 1 ]
[]
[]
[ "django", "python", "subdomain" ]
stackoverflow_0003793424_django_python_subdomain.txt