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:
String concatenation in Python
Can you describe difference between two ways of string concatenation: simple __add__ operator and %s patterns?
I had some investigation in this question and found %s (in form without using parentheses) a little faster.
Also another question was appeared: why result of 'hell%s' % 'o' refers to another memory region than 'hell%s' % ('o',)?
There is some code example:
l = ['hello', 'hell' + 'o', 'hell%s' % 'o', 'hell%s' % ('o',)]
print [id(s) for s in l]
Result:
[34375618400, 34375618400, 34375618400, 34375626256]
P.S. I know about string interning :)
A:
Here is a small exercise:
>>> def f1():
'hello'
>>> def f2():
'hel' 'lo'
>>> def f3():
'hel' + 'lo'
>>> def f4():
'hel%s' % 'lo'
>>> def f5():
'hel%s' % ('lo',)
>>> for f in (f1, f2, f3, f4, f5):
print(f.__name__)
dis.dis(f)
f1
1 0 LOAD_CONST 1 (None)
3 RETURN_VALUE
f2
1 0 LOAD_CONST 1 (None)
3 RETURN_VALUE
f3
2 0 LOAD_CONST 3 ('hello')
3 POP_TOP
4 LOAD_CONST 0 (None)
7 RETURN_VALUE
f4
2 0 LOAD_CONST 3 ('hello')
3 POP_TOP
4 LOAD_CONST 0 (None)
7 RETURN_VALUE
f5
2 0 LOAD_CONST 1 ('hel%s')
3 LOAD_CONST 3 (('lo',))
6 BINARY_MODULO
7 POP_TOP
8 LOAD_CONST 0 (None)
11 RETURN_VALUE
As you can see, all simple concatenations/formatting are done by compiler. The last function requires more complex formatting and therefore, I guess, is actually executed. Since all those object created at compilation time they all have the same id.
A:
Using % is, technically speaking, string formatting, not concatenation. They are two entirely* different worlds.
If you know about string interning then you should know that there's absolutely no guarantee that two strings will occupy the same memory as another. The fact that in your example the first three do is nothing more than pure coincidence.
I'm not 100% sure how string formatting works, but I know that it's not implemented the same in the underlying C as concatenation - I think it works a little more along the lines of ''.join(sequence), which is also faster than + for large strings - see this post for more info.
*sort of.
| String concatenation in Python | Can you describe difference between two ways of string concatenation: simple __add__ operator and %s patterns?
I had some investigation in this question and found %s (in form without using parentheses) a little faster.
Also another question was appeared: why result of 'hell%s' % 'o' refers to another memory region than 'hell%s' % ('o',)?
There is some code example:
l = ['hello', 'hell' + 'o', 'hell%s' % 'o', 'hell%s' % ('o',)]
print [id(s) for s in l]
Result:
[34375618400, 34375618400, 34375618400, 34375626256]
P.S. I know about string interning :)
| [
"Here is a small exercise:\n>>> def f1():\n 'hello'\n\n\n>>> def f2():\n 'hel' 'lo'\n\n\n>>> def f3():\n 'hel' + 'lo'\n\n\n>>> def f4():\n 'hel%s' % 'lo'\n\n\n>>> def f5():\n 'hel%s' % ('lo',)\n\n\n>>> for f in (f1, f2, f3, f4, f5):\n print(f.__name__)\n dis.dis(f)\n\n\nf1\n 1 0 LOAD... | [
7,
1
] | [] | [] | [
"compilation",
"internals",
"object_identity",
"python"
] | stackoverflow_0003371745_compilation_internals_object_identity_python.txt |
Q:
List all currently open file handles?
Possible Duplicate:
check what files are open in Python
Hello,
Is it possible to obtain a list of all currently open file handles, I presume that they are stored somewhere in the environment.
I am interested in theis function as I would like to safely handle any files that are open when a fatal error is raised, i.e. close file handles and replace potentially corrupted files with the original files.
I have the handling working but without knowing what file handles are open, I am unable to implement this idea.
As an aside, when a file handle is initialised, can this be inherited by another imported method?
Thank you
A:
lsof, /proc/pid/fd/
A:
The nice way of doing this would be to modify your code to keep track of when it opens a file:
def log_open( *args, **kwargs ):
print( "Opening a file..." )
print( *args, **kwargs )
return open( *args, **kwargs )
Then, use log_open instead of open to open files. You could even do something more hacky, like modifying the File class to log itself. That's covered in the linked question above.
There's probably a disgusting, filthy hack involving the garbage collector or looking in __dict__ or something, but you don't want to do that unless you absolutely really truly seriously must.
A:
If you're using python 2.5+ you can use the with keyword (though 2.5 needs `from future import with_statement)
with open('filename.txt', 'r') as f:
#do stuff here
pass
#here f has been closed and disposed properly - even with raised exceptions
I don't know what kind of catastrophic failure needs to bork the with statement, but I assume it's a really bad one. On WinXP, my quick unscientific test:
import time
with open('test.txt', 'w') as f:
f.write('testing\n')
while True:
time.sleep(1)
and then killing the process with Windows Task Manager still wrote the data to file.
| List all currently open file handles? |
Possible Duplicate:
check what files are open in Python
Hello,
Is it possible to obtain a list of all currently open file handles, I presume that they are stored somewhere in the environment.
I am interested in theis function as I would like to safely handle any files that are open when a fatal error is raised, i.e. close file handles and replace potentially corrupted files with the original files.
I have the handling working but without knowing what file handles are open, I am unable to implement this idea.
As an aside, when a file handle is initialised, can this be inherited by another imported method?
Thank you
| [
"lsof, /proc/pid/fd/\n",
"The nice way of doing this would be to modify your code to keep track of when it opens a file:\ndef log_open( *args, **kwargs ):\n print( \"Opening a file...\" )\n print( *args, **kwargs )\n return open( *args, **kwargs )\n\nThen, use log_open instead of open to open files. You ... | [
6,
2,
0
] | [] | [] | [
"filehandle",
"linux",
"python"
] | stackoverflow_0003370540_filehandle_linux_python.txt |
Q:
Decision maker question: compare ASP.NET / Ruby / Python on web UI controls
I need to learn a language for writing web applications (not websites!).
After some research in google and stackoverflow I ended up that the choice should fall in:
1) Ruby + Rails
2) Python + Django
3) c# + ASP.NET
For sure even pickng one randomly would not be a bad choice, but my question here is specific to UI controls. I come from the win32 developmenet world, so in my past experience I was in sites like DevExpress and Telerik that sell ASP.NET (or silverlight) controls like advanced grids, scheduling components, treelists...
So ASP.NET is covered, since Ruby/Python for me currently are totally unknown can you please shed some light on the UI side? I mean how in those worlds UI controls are managed? Where to find them?
All is done using libraries like ExtJS or JQuery? How does it work? (it is a newbie question, so forgive the over-simplicistic approach).
A:
Ruby on Rails is a server-side framework that processes HTTP requests and responds with HTML†. It doesn't have any concept of the kind of UI controls that you're referring to.
However, it can integrate with JavaScript frameworks such as ExtJS or jQuery and there are some Rails plugins or RubyGems that make this integration work easier. For example, this Railscast shows an example of using a calendar within a Rails application.
†Usually HTML. It can also respond with XML, JSON, text or whatever you like really.
A:
HTML only provides some "default controls". Such as dropdowns, buttons, hiperlinks and checkboxes.
More elaborated controls such as grids or treelists have to be built on top of the page using a combination of javascript and images. There are several libraries out there for doing so, my favourite one being jquery UI.
Ruby + Rails doesn't include any complex UI elements "out of the box" (just plain controls), but including jquery UI (or any other javascript library) isn't really very difficult.
I don't have much experience with Python and Django, but it is more or less the same history: they don't come with "advanced controls" by default; they just provide the regular html controls.
I have even less experience with ASP.NET. It could very well come with a UI library - you would have to look at it.
I've got a couple other remarks: you might be giving too much importance to UI elements. What differences a web application from a web site is not the fact that it uses this or that control; It's the stuff that happens on the server side. Which is, probably, where you will spend most of your time developing stuff.
With this in mind, I recommend you to re-think your question. Instead of asking yourself "what gives me more UI elements more easily" ask yourself "what gives me an easier time developing the server side".
My answer to that second question is, "probably Ruby on Rails". The amount of things it comes with may not be evident at first, but it enforces lots of good practices - from naming conventions, to testing, to unobstrusive javascript (that one on rails 3.0 mostly). The list just keeps going on. And on top of that, its community is fantastic.
In any case, please note that this is just my opinion and that I'm not very experienced on the other 2 systems - I just gave them some exploratory looks. You should check it with other sources.
A:
If you're already familiar with C# and ASP.NET, why not use that?
Of course if you know Python, the Django docs are a good great place to start. Even if you don't know Python they'll at least give you an idea about what it will take to learn/use Python+Django.
HTH!
| Decision maker question: compare ASP.NET / Ruby / Python on web UI controls | I need to learn a language for writing web applications (not websites!).
After some research in google and stackoverflow I ended up that the choice should fall in:
1) Ruby + Rails
2) Python + Django
3) c# + ASP.NET
For sure even pickng one randomly would not be a bad choice, but my question here is specific to UI controls. I come from the win32 developmenet world, so in my past experience I was in sites like DevExpress and Telerik that sell ASP.NET (or silverlight) controls like advanced grids, scheduling components, treelists...
So ASP.NET is covered, since Ruby/Python for me currently are totally unknown can you please shed some light on the UI side? I mean how in those worlds UI controls are managed? Where to find them?
All is done using libraries like ExtJS or JQuery? How does it work? (it is a newbie question, so forgive the over-simplicistic approach).
| [
"Ruby on Rails is a server-side framework that processes HTTP requests and responds with HTML†. It doesn't have any concept of the kind of UI controls that you're referring to. \nHowever, it can integrate with JavaScript frameworks such as ExtJS or jQuery and there are some Rails plugins or RubyGems that make this ... | [
3,
2,
1
] | [] | [] | [
"asp.net",
"python",
"ruby_on_rails",
"uicontrol"
] | stackoverflow_0003370019_asp.net_python_ruby_on_rails_uicontrol.txt |
Q:
OSError in one of the threads of Bottle framework, while running the dev server
When I run bottle development server, I notice some warning showing up.
Can any one figure it out what exactly is the problem?
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
self.run()
File "/usr/local/lib/python2.6/dist-packages/bottle-0.8.1-py2.6.egg/bottle.py", line 1406, in run
if path: files[path] = mtime(path)
File "/usr/local/lib/python2.6/dist-packages/bottle-0.8.1-py2.6.egg/bottle.py", line 1401, in <lambda>
mtime = lambda path: os.stat(path).st_mtime
OSError: [Errno 20] Not a directory: '/usr/local/lib/python2.6/dist-packages/github2-0.1.2-py2.6.egg/github2/issues.py'
A:
This is a bug in bottle (solved in 0.8.2). The reloading feature checks for modified module files and is confused by paths that point into egg archives. Update to 0.8.2 or disable the reloading-feature to solve this.
| OSError in one of the threads of Bottle framework, while running the dev server | When I run bottle development server, I notice some warning showing up.
Can any one figure it out what exactly is the problem?
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
self.run()
File "/usr/local/lib/python2.6/dist-packages/bottle-0.8.1-py2.6.egg/bottle.py", line 1406, in run
if path: files[path] = mtime(path)
File "/usr/local/lib/python2.6/dist-packages/bottle-0.8.1-py2.6.egg/bottle.py", line 1401, in <lambda>
mtime = lambda path: os.stat(path).st_mtime
OSError: [Errno 20] Not a directory: '/usr/local/lib/python2.6/dist-packages/github2-0.1.2-py2.6.egg/github2/issues.py'
| [
"This is a bug in bottle (solved in 0.8.2). The reloading feature checks for modified module files and is confused by paths that point into egg archives. Update to 0.8.2 or disable the reloading-feature to solve this.\n"
] | [
3
] | [] | [] | [
"bottle",
"multithreading",
"python"
] | stackoverflow_0003306139_bottle_multithreading_python.txt |
Q:
enabling tty in a ssh session
I would to take in some login information for a script have written in to be used by many users. In python I set the input_raw to read from dev/tty but it fails horribly when i am connecting to the script being run on a server through ssh.
Thoughts? Workarounds?
I would prefer to avoid hard coding usernames into the script.
Please and thank you.
A:
Try using the -t option to ssh:
-t Force pseudo-tty allocation. This can be used to execute arbi-
trary screen-based programs on a remote machine, which can be
very useful, e.g. when implementing menu services. Multiple -t
options force tty allocation, even if ssh has no local tty.
There doesn't seem to be an equivalent option in ~/.ssh/config, so you will need to create a shell script. A simple one is:
#!/bin/sh
ssh -t "$*"
Save this as ssh-t or something, chmod +x ssh-t, and put it somewhere in your PATH. Then set GIT_SSH=ssh-t to tell Git to use this script.
| enabling tty in a ssh session | I would to take in some login information for a script have written in to be used by many users. In python I set the input_raw to read from dev/tty but it fails horribly when i am connecting to the script being run on a server through ssh.
Thoughts? Workarounds?
I would prefer to avoid hard coding usernames into the script.
Please and thank you.
| [
"Try using the -t option to ssh:\n\n -t Force pseudo-tty allocation. This can be used to execute arbi-\n trary screen-based programs on a remote machine, which can be\n very useful, e.g. when implementing menu services. Multiple -t\n options force tty allocation, even ... | [
5
] | [] | [] | [
"python",
"scripting",
"ssh",
"tty"
] | stackoverflow_0003372268_python_scripting_ssh_tty.txt |
Q:
Algorithm to determine exchange rate
Given a data set of various currency pairs, how do I efficiently compute the implied fx rate for a pair not supplied in the data set?
For example, say my database/table looks like this (this data is fudged):
GBP x USD = 1.5
USD x GBP = 0.64
GBP x EUR = 1.19
AUD x USD = 1.1
Notice that (GBP,USD) != 1/(USD,GBP).
I would expect the following results:
print rate('GBP','USD')
> 1.5
print rate('USD','GBP')
> 0.64
print rate('GBP','EUR')
> 1.19
#now in the absence of an explicit pair, we imply one using the inverse
print rate('EUR','GBP')
> 0.84
These are the simple cases, it gets more interesting:
#this is the implied rate from (GBP,EUR) and (GBP,USD)
print rate('EUR','USD')
> 1.26
Or an even more complicated example is finding the most efficient translation using 3 or more pairs:
print rate('EUR','AUD')
> 1.38
I think that details the programming related aspects of this problem. I'd imagine there's an efficient or clever recursion that can be done here. The only requirement is that the least number of pairs are used to arrive at the asked for pair (this is to reduce error). If no explicit inverse is given, then inverting a pair costs you nothing.
Motivation
In the ideal financial world, currency markets are efficient. In reality, that's 99% true. Often times, odd currency pairs aren't quoted or they're quoted infrequently. If an explicit quote exists, we must use it in our arbitrary calculations. If not, we must imply the most accurate pair, out to as many decimal places as we can. Furthermore, they don't always multiply to 1 (actually, they never multiply to 1); this reflects the bid/ask spread in the market. So we keep as many pairs as we can in both directions, but would like to be able to code in general for all currencies.
I think I have a decent, brute force solution implemented. It works, but I thought the problem was interesting and was wondering if anyone else thought it was interesting/challenging. I'm personally working in Python but it's more an exercise than an implementation, so psuedo code is "good enough".
A:
You're looking for the shortest path in a directed graph, where the currencies are the vertices and the given exchange rates are the edges.
If an exchange rate is given only for one direction, you can add one for the opposite direction with a higher cost.
| Algorithm to determine exchange rate | Given a data set of various currency pairs, how do I efficiently compute the implied fx rate for a pair not supplied in the data set?
For example, say my database/table looks like this (this data is fudged):
GBP x USD = 1.5
USD x GBP = 0.64
GBP x EUR = 1.19
AUD x USD = 1.1
Notice that (GBP,USD) != 1/(USD,GBP).
I would expect the following results:
print rate('GBP','USD')
> 1.5
print rate('USD','GBP')
> 0.64
print rate('GBP','EUR')
> 1.19
#now in the absence of an explicit pair, we imply one using the inverse
print rate('EUR','GBP')
> 0.84
These are the simple cases, it gets more interesting:
#this is the implied rate from (GBP,EUR) and (GBP,USD)
print rate('EUR','USD')
> 1.26
Or an even more complicated example is finding the most efficient translation using 3 or more pairs:
print rate('EUR','AUD')
> 1.38
I think that details the programming related aspects of this problem. I'd imagine there's an efficient or clever recursion that can be done here. The only requirement is that the least number of pairs are used to arrive at the asked for pair (this is to reduce error). If no explicit inverse is given, then inverting a pair costs you nothing.
Motivation
In the ideal financial world, currency markets are efficient. In reality, that's 99% true. Often times, odd currency pairs aren't quoted or they're quoted infrequently. If an explicit quote exists, we must use it in our arbitrary calculations. If not, we must imply the most accurate pair, out to as many decimal places as we can. Furthermore, they don't always multiply to 1 (actually, they never multiply to 1); this reflects the bid/ask spread in the market. So we keep as many pairs as we can in both directions, but would like to be able to code in general for all currencies.
I think I have a decent, brute force solution implemented. It works, but I thought the problem was interesting and was wondering if anyone else thought it was interesting/challenging. I'm personally working in Python but it's more an exercise than an implementation, so psuedo code is "good enough".
| [
"You're looking for the shortest path in a directed graph, where the currencies are the vertices and the given exchange rates are the edges.\nIf an exchange rate is given only for one direction, you can add one for the opposite direction with a higher cost.\n"
] | [
16
] | [] | [] | [
"currency",
"finance",
"python"
] | stackoverflow_0003372375_currency_finance_python.txt |
Q:
Dynamic Loading of Modules then using "from x import *" on loaded module
I have some django apps which are versioned by app name.
appv1
appv2
The models.py in the apps are slightly different based on the version, but have the same model names.
I'm attempting to load the models dynamically into the current namespace.
So I've made a function that attempts to get the module and return it:
def get_models_module(release):
release_models_path = u"project.data_%s" % (release)
_temp = __import__(release_models_path, globals(), locals(), ["models"], -1)
models = _temp.models
return models
Then I try to load all the models from the returned models module but it fails.
models = get_models_module("1")
from models import *
When this happens I get the error:
ImportError: No module named models
I checked and the returned "models" object is listed as "module 'project.data_1.models' ...",
but apparently it doesn't like to be renamed.
Is there a way I can load all the defined models from the specific app revision?
Or, is there a better way to handle this kind of situation?
Note: This is currently only in the load function to get data into the database, and isn't run through any views.
Updated Solution:
Thanks Daniel Kluev for the solution, here's my updated function:
def load_release_models(release):
model_release = release.replace(u".", u"_").replace(u"-", u"d")
release_models_path = u"project.data_%s.models" % (model_release)
# import all release models into (global) namespace
exec(u"from {0} import *".format(release_models_path)) in globals()
Note - I'm loading into globals since I need access to these models within the whole file.
A:
At from models import * you are NOT referring to the models variable. You are just trying to import module called 'models', which, obviously, does not exist.
You can use hack like this to import everything from the module into current namespace:
ldict = locals()
for k in models.__dict__:
if not k.startswith('__') or not k.endswith('__'):
ldict[k] = models.__dict__[k]
Or use exec() to load the module,
exec("from project.data_{0}.models import *".format(release)) in locals()
| Dynamic Loading of Modules then using "from x import *" on loaded module | I have some django apps which are versioned by app name.
appv1
appv2
The models.py in the apps are slightly different based on the version, but have the same model names.
I'm attempting to load the models dynamically into the current namespace.
So I've made a function that attempts to get the module and return it:
def get_models_module(release):
release_models_path = u"project.data_%s" % (release)
_temp = __import__(release_models_path, globals(), locals(), ["models"], -1)
models = _temp.models
return models
Then I try to load all the models from the returned models module but it fails.
models = get_models_module("1")
from models import *
When this happens I get the error:
ImportError: No module named models
I checked and the returned "models" object is listed as "module 'project.data_1.models' ...",
but apparently it doesn't like to be renamed.
Is there a way I can load all the defined models from the specific app revision?
Or, is there a better way to handle this kind of situation?
Note: This is currently only in the load function to get data into the database, and isn't run through any views.
Updated Solution:
Thanks Daniel Kluev for the solution, here's my updated function:
def load_release_models(release):
model_release = release.replace(u".", u"_").replace(u"-", u"d")
release_models_path = u"project.data_%s.models" % (model_release)
# import all release models into (global) namespace
exec(u"from {0} import *".format(release_models_path)) in globals()
Note - I'm loading into globals since I need access to these models within the whole file.
| [
"At from models import * you are NOT referring to the models variable. You are just trying to import module called 'models', which, obviously, does not exist.\nYou can use hack like this to import everything from the module into current namespace:\nldict = locals()\nfor k in models.__dict__:\n if not k.startswit... | [
4
] | [] | [] | [
"django",
"import",
"python"
] | stackoverflow_0003372361_django_import_python.txt |
Q:
Calling Python instance methods in function decorators
Is there a clean way to have a decorator call an instance method on a class only at the time an instance of the class is instantiated?
class C:
def instance_method(self):
print('Method called')
def decorator(f):
print('Locals in decorator %s ' % locals())
def wrap(f):
print('Locals in wrapper %s' % locals())
self.instance_method()
return f
return wrap
@decorator
def function(self):
pass
c = C()
c.function()
I know this doesn't work because self is undefined at the point decorator is called (since it isn't called as an instance method as there is no available reference to the class). I then came up with this solution:
class C:
def instance_method(self):
print('Method called')
def decorator():
print('Locals in decorator %s ' % locals())
def wrap(f):
def wrapped_f(*args):
print('Locals in wrapper %s' % locals())
args[0].instance_method()
return f
return wrapped_f
return wrap
@decorator()
def function(self):
pass
c = C()
c.function()
This uses the fact that I know the first argument to any instance method will be self. The problem with the way this wrapper is defined is that the instance method is called every time the function is executed, which I don't want. I then came up with the following slight modification which works:
class C:
def instance_method(self):
print('Method called')
def decorator(called=[]):
print('Locals in decorator %s ' % locals())
def wrap(f):
def wrapped_f(*args):
print('Locals in wrapper %s' % locals())
if f.__name__ not in called:
called.append(f.__name__)
args[0].instance_method()
return f
return wrapped_f
return wrap
@decorator()
def function(self):
pass
c = C()
c.function()
c.function()
Now the function only gets called once, but I don't like the fact that this check has to happen every time the function gets called. I'm guessing there's no way around it, but if anyone has any suggestions, I'd love to hear them! Thanks :)
A:
I came up with this as a possible alternative solution. I like it because there is only one call that happens when the function is defined, and one when the class is instantiated. The only downside is a tiny bit of extra memory consumption for the function attribute.
from types import FunctionType
class C:
def __init__(self):
for name,f in C.__dict__.iteritems():
if type(f) == FunctionType and hasattr(f, 'setup'):
self.instance_method()
def instance_method(self):
print('Method called')
def decorator(f):
setattr(f, 'setup', True)
return f
@decorator
def function(self):
pass
c = C()
c.function()
c.function()
A:
I think you're asking something fundamentally impossible. The decorator will be created at the same time as the class, but the instance method doesn't exist until the instance does, which is later. So the decorator can't handle instance-specific functionality.
Another way to think about this is that the decorator is a functor: it transforms functions into other functions. But it doesn't say anything about the arguments of these functions; it works at a higher level than that. So invoking an instance method on an argument of function is not something that should be done by a decorator; it's something that should be done by function.
The way to get around this is necessarily hackish. Your method looks OK, as hacks go.
A:
It can be achieved by using callables as decorators.
class ADecorator(object):
func = None
def __new__(cls, func):
dec = object.__new__(cls)
dec.__init__(func)
def wrapper(*args, **kw):
return dec(*args, **kw)
return wrapper
def __init__(self, func, *args, **kw):
self.func = func
self.act = self.do_first
def do_rest(self, *args, **kw):
pass
def do_first(self, *args, **kw):
args[0].a()
self.act = self.do_rest
def __call__(self, *args, **kw):
return self.act(*args, **kw)
class A(object):
def a(self):
print "Original A.a()"
@ADecorator
def function(self):
pass
a = A()
a.function()
a.function()
A:
How should multiple instances of the class C behave? Should instance_method only be called once, no matter which instance calls function? Or should each instance call instance_method once?
Your called=[] default argument makes the decorator remember that something with string name function has been called. What if decorator is used on two different classes which both have a method named function? Then
c=C()
d=D()
c.function()
d.function()
will only call c.instance_method and prevent d.instance_method from getting called. Strange, and probably not what you want.
Below, I use self._instance_method_called to record if self.instance_method has been called. This makes each instance of C call instance_method at most once.
If you want instance_method to be called at most once regardless of which instance of C calls function, then simply define _instance_method_called as a class attribute instead of an instance attribute.
def decorator():
print('Locals in decorator %s ' % locals())
def wrap(f):
def wrapped(self,*args):
print('Locals in wrapper %s' % locals())
if not self._instance_method_called:
self.instance_method()
self._instance_method_called=True
return f
return wrapped
return wrap
class C:
def __init__(self):
self._instance_method_called=False
def instance_method(self): print('Method called')
@decorator()
def function(self):
pass
c = C()
# Locals in decorator {}
c.function()
# Locals in wrapper {'self': <__main__.C instance at 0xb76f1aec>, 'args': (), 'f': <function function at 0xb76eed14>}
# Method called
c.function()
# Locals in wrapper {'self': <__main__.C instance at 0xb76f1aec>, 'args': (), 'f': <function function at 0xb76eed14>}
d = C()
d.function()
# Locals in wrapper {'self': <__main__.C instance at 0xb76f1bcc>, 'args': (), 'f': <function function at 0xb76eed14>}
# Method called
d.function()
# Locals in wrapper {'self': <__main__.C instance at 0xb76f1bcc>, 'args': (), 'f': <function function at 0xb76eed14>}
Edit: To get rid of the if statement:
def decorator():
print('Locals in decorator %s ' % locals())
def wrap(f):
def rest(self,*args):
print('Locals in wrapper %s' % locals())
return f
def first(self,*args):
print('Locals in wrapper %s' % locals())
self.instance_method()
setattr(self.__class__,f.func_name,rest)
return f
return first
return wrap
class C:
def instance_method(self): print('Method called')
@decorator()
def function(self):
pass
| Calling Python instance methods in function decorators | Is there a clean way to have a decorator call an instance method on a class only at the time an instance of the class is instantiated?
class C:
def instance_method(self):
print('Method called')
def decorator(f):
print('Locals in decorator %s ' % locals())
def wrap(f):
print('Locals in wrapper %s' % locals())
self.instance_method()
return f
return wrap
@decorator
def function(self):
pass
c = C()
c.function()
I know this doesn't work because self is undefined at the point decorator is called (since it isn't called as an instance method as there is no available reference to the class). I then came up with this solution:
class C:
def instance_method(self):
print('Method called')
def decorator():
print('Locals in decorator %s ' % locals())
def wrap(f):
def wrapped_f(*args):
print('Locals in wrapper %s' % locals())
args[0].instance_method()
return f
return wrapped_f
return wrap
@decorator()
def function(self):
pass
c = C()
c.function()
This uses the fact that I know the first argument to any instance method will be self. The problem with the way this wrapper is defined is that the instance method is called every time the function is executed, which I don't want. I then came up with the following slight modification which works:
class C:
def instance_method(self):
print('Method called')
def decorator(called=[]):
print('Locals in decorator %s ' % locals())
def wrap(f):
def wrapped_f(*args):
print('Locals in wrapper %s' % locals())
if f.__name__ not in called:
called.append(f.__name__)
args[0].instance_method()
return f
return wrapped_f
return wrap
@decorator()
def function(self):
pass
c = C()
c.function()
c.function()
Now the function only gets called once, but I don't like the fact that this check has to happen every time the function gets called. I'm guessing there's no way around it, but if anyone has any suggestions, I'd love to hear them! Thanks :)
| [
"I came up with this as a possible alternative solution. I like it because there is only one call that happens when the function is defined, and one when the class is instantiated. The only downside is a tiny bit of extra memory consumption for the function attribute.\nfrom types import FunctionType\n\nclass C:\n ... | [
1,
0,
0,
0
] | [] | [] | [
"decorator",
"instance",
"methods",
"python"
] | stackoverflow_0003371680_decorator_instance_methods_python.txt |
Q:
Dealing with timezones in Django
I'm trying to deal with timezone information in Django. I tried doing something like:
results = Competitor.objects.raw("SELECT official_start AT TIME ZONE 'UTC', official_finish AT TIME ZONE 'UTC' FROM competitor WHERE race_id=1")
Thinking that this way I would know that the timezone was UTC but say I store a time in the database that is '2010-07-30 15:11:23' in UTC, in Django it will show up as '2010-07-30 10:11:23'. Any idea what is going on?
A:
I realized that in the settings.py file there is an option: TIME_ZONE. setting this to UTC solved the problem.
| Dealing with timezones in Django | I'm trying to deal with timezone information in Django. I tried doing something like:
results = Competitor.objects.raw("SELECT official_start AT TIME ZONE 'UTC', official_finish AT TIME ZONE 'UTC' FROM competitor WHERE race_id=1")
Thinking that this way I would know that the timezone was UTC but say I store a time in the database that is '2010-07-30 15:11:23' in UTC, in Django it will show up as '2010-07-30 10:11:23'. Any idea what is going on?
| [
"I realized that in the settings.py file there is an option: TIME_ZONE. setting this to UTC solved the problem.\n"
] | [
1
] | [] | [] | [
"django",
"python",
"time",
"timezone"
] | stackoverflow_0003372600_django_python_time_timezone.txt |
Q:
When to thread?
I have never written any code that uses threads.
I have a web application that accepts a POST request, and creates an image based on the data in the body of the request.
Would I want to spin off a thread for the image creation, as to prevent the server from hanging until the image is created? Is this an appropriate use, or merely a solution looking for a problem ?
Please correct any misunderstandings I may have.
A:
Rather than thinking about handling this via threads or even processes, consider using a distributed task manager such as Celery to manage this sort of thing.
A:
Usual approach for handling HTTP requests synchronously is to spawn (or re-use one in the pool) new thread for each request as soon as it comes.
However, python threads are not very good for HTTP, due to GIL and some i/o and other calls blocking whole app, including other threads.
You should look into multiprocessing module for this usage. Spawn some worker processes, and then pass requests to them to process.
| When to thread? | I have never written any code that uses threads.
I have a web application that accepts a POST request, and creates an image based on the data in the body of the request.
Would I want to spin off a thread for the image creation, as to prevent the server from hanging until the image is created? Is this an appropriate use, or merely a solution looking for a problem ?
Please correct any misunderstandings I may have.
| [
"Rather than thinking about handling this via threads or even processes, consider using a distributed task manager such as Celery to manage this sort of thing.\n",
"Usual approach for handling HTTP requests synchronously is to spawn (or re-use one in the pool) new thread for each request as soon as it comes.\nHow... | [
3,
2
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003372774_multithreading_python.txt |
Q:
Python: best/efficient way of finding a list of words in a text?
I have a list of approximately 300 words and a huge amount of text that I want to scan to know how many times each word appears.
I am using the re module from python:
for word in list_word:
search = re.compile(r"""(\s|,)(%s).?(\s|,|\.|\))""" % word)
occurrences = search.subn("", text)[1]
but I want to know if there is a more efficient or more elegant way of doing this?
A:
If you have a huge amount of text, I wouldn't use regexps in this case but simply split text:
words = {"this": 0, "that": 0}
for w in text.split():
if w in words:
words[w] += 1
words will give you the frequency for each word
A:
Try stripping all the punctuation from your text and then splitting on whitespace. Then simply do
for word in list_word:
occurence = strippedText.count(word)
Or if you're using python 3.0 I think you could do:
occurences = {word: strippedText.count(word) for word in list_word}
A:
Googling: python frequency
gives me this page as the first result: http://www.daniweb.com/code/snippet216747.html
Which seems to be what you're looking for.
A:
You can also split the text into words and search the resulting list.
A:
Regular expressions may not be what you want. Python has a number of built-in string operations that are much faster, and I believe .count() has what you need.
http://docs.python.org/library/stdtypes.html#string-methods
A:
If Python is not a must, you can use awk
$ cat file
word1
word2
word3
word4
$ cat file1
blah1 blah2 word1 word4 blah3 word2
junk1 junk2 word2 word1 junk3
blah4 blah5 word3 word6 end
$ awk 'FNR==NR{w[$1];next} {for(i=1;i<=NF;i++) a[$i]++}END{for(i in w){ if(i in a) print i,a[i] } } ' file file1
word1 2
word2 2
word3 1
word4 1
A:
It sounds to me like the Natural Language Toolkit might have what you need.
http://www.nltk.org/
A:
Maybe you could adapt this my multisearch generator function.
from itertools import islice
testline = "Sentence 1. Sentence 2? Sentence 3! Sentence 4. Sentence 5."
def multis(search_sequence,text,start=0):
""" multisearch by given search sequence values from text, starting from position start
yielding tuples of text before sequence item and found sequence item"""
x=''
for ch in text[start:]:
if ch in search_sequence:
if x: yield (x,ch)
else: yield ch
x=''
else:
x+=ch
else:
if x: yield x
# split the first two sentences by the dot/question/exclamation.
two_sentences = list(islice(multis('.?!',testline),2)) ## must save the result of generation
print "result of split: ", two_sentences
print '\n'.join(sentence.strip()+sep for sentence,sep in two_sentences)
| Python: best/efficient way of finding a list of words in a text? | I have a list of approximately 300 words and a huge amount of text that I want to scan to know how many times each word appears.
I am using the re module from python:
for word in list_word:
search = re.compile(r"""(\s|,)(%s).?(\s|,|\.|\))""" % word)
occurrences = search.subn("", text)[1]
but I want to know if there is a more efficient or more elegant way of doing this?
| [
"If you have a huge amount of text, I wouldn't use regexps in this case but simply split text:\nwords = {\"this\": 0, \"that\": 0}\nfor w in text.split():\n if w in words:\n words[w] += 1\n\nwords will give you the frequency for each word\n",
"Try stripping all the punctuation from your text and then splittin... | [
5,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003372332_python_regex.txt |
Q:
How do I fix a "JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)"?
I'm trying to get Twitter API search results for a given hashtag using Python, but I'm having trouble with this "No JSON object could be decoded" error. I had to add the extra % towards the end of the URL to prevent a string formatting error. Could this JSON error be related to the extra %, or is it caused by something else? Any suggestions would be much appreciated.
A snippet:
import simplejson
import urllib2
def search_twitter(quoted_search_term):
url = "http://search.twitter.com/search.json?callback=twitterSearch&q=%%23%s" % quoted_search_term
f = urllib2.urlopen(url)
json = simplejson.load(f)
return json
A:
There were a couple problems with your initial code. First you never read in the content from twitter, just opened the url. Second in the url you set a callback (twitterSearch). What a call back does is wrap the returned json in a function call so in this case it would have been twitterSearch(). This is useful if you want a special function to handle the returned results.
import simplejson
import urllib2
def search_twitter(quoted_search_term):
url = "http://search.twitter.com/search.json?&q=%%23%s" % quoted_search_term
f = urllib2.urlopen(url)
content = f.read()
json = simplejson.loads(content)
return json
| How do I fix a "JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)"? | I'm trying to get Twitter API search results for a given hashtag using Python, but I'm having trouble with this "No JSON object could be decoded" error. I had to add the extra % towards the end of the URL to prevent a string formatting error. Could this JSON error be related to the extra %, or is it caused by something else? Any suggestions would be much appreciated.
A snippet:
import simplejson
import urllib2
def search_twitter(quoted_search_term):
url = "http://search.twitter.com/search.json?callback=twitterSearch&q=%%23%s" % quoted_search_term
f = urllib2.urlopen(url)
json = simplejson.load(f)
return json
| [
"There were a couple problems with your initial code. First you never read in the content from twitter, just opened the url. Second in the url you set a callback (twitterSearch). What a call back does is wrap the returned json in a function call so in this case it would have been twitterSearch(). This is useful if ... | [
8
] | [] | [] | [
"json",
"python",
"simplejson",
"twitter"
] | stackoverflow_0003372643_json_python_simplejson_twitter.txt |
Q:
Passing an array of long strings ( >4000 bytes) to an Oracle (11gR2) stored procedure using cx_Oracle
We need to bulk load many long strings (>4000 Bytes, but <10,000 Bytes) using cx_Oracle. The data type in the table is CLOB. We will need to load >100 million of these strings. Doing this one by one would suck. Doing it in a bulk fashion, ie using cursor.arrayvar() would be ideal. However, CLOB does not support arrays. BLOB, LOB, LONG_STRING LONG_RAW don't either. Any help would be greatly appreciated.
A:
Off the wall suggestion, but since you are on 11gR2 have a look at DBFS
From the 'load' point of view, you are just copying files and they 'appear' as LOBs. You can do a similar thing with the built-in FTP server but file handling is a lot easier.
You just then write a procedure that pulls them from the dbfs_content view and pushes them to your procedure.
The other though, is, if they are all under 12,000 bytes, split them into three parts and deal with them as three separate VARCHAR2(4000) strings and join them up again on the PL/SQL side.
A:
In the interest of getting shit done that is good enough, we did the abuse of the CLOB I mentioned in my comment. It took less than 30 minutes to get coded up, runs fast and works.
| Passing an array of long strings ( >4000 bytes) to an Oracle (11gR2) stored procedure using cx_Oracle | We need to bulk load many long strings (>4000 Bytes, but <10,000 Bytes) using cx_Oracle. The data type in the table is CLOB. We will need to load >100 million of these strings. Doing this one by one would suck. Doing it in a bulk fashion, ie using cursor.arrayvar() would be ideal. However, CLOB does not support arrays. BLOB, LOB, LONG_STRING LONG_RAW don't either. Any help would be greatly appreciated.
| [
"Off the wall suggestion, but since you are on 11gR2 have a look at DBFS\nFrom the 'load' point of view, you are just copying files and they 'appear' as LOBs. You can do a similar thing with the built-in FTP server but file handling is a lot easier.\nYou just then write a procedure that pulls them from the dbfs_con... | [
0,
0
] | [] | [] | [
"cx_oracle",
"oracle",
"python"
] | stackoverflow_0003358666_cx_oracle_oracle_python.txt |
Q:
Pylons 1.0 - c.id no longer being automatically set on python v2.6.2 and 2.7
I am at a loss on this one, I intalled a SSD on my dev box today and started with a fresh development environment.
In short, pylons no longer sets the c.id based on the id passed to the action.
Code, error, and libs install: http://pastie.org/1064929
Very strange, because my production server is mirroring my python version (2.6.2) and all my python libs are at the latest release on both machines. I only experience this on my dev machine. I have tried python 2.7 with the same results.
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39))
A:
Well, after trying older releases of paste and routes I gave up and removed all usage of c.id. I suppose that is what I get for relying on too much magic.
| Pylons 1.0 - c.id no longer being automatically set on python v2.6.2 and 2.7 | I am at a loss on this one, I intalled a SSD on my dev box today and started with a fresh development environment.
In short, pylons no longer sets the c.id based on the id passed to the action.
Code, error, and libs install: http://pastie.org/1064929
Very strange, because my production server is mirroring my python version (2.6.2) and all my python libs are at the latest release on both machines. I only experience this on my dev machine. I have tried python 2.7 with the same results.
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39))
| [
"Well, after trying older releases of paste and routes I gave up and removed all usage of c.id. I suppose that is what I get for relying on too much magic.\n"
] | [
0
] | [] | [] | [
"paster",
"pylons",
"python"
] | stackoverflow_0003359295_paster_pylons_python.txt |
Q:
How do I get an instance of BaseHTTPRequestHandler instantiated during request handling inside an action code?
I need to access the rfile and wfile properties of a request handler instance. AFAIK, such a handler is instantiated by the framework during request lifetime.
Update: I found that rfile is accessible through request.environ['wsgi.input']. To access wfile I've do a hack with the additional line in Paste sources, httpserver.py:210:
,'wsgi.output': self.wfile
But I wonder if there is a better solution...
A:
Better do like this http://pythonpaste.org/webob/reference.html#body-app-iter
In pylons action:
f = response.body_file
f.write('hey')
The response.body_file is only like a file object, but not real stream.
For more details read http://www.python.org/dev/peps/pep-0333/#id22
| How do I get an instance of BaseHTTPRequestHandler instantiated during request handling inside an action code? | I need to access the rfile and wfile properties of a request handler instance. AFAIK, such a handler is instantiated by the framework during request lifetime.
Update: I found that rfile is accessible through request.environ['wsgi.input']. To access wfile I've do a hack with the additional line in Paste sources, httpserver.py:210:
,'wsgi.output': self.wfile
But I wonder if there is a better solution...
| [
"Better do like this http://pythonpaste.org/webob/reference.html#body-app-iter\nIn pylons action:\n f = response.body_file\n f.write('hey')\n\nThe response.body_file is only like a file object, but not real stream.\nFor more details read http://www.python.org/dev/peps/pep-0333/#id22\n"
] | [
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003365660_pylons_python.txt |
Q:
python subprocess calling "internal" process
Out of curiosity and trying to understand the subprocess module: Is it possible to do something like:
import subprocess
def myfun(arg):
# do stuff
arg = something;
p = subprocess.Popen(["myfun","arg"])
without putting "myfun" in a file of its own? It seems like this would in general be a scary thing to do if you are not careful about cleaning up child processes.
A:
You can pass Popen a preexec_fn, which is a callable object executed in the child process before the command is exec'd. A more standard approach is to use the multiprocessing module, which requires a Python function instead of an external command.
| python subprocess calling "internal" process | Out of curiosity and trying to understand the subprocess module: Is it possible to do something like:
import subprocess
def myfun(arg):
# do stuff
arg = something;
p = subprocess.Popen(["myfun","arg"])
without putting "myfun" in a file of its own? It seems like this would in general be a scary thing to do if you are not careful about cleaning up child processes.
| [
"You can pass Popen a preexec_fn, which is a callable object executed in the child process before the command is exec'd. A more standard approach is to use the multiprocessing module, which requires a Python function instead of an external command.\n"
] | [
4
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003373554_python_subprocess.txt |
Q:
Measuring rectangles at odd angles with a low resolution input matrix (Linear regression classification?)
I'm trying to solve the following problem:
Given an input of, say,
0000000000000000
0011111111110000
0011111111110000
0011111111110000
0000000000000000
0000000111111110
0000000111111110
0000000000000000
I need to find the width and height of all rectangles in the field. The input is actually a single column at a time (think like a scanner moves from left to right) and is continuous for the duration of the program (that is, the scanning column doesn't move, but the rectangles move over it).
In this example, I can 'wait for a rectangle to begin' (that is, watch for zeros changing to 1s) and then watch it end (ones back to zeros) and measure the piece in 'grid units'. This will work fine for the simple case outlined above, but will fail is the rectangle is tilted at an angle, for example:
0000000000000000
0000011000000000
0000111100000000
0001111111000000
0000111111100000
0000011111110000
0000000111100000
0000000011000000
I had originally thought that the following question would apply:
Dynamic programming - Largest square block
but now i'm not so sure.
I have little to no experience with regression or regression testing, but I think that I could represent this as an input of 8 variables.....
Well to be honest i'm not sure how I would do this at all. The sizes that this part of the code extracts need to be fitted against rectangles of known sizes (ie, from a database).
I initially thought I could feed the known data as training exercises and store the positive test results, but I'm really not sure where to go from here.
Thanks for any advice you might have.
A:
Collect the transition points (from a 1 to a 0 or vice-versa) as you're scanning, then figure the length and width either directly from there, or from the convex hull of each object.
If rectangles can overlap, then you'll have bigger issues.
A:
I'd take following steps:
get all columns together in a matrix (this is needed for proper filtering)
now apply a filter (need to google for it a bit) to sharpen edges and corners
create some structure to hold data for next steps (this can have many different solutions, choose your favorite and/or optimal)
scan vertically (column by column) and for each segment of consequent 'ones' found in a column (segment means you have found it's start end end y coordinates) do:
check that this segment overlaps some segment in the previous column
if it does not, consider this a new rect. Create a rect object and assign it's handle to the segment. for the new rect, update it's metrics (this operation takes just the segment's coordinates - x, ymin, ymax, and will be discussed later)
if it does, assume this is the same rect, take the rect's handle, assign this handle to the current segment then get the rect by it's handle and update it's metrics
That's pretty it. After this you will have a pool of rect objects each having four coordinates of its corners. Do some primitive math to approximate rect's width and height.
So where is the magic? Well, it all happens in the update rect metrics routine.
For each rect we have 13 metrics:
min X => ymin1, ymax1
max X => ymin2, ymax2
min Y => xmin1, xmax1
max Y => xmin2, xmax2
average vertical segment length
First of all we have to determine if this rect is properly aligned within our scan grid. To do this we compare values average vertical segment length and max Y - min Y. If they are the same (i'd choose a threshold around 97%, and then tune it for the best results), then we assume the following coordinates for our rect:
(min X, max Y)
(min X, min Y)
(max X, max Y)
(max X, min Y).
In other case out rect is rotated and in this case we take it's coordinates as follows:
(min X, (ymin1+ymax1)/2)
((xmin1+xmax1)/2, min Y)
(max X, (ymin2+ymax2)/2)
((xmin2+xmax2)/2, max Y)
A:
I posed this question to a friend, and he suggested:
When seeing a 1 for the first time, store it as a new shape. Flood fill it to the right, and add those points to the same shape.
Any input pixel that is'nt in a shape now is a new shape. Do the same flood fill.
On the next input column, flood again from the original shape points. Add new pixels to the corresponding shape
If any flood fill does not add any new pixels for two consecutive columns, you have a completed shape. Move on, and try to determine it's dimensions
This then leaves us with getting the dimensions for a shape we isolated (like in example 2).
For this, we thought up:
If the number of leftmost pixels in the shape is below the average number of pixels per column, then the peice is probably rotated. Thus, find the corners by getting the outermost pixels. Use distance formula between all of them. Largest = hypotenuse, others = width or height.
Otherwise, this peice is probably perfectly aligned, so the corners are probably just the topleft most pixel, bottom right most pixel, etc
What do you all think?
| Measuring rectangles at odd angles with a low resolution input matrix (Linear regression classification?) | I'm trying to solve the following problem:
Given an input of, say,
0000000000000000
0011111111110000
0011111111110000
0011111111110000
0000000000000000
0000000111111110
0000000111111110
0000000000000000
I need to find the width and height of all rectangles in the field. The input is actually a single column at a time (think like a scanner moves from left to right) and is continuous for the duration of the program (that is, the scanning column doesn't move, but the rectangles move over it).
In this example, I can 'wait for a rectangle to begin' (that is, watch for zeros changing to 1s) and then watch it end (ones back to zeros) and measure the piece in 'grid units'. This will work fine for the simple case outlined above, but will fail is the rectangle is tilted at an angle, for example:
0000000000000000
0000011000000000
0000111100000000
0001111111000000
0000111111100000
0000011111110000
0000000111100000
0000000011000000
I had originally thought that the following question would apply:
Dynamic programming - Largest square block
but now i'm not so sure.
I have little to no experience with regression or regression testing, but I think that I could represent this as an input of 8 variables.....
Well to be honest i'm not sure how I would do this at all. The sizes that this part of the code extracts need to be fitted against rectangles of known sizes (ie, from a database).
I initially thought I could feed the known data as training exercises and store the positive test results, but I'm really not sure where to go from here.
Thanks for any advice you might have.
| [
"Collect the transition points (from a 1 to a 0 or vice-versa) as you're scanning, then figure the length and width either directly from there, or from the convex hull of each object. \nIf rectangles can overlap, then you'll have bigger issues.\n",
"I'd take following steps:\n\nget all columns together in a matr... | [
2,
1,
0
] | [] | [] | [
"classification",
"linear_regression",
"python"
] | stackoverflow_0003372659_classification_linear_regression_python.txt |
Q:
Is there a JGraph alternative for Python?
Which library can I use to develop an application for visual modeling with graphs?
Is there a library for Python like JGraph for Java?
Thank you!
A:
GraphViz is a powerful tool to make nice graphs and you have a python wrapper called PygraphViz that should answer your question.
A:
I don't know from JGraph, but gnuplot has a Python wrapper.
| Is there a JGraph alternative for Python? | Which library can I use to develop an application for visual modeling with graphs?
Is there a library for Python like JGraph for Java?
Thank you!
| [
"GraphViz is a powerful tool to make nice graphs and you have a python wrapper called PygraphViz that should answer your question.\n",
"I don't know from JGraph, but gnuplot has a Python wrapper.\n"
] | [
2,
0
] | [] | [] | [
"graph",
"modeling",
"python",
"user_interface"
] | stackoverflow_0003373095_graph_modeling_python_user_interface.txt |
Q:
Line-wrapping problems with IPython shell
If I have run a long line in IPython, and try and recall it (using the up-arrow) or backspace beyond the start of the current line, it displays incorrectly (all smushed into one line)
For example, in the following session I wrote a long line [1], entered a somewhat-blank line [2], then up-arrowed twice to get the print statement on line [3], and the following happened:
Happens in both iTerm and Terminal.app.. I had a similar problem with regular terminal sessions, which was fixed by properly terminating colour codes, but I'm not sure how to fix it with IPython
A:
Aha! I had an old version of the Python readline module - installing the latest from http://ipython.scipy.org/dist/ and it works perfectly!
sudo easy_install http://ipython.scipy.org/dist/readline-2.5.1-py2.5-macosx-10.5-i386.egg
A:
Got this problem on Snow Leopard. Installing a new version of readline from http://pypi.python.org/pypi/readline/ fixes it:
sudo easy_install http://pypi.python.org/packages/2.6/r/readline/readline-2.6.4-py2.6-macosx-10.6-universal.egg
A:
I can't reproduce it (up-arrow works for long lines in ipython):
| Line-wrapping problems with IPython shell | If I have run a long line in IPython, and try and recall it (using the up-arrow) or backspace beyond the start of the current line, it displays incorrectly (all smushed into one line)
For example, in the following session I wrote a long line [1], entered a somewhat-blank line [2], then up-arrowed twice to get the print statement on line [3], and the following happened:
Happens in both iTerm and Terminal.app.. I had a similar problem with regular terminal sessions, which was fixed by properly terminating colour codes, but I'm not sure how to fix it with IPython
| [
"Aha! I had an old version of the Python readline module - installing the latest from http://ipython.scipy.org/dist/ and it works perfectly!\nsudo easy_install http://ipython.scipy.org/dist/readline-2.5.1-py2.5-macosx-10.5-i386.egg\n\n",
"Got this problem on Snow Leopard. Installing a new version of readline from... | [
12,
2,
1
] | [] | [] | [
"ipython",
"python",
"terminal"
] | stackoverflow_0000670764_ipython_python_terminal.txt |
Q:
Building a compiler or interpreter using Python
Right now I'm writing my PhD proposal to build a language processor for a new specification language for Java (cf. JML, or Spec# for C#) and need to nail down an implementation tool to start development. The research aspects of the language (syntax, semantics, theoretical results) are orthogonal to my choice of implementation, so I'd like to use Python (2.6+) for my own reasons. The end-product will be either a compiler or interpreter capable of verifying some specified properties for programs written in Java.
What's the best framework/library for building compilers/interpreters in Python? Are the "batteries included" for this problem?
Bonus points awarded to solutions that have reference compilers for Java 6+.
A:
I personally can't stand antlr, I use lex/yacc as my parser generator. Here is a Python implementation http://www.dabeaz.com/ply/ that you could use.
That just deals with parsing though, that really doesn't even begin to construct your interpreter. For that, you'll probably be building it from the ground up - I've never heard of a library specifically geared towards this (I would be excited to see some of them, please link me there in the comments if you know of any).
Check out this SO post how to start writing a very simple programming language it has good ideas.il.
A:
maybe you want to have a look at this
A:
May I suggest antlr with its python binding?
| Building a compiler or interpreter using Python | Right now I'm writing my PhD proposal to build a language processor for a new specification language for Java (cf. JML, or Spec# for C#) and need to nail down an implementation tool to start development. The research aspects of the language (syntax, semantics, theoretical results) are orthogonal to my choice of implementation, so I'd like to use Python (2.6+) for my own reasons. The end-product will be either a compiler or interpreter capable of verifying some specified properties for programs written in Java.
What's the best framework/library for building compilers/interpreters in Python? Are the "batteries included" for this problem?
Bonus points awarded to solutions that have reference compilers for Java 6+.
| [
"I personally can't stand antlr, I use lex/yacc as my parser generator. Here is a Python implementation http://www.dabeaz.com/ply/ that you could use.\nThat just deals with parsing though, that really doesn't even begin to construct your interpreter. For that, you'll probably be building it from the ground up - I... | [
7,
1,
0
] | [] | [] | [
"compiler_construction",
"interpreter",
"java",
"programming_languages",
"python"
] | stackoverflow_0003373817_compiler_construction_interpreter_java_programming_languages_python.txt |
Q:
HOWTO: Write Python API wrapper?
I'd like to write a python library to wrap a REST-style API offered by a particular Web service. Does anyone know of any good learning resources for such work, preferably aimed at intermediate Python programmers?
I'd like a good article on the subject, but I'd settle for nice, clear code examples.
CLARIFICATION: What I'm looking to do is write a Python client to interact with a Web service -- something to construct HTTP requests and parse XML/JSON responses, all wrapped up in Python objects.
A:
I can't point you to any article on how to do it, but I think there are a few libraries that can be good models on how to design your own.
PyAws for example. I didn't see the source code so I can't tell you how good it is as code example, but the features and the usage examples in their website should be a useful design model
Universal Feed Parser is not a wrapper for a webservice (it's an RSS parser library), but it's a great example of a design that prioritizes usage flexibility and hiding implementation details. I think you can get very good usage ideas for your wrapper there.
A:
My favorite combination is httplib2 (or pycurl for performance) and simplejson. As REST is more "a way of design" then a real "protocol" there is not really a reusable thing (that I know of). On Ruby you have something like ActiveResource. And to be honest, even that would just expose some tables as a webservice, whereas the power of xml/json is that they are more like "views" that can contain multiple objects optimized for your application. I hope this makes sense :-)
A:
This tutorial page could be a good starting place (but it doesn't contain everything you need).
A:
You should take a look at PyFacebook. This is a python wrapper for the Facebook API, and it's one of the most nicely done API's I have ever used.
A:
You could checkout pythenic jobs, a nice, simple, but well-formed "Python wrapper around the Authentic Jobs ... API" as a good example. That's what I'm doing now :)
| HOWTO: Write Python API wrapper? | I'd like to write a python library to wrap a REST-style API offered by a particular Web service. Does anyone know of any good learning resources for such work, preferably aimed at intermediate Python programmers?
I'd like a good article on the subject, but I'd settle for nice, clear code examples.
CLARIFICATION: What I'm looking to do is write a Python client to interact with a Web service -- something to construct HTTP requests and parse XML/JSON responses, all wrapped up in Python objects.
| [
"I can't point you to any article on how to do it, but I think there are a few libraries that can be good models on how to design your own.\nPyAws for example. I didn't see the source code so I can't tell you how good it is as code example, but the features and the usage examples in their website should be a useful... | [
3,
2,
0,
0,
0
] | [] | [] | [
"api",
"python",
"rest",
"web_services"
] | stackoverflow_0000517237_api_python_rest_web_services.txt |
Q:
Global Variable Not Defined
I'm calling two separate functions to determine what "P01" equals. The first one selects a random number, and discards random numbers already picked. The second one takes the result of the random number and picks a variable to make 'position' equal. I then say that 'P01' equals 'position.'
I've made 'position' a global variable, but I keep getting an error when I try to assign 'position' to 'P01' saying "position is not defined."
Any ideas?
### Monster Statistics ####
Cerebus = {'name': 'Cerebus','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Cthulhu = {'name': 'Cthulhu','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Cyclops = {'name': 'Cyclops','HP1': 65,'HP2': 85,'HP3': 95,'HP4': 130,'Atk1L1': 3,'Atk1L2': 4,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 3,'Atk1L2dmg': 4,'Atk1L3dmg': 4,'Atk1L4dmg': 5,'Atk2L1': 2,'Atk2L2': 3,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 5,'Atk2L2dmg': 6,'Atk2L3dmg': 6,'Atk2L4dmg': 7,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 3,'Atk3L1dmg': 5,'Atk3L2dmg': 6,'Atk3L3dmg': 6,'Atk3L4dmg': 7,'Dfns1': 2,'Dfns2': 3,'Dfns3': 4,'Dfns4': 5,}
Genie = {'name': 'Genie','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
GiantApe = {'name': 'Giant Ape','HP1': 70,'HP2': 90,'HP3': 110,'HP4': 140,'Atk1L1': 3,'Atk1L2': 4,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 4,'Atk1L2dmg': 5,'Atk1L3dmg': 5,'Atk1L4dmg': 6,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 5,'Atk2L2dmg': 6,'Atk2L3dmg': 6,'Atk2L4dmg': 7,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 3,'Atk3L1dmg': 6,'Atk3L2dmg': 6,'Atk3L3dmg': 7,'Atk3L4dmg': 8,'Dfns1': 2,'Dfns2': 3,'Dfns3': 3,'Dfns4': 4,}
GiantLizard = {'name': 'Giant Lizard','HP1': 80,'HP2': 100,'HP3': 130,'HP4': 170,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 3,'Atk1L2dmg': 4,'Atk1L3dmg': 5,'Atk1L4dmg': 6,'Atk2L1': 2,'Atk2L2': 3,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 4,'Atk2L2dmg': 5,'Atk2L3dmg': 6,'Atk2L4dmg': 7,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 6,'Atk3L2dmg': 7,'Atk3L3dmg': 8,'Atk3L4dmg': 8,'Dfns1': 1,'Dfns2': 2,'Dfns3': 2,'Dfns4': 3,}
GreyAlien = {'name': 'Grey Alien','HP1': 30,'HP2': 40,'HP3': 45,'HP4': 50,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 3,'Atk2L4dmg': 4,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 4,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 3,'Dfns2': 4,'Dfns3': 4,'Dfns4': 5,}
Gryffin = {'name': 'Gryffin','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Leprechaun = {'name': 'Leprechaun','HP1': 30,'HP2': 35,'HP3': 50,'HP4': 65,'Atk1L1': 3,'Atk1L2': 4,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 1,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 3,'Atk2L3': 4,'Atk2L4': 5,'Atk2L1dmg': 2,'Atk2L2dmg': 2,'Atk2L3dmg': 3,'Atk2L4dmg': 4,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 4,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 6,'Atk3L4dmg': 6,'Dfns1': 4,'Dfns2': 6,'Dfns3': 7,'Dfns4': 8,}
Medusa = {'name': 'Medusa','HP1': 20,'HP2': 30,'HP3': 45,'HP4': 50,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 4,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 2,'Atk2L2dmg': 2,'Atk2L3dmg': 3,'Atk2L4dmg': 3,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 2,'Dfns2': 3,'Dfns3': 4,'Dfns4': 4,}
Minotaur = {'name': 'Minotaur','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Ninja = {'name': 'Ninja','HP1': 20,'HP2': 30,'HP3': 40,'HP4': 55,'Atk1L1': 4,'Atk1L2': 5,'Atk1L3': 5,'Atk1L4': 7,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 3,'Atk1L4dmg': 3,'Atk2L1': 3,'Atk2L2': 4,'Atk2L3': 5,'Atk2L4': 6,'Atk2L1dmg': 3,'Atk2L2dmg': 4,'Atk2L3dmg': 5,'Atk2L4dmg': 6,'Atk3L1': 2,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 3,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 4,'Dfns2': 5,'Dfns3': 6,'Dfns4': 7,}
Ogre = {'name': 'Ogre','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
OozeMonster = {'name': 'Ooze Monster','HP1': 30,'HP2': 40,'HP3': 60,'HP4': 90,'Atk1L1': 4,'Atk1L2': 5,'Atk1L3': 6,'Atk1L4': 7,'Atk1L1dmg': 1,'Atk1L2dmg': 1,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 3,'Atk2L1dmg': 2,'Atk2L2dmg': 2,'Atk2L3dmg': 3,'Atk2L4dmg': 3,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 2,'Atk3L1dmg': 4,'Atk3L2dmg': 4,'Atk3L3dmg': 6,'Atk3L4dmg': 7,'Dfns1': 1,'Dfns2': 2,'Dfns3': 3,'Dfns4': 3,}
Orc = {'name': 'Orc','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Pirate = {'name': 'Pirate','HP1': 20,'HP2': 30,'HP3': 40,'HP4': 45,'Atk1L1': 4,'Atk1L2': 5,'Atk1L3': 5,'Atk1L4': 6,'Atk1L1dmg': 2,'Atk1L2dmg': 3,'Atk1L3dmg': 3,'Atk1L4dmg': 4,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 3,'Atk2L2dmg': 3,'Atk2L3dmg': 4,'Atk2L4dmg': 5,'Atk3L1': 2,'Atk3L2': 3,'Atk3L3': 3,'Atk3L4': 4,'Atk3L1dmg': 3,'Atk3L2dmg': 4,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 3,'Dfns2': 4,'Dfns3': 4,'Dfns4': 5,}
PossessedDoll = {'name': 'Possessed Doll','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Robot = {'name': 'Robot','HP1': 63,'HP2': 76,'HP3': 84,'HP4': 102,'Atk1L1': 4,'Atk1L2': 5,'Atk1L3': 5,'Atk1L4': 6,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 3,'Atk2L2': 4,'Atk2L3': 4,'Atk2L4': 5,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 3,'Atk2L4dmg': 4,'Atk3L1': 2,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 3,'Atk3L1dmg': 3,'Atk3L2dmg': 4,'Atk3L3dmg': 5,'Atk3L4dmg': 5,'Dfns1': 2,'Dfns2': 3,'Dfns3': 4,'Dfns4': 4,}
Sasquatch = {'name': 'Sasquatch','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Unicorn = {'name': 'Unicorn','HP1': 25,'HP2': 35,'HP3': 50,'HP4': 85,'Atk1L1': 3,'Atk1L2': 4,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 2,'Atk1L2dmg': 2,'Atk1L3dmg': 3,'Atk1L4dmg': 4,'Atk2L1': 3,'Atk2L2': 4,'Atk2L3': 5,'Atk2L4': 6,'Atk2L1dmg': 3,'Atk2L2dmg': 4,'Atk2L3dmg': 5,'Atk2L4dmg': 5,'Atk3L1': 2,'Atk3L2': 3,'Atk3L3': 4,'Atk3L4': 5,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 6,'Atk3L4dmg': 7,'Dfns1': 4,'Dfns2': 5,'Dfns3': 6,'Dfns4': 7,}
Vampire = {'name': 'Vampire','HP1': 40,'HP2': 50,'HP3': 75,'HP4': 95,'Atk1L1': 4,'Atk1L2': 5,'Atk1L3': 5,'Atk1L4': 6,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 3,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 4,'Atk2L4dmg': 4,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 3,'Atk3L2dmg': 4,'Atk3L3dmg': 5,'Atk3L4dmg': 5,'Dfns1': 3,'Dfns2': 4,'Dfns3': 5,'Dfns4': 6,}
Werewolf = {'name': 'Werewolf','HP1': 25,'HP2': 30,'HP3': 50,'HP4': 75,'Atk1L1': 4,'Atk1L2': 4,'Atk1L3': 5,'Atk1L4': 6,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 3,'Atk1L4dmg': 3,'Atk2L1': 3,'Atk2L2': 3,'Atk2L3': 4,'Atk2L4': 5,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 3,'Atk2L4dmg': 3,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 4,'Atk3L1dmg': 4,'Atk3L2dmg': 4,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 4,'Dfns2': 5,'Dfns3': 6,'Dfns4': 7,}
Witch = {'name': 'Witch','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Wizard = {'name': 'Wizard','HP1': 40,'HP2': 60,'HP3': 90,'HP4': 115,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 1,'Atk1L3dmg': 2,'Atk1L4dmg': 2,'Atk2L1': 2,'Atk2L2': 3,'Atk2L3': 4,'Atk2L4': 4,'Atk2L1dmg': 4,'Atk2L2dmg': 4,'Atk2L3dmg': 5,'Atk2L4dmg': 6,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 3,'Atk3L4': 3,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 4,'Dfns2': 5,'Dfns3': 6,'Dfns4': 6,}
Yeti = {'name': 'Yeti','HP1': 30,'HP2': 35,'HP3': 55,'HP4': 80,'Atk1L1': 3,'Atk1L2': 4,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 3,'Atk1L4dmg': 4,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 3,'Atk2L2dmg': 3,'Atk2L3dmg': 4,'Atk2L4dmg': 5,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 3,'Dfns2': 3,'Dfns3': 4,'Dfns4': 5,}
Zombie = {'name': 'Zombie','HP1': 49,'HP2': 60,'HP3': 90,'HP4': 120,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 4,'Atk2L4dmg': 4,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 3,'Atk3L2dmg': 4,'Atk3L3dmg': 4,'Atk3L4dmg': 5,'Dfns1': 1,'Dfns2': 2,'Dfns3': 2,'Dfns4': 3,}
import random
def pickmonster (slotnumber):
global position
if slotnumber == 1: position = Cyclops
if slotnumber == 2: position = Genie
if slotnumber == 3: position = GiantApe
if slotnumber == 4: position = GiantLizard
if slotnumber == 5: position = GreyAlien
if slotnumber == 6: position = Leprechaun
if slotnumber == 7: position = Medusa
if slotnumber == 8: position = Ninja
if slotnumber == 9: position = OozeMonster
if slotnumber == 10: position = Pirate
if slotnumber == 11: position = Robot
if slotnumber == 12: position = Unicorn
if slotnumber == 13: position = Vampire
if slotnumber == 14: position = Werewolf
if slotnumber == 15: position = Wizard
if slotnumber == 16: position = Zombie
pickednumbers = []
def slotseeder ():
global randomnumber
randomnumber = (random.randrange(1,16))
if randomnumber in pickednumbers:
t = 1
else:
pickednumbers.append(randomnumber)
pickmonster (randomnumber)
slotseeder
P01 = position
print P01
A:
There is several problems in the code. Like you are not calling function if it is not followed by opening and closing parenthesis.
ie: not slotseeder but slotseeder()
(That is the one that breaks the code)
I would probably write your sample code as below:
### Monster Statistics ####
default_stats = dict(name='unknown',
HP=[0, 0, 0, 0],
Atk1=[0, 0, 0, 0], Atk1dmg=[0, 0, 0, 0],
Atk2=[0, 0, 0, 0], Atk2dmg=[0, 0, 0, 0],
Atk3=[0, 0, 0, 0], Atk3dmg=[0, 0, 0, 0],
Dfns=[0, 0, 0, 0])
Monsters = [dict(default_stats, name='Cerebus'),
dict(default_stats, name='Cthulhu'),
dict(default_stats, name='Cyclops',
HP=[65, 85, 95, 130],
Atk1=[3, 4, 4, 5], Atk1dmg=[3, 4, 4, 5],
Atk2=[2, 3, 3, 4], Atk2dmg=[5, 6, 6, 7],
Atk3=[1, 2, 3, 3], Atk3dmg=[5, 6, 6, 7],
Dfns=[2, 3, 4, 5]),
dict(default_stats, name='Genie'),
dict(default_stats, name='Giant Ape',
HP=[70, 90, 110, 140],
Atk1=[3, 4, 4, 5], Atk1dmg=[4, 5, 5, 6],
Atk2=[2, 2, 3, 4], Atk2dmg=[5, 6, 6, 7],
Atk3=[1, 2, 3, 3], Atk3dmg=[6, 6, 7, 8],
Dfns=[2, 3, 3, 4]),
dict(default_stats, name='Giant Lizard',
HP=[80, 100, 130, 170],
Atk1=[3, 3, 4, 5], Atk1dmg=[3, 4, 5, 6],
Atk2=[2, 3, 3, 4], Atk2dmg=[4, 5, 6, 7],
Atk3=[1, 2, 2, 3], Atk3dmg=[6, 7, 8, 8],
Dfns=[1, 2, 2, 3]),
dict(default_stats, name='Grey Alien',
HP=[30, 40, 45, 50],
Atk1=[3, 3, 4, 5], Atk1dmg=[1, 2, 2, 3],
Atk2=[2, 2, 3, 4], Atk2dmg=[2, 3, 3, 4],
Atk3=[1, 2, 3, 4], Atk3dmg=[4, 5, 5, 6],
Dfns=[3, 4, 4, 5]),
dict(default_stats, name='Gryffin'),
dict(name='Leprechaun',
HP=[30, 35, 50, 65],
Atk1=[3, 4, 4, 5], Atk1dmg=[1, 1, 2, 3],
Atk2=[2, 3, 4, 5], Atk2dmg=[2, 2, 3, 4],
Atk3=[1, 2, 3, 4], Atk3dmg=[4, 5, 6, 6],
Dfns=[4, 6, 7, 8]),
dict(default_stats, name='Medusa',
HP=[20, 30, 45, 50],
Atk1=[3, 3, 4, 4], Atk1dmg=[1, 2, 2, 3],
Atk2=[2, 2, 3, 4], Atk2dmg=[2, 2, 3, 3],
Atk3=[1, 1, 2, 3], Atk3dmg=[4, 5, 5, 6],
Dfns=[2, 3, 4, 4]),
dict(default_stats, name='Minotaur'),
dict(default_stats, name='Ninja',
HP=[20, 30, 40, 55],
Atk1=[4, 5, 5, 7], Atk1dmg=[1, 2, 3, 3],
Atk2=[3, 4, 5, 6], Atk2dmg=[3, 4, 5, 6],
Atk3=[2, 2, 3, 3], Atk3dmg=[4, 5, 5, 6],
Dfns=[4, 5, 6, 7]),
dict(default_stats, name='Ogre'),
dict(default_stats, name='Ooze Monster',
HP=[30, 40, 60, 90],
Atk1=[4, 5, 6, 7], Atk1dmg=[1, 1, 2, 3],
Atk2=[2, 2, 3, 3], Atk2dmg=[2, 2, 3, 3],
Atk3=[1, 1, 2, 2], Atk3dmg=[4, 4, 6, 7],
Dfns=[1, 2, 3, 3]),
dict(default_stats, name='Orc'),
dict(default_stats, name='Pirate',
HP=[20, 30, 40, 45],
Atk1=[4, 5, 5, 6], Atk1dmg=[2, 3, 3, 4],
Atk2=[2, 2, 3, 4], Atk2dmg=[3, 3, 4, 5],
Atk3=[2, 3, 3, 4], Atk3dmg=[3, 4, 5, 6],
Dfns=[3, 4, 4, 5]),
dict(default_stats, name='Possessed Doll'),
dict(default_stats, name='Robot',
HP=[63, 76, 84, 102],
Atk1=[4, 5, 5, 6], Atk1dmg=[1, 2, 2, 3],
Atk2=[3, 4, 4, 5], Atk2dmg=[2, 3, 3, 4],
Atk3=[2, 2, 3, 3], Atk3dmg=[3, 4, 5, 5],
Dfns=[2, 3, 4, 4]),
dict(default_stats, name='Sasquatch'),
dict(name='Unicorn',
HP=[25, 35, 50, 85],
Atk1=[3, 4, 4, 5], Atk1dmg=[2, 2, 3, 4],
Atk2=[3, 4, 5, 6], Atk2dmg=[3, 4, 5, 5],
Atk3=[2, 3, 4, 5], Atk3dmg=[4, 5, 6, 7],
Dfns=[4, 5, 6, 7]),
dict(default_stats, name='Vampire',
HP=[40, 50, 75, 95],
Atk1=[4, 5, 5, 6], Atk1dmg=[1, 2, 2, 3],
Atk2=[2, 3, 3, 4], Atk2dmg=[2, 3, 4, 4],
Atk3=[1, 2, 2, 3], Atk3dmg=[3, 4, 5, 5],
Dfns=[3, 4, 5, 6]),
dict(default_stats, name='Werewolf',
HP=[25, 30, 50, 75],
Atk1=[4, 4, 5, 6], Atk1dmg=[1, 2, 3, 3],
Atk2=[3, 3, 4, 5], Atk2dmg=[2, 3, 3, 3],
Atk3=[1, 1, 2, 4], Atk3dmg=[4, 4, 5, 6],
Dfns=[4, 5, 6, 7]),
dict(default_stats, name='Witch'),
dict(default_stats, name='Wizard',
HP=[40, 60, 90, 115],
Atk1=[3, 3, 4, 5], Atk1dmg=[1, 1, 2, 2],
Atk2=[2, 3, 4, 4], Atk2dmg=[4, 4, 5, 6],
Atk3=[1, 1, 3, 3], Atk3dmg=[4, 5, 5, 6],
Dfns=[4, 5, 6, 6]),
dict(default_stats, name='Yeti',
HP=[30, 35, 55, 80],
Atk1=[3, 4, 4, 5], Atk1dmg=[1, 2, 3, 4],
Atk2=[2, 2, 3, 4], Atk2dmg=[3, 3, 4, 5],
Atk3=[1, 1, 2, 3], Atk3dmg=[4, 5, 5, 6],
Dfns=[3, 3, 4, 5]),
dict(default_stats, name='Zombie',
HP=[49, 60, 90, 120],
Atk1=[3, 3, 4, 5], Atk1dmg=[1, 2, 2, 3],
Atk2=[2, 2, 3, 4], Atk2dmg=[2, 3, 4, 4],
Atk3=[1, 1, 2, 3], Atk3dmg=[3, 4, 4, 5],
Dfns=[1, 2, 2, 3])
]
import random
picked = [monster for monster in Monsters
if monster['name'] in ['Cyclops',
'Genie', 'Giant Ape', 'Giant Lizard',
'Grey Alien', 'Leprechaun', 'Medusa',
'Ninja', 'Ooze Monster', 'Pirate',
'Robot', 'Unicorn', 'Vampire',
'Werewolf', 'Wizard', 'Zombie']]
def slotseeder ():
randomnumber = (random.randrange(0,len(picked)))
if picked[randomnumber] != None:
pickedmonster = Monsters[randomnumber]
picked[randomnumber] = None
return pickedmonster
P01 = slotseeder()
if P01 is not None:
print "I got monster:", P01
else:
print "Monster already used"
As you can see, the main change is in the data structure.
put all the monsters in one unique list. There is no point in using a different variable name for each. It just makes code harder to write when you want to pick a monster later.
I changed the dict initialisation syntax, the other one uses too much quotes for my taste.
also added default dictionary, it is handy to show which monsters are really defined or not, could also be used as template if some monsters are close enough.
replaced lists of numbered variables (like HP1, HP2, HP3, etc) with real lists. That's what lists are designed for. That slightly change access syntax, but it opens new possibilities. The same kind of change can probably be done for Atk levels as there is also numbered variables, but names suggests also that Atk1 and Atk1dmg may be combined as a tuple. I leave it to reader to still enhance the structure.
I believe the result is much easier to read than the initial one.
That is just a possibility. Another one could be to use a dictionary with monster name as key for all monsters. It would probably be even better than the above, and also defining a real Monster class would probably be a better idea than using dict(). But one step every day is enough.
After changing the data structure, changes to code are easy. I leave you figure it out. Just one last detail about initial program: it would never got a Zombie (because of randrange behavior). I figured it was a bug and changed it.
Have fun with python :-)
note: If you wonder if I really edited the monstruous initial structure, the answer is no. I wrote a program to do it for me. Well, I used some inline Perl for that purpose as it was faster than writing it using Python. I know. I'm evil.
A:
May I suggest writing the ifs as something like:
monsters = [Cyclops, Genie, GiantApe, GiantLizard, GreyAlien, Leprechaun, Medusa, Ninja, OozeMonster, Pirate, Robot, Unicorn, Vampire, Werewolf, Wizard, Zombie]
monster = monsters[randomnumber-1]
A:
I see you didn't declare position in the outer scope at all. Declare position before the function declarations, and you should be ok.
A:
To use a global variable, first create it globally (outside of all classes and functions), then declare it as global locally (with global keyword) so you can assign to it.
Here's a shortened version of your code that does it right:
>>> Cyclops = "data for Cyclops"
... position = "" # declares position in global scope
... def pickmonster ():
... global position # tells python that the local variable 'position' refers to the global 'position'
... position = Cyclops
... pickmonster()
... print position
data for Cyclops
Do note that use of global variables is generally frowned upon. It would be better to have the function pickmonster return the data you need and keep track of it locally.
| Global Variable Not Defined | I'm calling two separate functions to determine what "P01" equals. The first one selects a random number, and discards random numbers already picked. The second one takes the result of the random number and picks a variable to make 'position' equal. I then say that 'P01' equals 'position.'
I've made 'position' a global variable, but I keep getting an error when I try to assign 'position' to 'P01' saying "position is not defined."
Any ideas?
### Monster Statistics ####
Cerebus = {'name': 'Cerebus','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Cthulhu = {'name': 'Cthulhu','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Cyclops = {'name': 'Cyclops','HP1': 65,'HP2': 85,'HP3': 95,'HP4': 130,'Atk1L1': 3,'Atk1L2': 4,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 3,'Atk1L2dmg': 4,'Atk1L3dmg': 4,'Atk1L4dmg': 5,'Atk2L1': 2,'Atk2L2': 3,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 5,'Atk2L2dmg': 6,'Atk2L3dmg': 6,'Atk2L4dmg': 7,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 3,'Atk3L1dmg': 5,'Atk3L2dmg': 6,'Atk3L3dmg': 6,'Atk3L4dmg': 7,'Dfns1': 2,'Dfns2': 3,'Dfns3': 4,'Dfns4': 5,}
Genie = {'name': 'Genie','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
GiantApe = {'name': 'Giant Ape','HP1': 70,'HP2': 90,'HP3': 110,'HP4': 140,'Atk1L1': 3,'Atk1L2': 4,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 4,'Atk1L2dmg': 5,'Atk1L3dmg': 5,'Atk1L4dmg': 6,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 5,'Atk2L2dmg': 6,'Atk2L3dmg': 6,'Atk2L4dmg': 7,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 3,'Atk3L1dmg': 6,'Atk3L2dmg': 6,'Atk3L3dmg': 7,'Atk3L4dmg': 8,'Dfns1': 2,'Dfns2': 3,'Dfns3': 3,'Dfns4': 4,}
GiantLizard = {'name': 'Giant Lizard','HP1': 80,'HP2': 100,'HP3': 130,'HP4': 170,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 3,'Atk1L2dmg': 4,'Atk1L3dmg': 5,'Atk1L4dmg': 6,'Atk2L1': 2,'Atk2L2': 3,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 4,'Atk2L2dmg': 5,'Atk2L3dmg': 6,'Atk2L4dmg': 7,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 6,'Atk3L2dmg': 7,'Atk3L3dmg': 8,'Atk3L4dmg': 8,'Dfns1': 1,'Dfns2': 2,'Dfns3': 2,'Dfns4': 3,}
GreyAlien = {'name': 'Grey Alien','HP1': 30,'HP2': 40,'HP3': 45,'HP4': 50,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 3,'Atk2L4dmg': 4,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 4,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 3,'Dfns2': 4,'Dfns3': 4,'Dfns4': 5,}
Gryffin = {'name': 'Gryffin','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Leprechaun = {'name': 'Leprechaun','HP1': 30,'HP2': 35,'HP3': 50,'HP4': 65,'Atk1L1': 3,'Atk1L2': 4,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 1,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 3,'Atk2L3': 4,'Atk2L4': 5,'Atk2L1dmg': 2,'Atk2L2dmg': 2,'Atk2L3dmg': 3,'Atk2L4dmg': 4,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 4,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 6,'Atk3L4dmg': 6,'Dfns1': 4,'Dfns2': 6,'Dfns3': 7,'Dfns4': 8,}
Medusa = {'name': 'Medusa','HP1': 20,'HP2': 30,'HP3': 45,'HP4': 50,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 4,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 2,'Atk2L2dmg': 2,'Atk2L3dmg': 3,'Atk2L4dmg': 3,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 2,'Dfns2': 3,'Dfns3': 4,'Dfns4': 4,}
Minotaur = {'name': 'Minotaur','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Ninja = {'name': 'Ninja','HP1': 20,'HP2': 30,'HP3': 40,'HP4': 55,'Atk1L1': 4,'Atk1L2': 5,'Atk1L3': 5,'Atk1L4': 7,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 3,'Atk1L4dmg': 3,'Atk2L1': 3,'Atk2L2': 4,'Atk2L3': 5,'Atk2L4': 6,'Atk2L1dmg': 3,'Atk2L2dmg': 4,'Atk2L3dmg': 5,'Atk2L4dmg': 6,'Atk3L1': 2,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 3,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 4,'Dfns2': 5,'Dfns3': 6,'Dfns4': 7,}
Ogre = {'name': 'Ogre','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
OozeMonster = {'name': 'Ooze Monster','HP1': 30,'HP2': 40,'HP3': 60,'HP4': 90,'Atk1L1': 4,'Atk1L2': 5,'Atk1L3': 6,'Atk1L4': 7,'Atk1L1dmg': 1,'Atk1L2dmg': 1,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 3,'Atk2L1dmg': 2,'Atk2L2dmg': 2,'Atk2L3dmg': 3,'Atk2L4dmg': 3,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 2,'Atk3L1dmg': 4,'Atk3L2dmg': 4,'Atk3L3dmg': 6,'Atk3L4dmg': 7,'Dfns1': 1,'Dfns2': 2,'Dfns3': 3,'Dfns4': 3,}
Orc = {'name': 'Orc','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Pirate = {'name': 'Pirate','HP1': 20,'HP2': 30,'HP3': 40,'HP4': 45,'Atk1L1': 4,'Atk1L2': 5,'Atk1L3': 5,'Atk1L4': 6,'Atk1L1dmg': 2,'Atk1L2dmg': 3,'Atk1L3dmg': 3,'Atk1L4dmg': 4,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 3,'Atk2L2dmg': 3,'Atk2L3dmg': 4,'Atk2L4dmg': 5,'Atk3L1': 2,'Atk3L2': 3,'Atk3L3': 3,'Atk3L4': 4,'Atk3L1dmg': 3,'Atk3L2dmg': 4,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 3,'Dfns2': 4,'Dfns3': 4,'Dfns4': 5,}
PossessedDoll = {'name': 'Possessed Doll','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Robot = {'name': 'Robot','HP1': 63,'HP2': 76,'HP3': 84,'HP4': 102,'Atk1L1': 4,'Atk1L2': 5,'Atk1L3': 5,'Atk1L4': 6,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 3,'Atk2L2': 4,'Atk2L3': 4,'Atk2L4': 5,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 3,'Atk2L4dmg': 4,'Atk3L1': 2,'Atk3L2': 2,'Atk3L3': 3,'Atk3L4': 3,'Atk3L1dmg': 3,'Atk3L2dmg': 4,'Atk3L3dmg': 5,'Atk3L4dmg': 5,'Dfns1': 2,'Dfns2': 3,'Dfns3': 4,'Dfns4': 4,}
Sasquatch = {'name': 'Sasquatch','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Unicorn = {'name': 'Unicorn','HP1': 25,'HP2': 35,'HP3': 50,'HP4': 85,'Atk1L1': 3,'Atk1L2': 4,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 2,'Atk1L2dmg': 2,'Atk1L3dmg': 3,'Atk1L4dmg': 4,'Atk2L1': 3,'Atk2L2': 4,'Atk2L3': 5,'Atk2L4': 6,'Atk2L1dmg': 3,'Atk2L2dmg': 4,'Atk2L3dmg': 5,'Atk2L4dmg': 5,'Atk3L1': 2,'Atk3L2': 3,'Atk3L3': 4,'Atk3L4': 5,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 6,'Atk3L4dmg': 7,'Dfns1': 4,'Dfns2': 5,'Dfns3': 6,'Dfns4': 7,}
Vampire = {'name': 'Vampire','HP1': 40,'HP2': 50,'HP3': 75,'HP4': 95,'Atk1L1': 4,'Atk1L2': 5,'Atk1L3': 5,'Atk1L4': 6,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 3,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 4,'Atk2L4dmg': 4,'Atk3L1': 1,'Atk3L2': 2,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 3,'Atk3L2dmg': 4,'Atk3L3dmg': 5,'Atk3L4dmg': 5,'Dfns1': 3,'Dfns2': 4,'Dfns3': 5,'Dfns4': 6,}
Werewolf = {'name': 'Werewolf','HP1': 25,'HP2': 30,'HP3': 50,'HP4': 75,'Atk1L1': 4,'Atk1L2': 4,'Atk1L3': 5,'Atk1L4': 6,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 3,'Atk1L4dmg': 3,'Atk2L1': 3,'Atk2L2': 3,'Atk2L3': 4,'Atk2L4': 5,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 3,'Atk2L4dmg': 3,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 4,'Atk3L1dmg': 4,'Atk3L2dmg': 4,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 4,'Dfns2': 5,'Dfns3': 6,'Dfns4': 7,}
Witch = {'name': 'Witch','HP1': 0,'HP2': 0,'HP3': 0,'HP4': 0,'Atk1L1': 0,'Atk1L2': 0,'Atk1L3': 0,'Atk1L4': 0,'Atk1L1dmg': 0,'Atk1L2dmg': 0,'Atk1L3dmg': 0,'Atk1L4dmg': 0,'Atk2L1': 0,'Atk2L2': 0,'Atk2L3': 0,'Atk2L4': 0,'Atk2L1dmg': 0,'Atk2L2dmg': 0,'Atk2L3dmg': 0,'Atk2L4dmg': 0,'Atk3L1': 0,'Atk3L2': 0,'Atk3L3': 0,'Atk3L4': 0,'Atk3L1dmg': 0,'Atk3L2dmg': 0,'Atk3L3dmg': 0,'Atk3L4dmg': 0,'Dfns1': 0,'Dfns2': 0,'Dfns3': 0,'Dfns4': 0,}
Wizard = {'name': 'Wizard','HP1': 40,'HP2': 60,'HP3': 90,'HP4': 115,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 1,'Atk1L3dmg': 2,'Atk1L4dmg': 2,'Atk2L1': 2,'Atk2L2': 3,'Atk2L3': 4,'Atk2L4': 4,'Atk2L1dmg': 4,'Atk2L2dmg': 4,'Atk2L3dmg': 5,'Atk2L4dmg': 6,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 3,'Atk3L4': 3,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 4,'Dfns2': 5,'Dfns3': 6,'Dfns4': 6,}
Yeti = {'name': 'Yeti','HP1': 30,'HP2': 35,'HP3': 55,'HP4': 80,'Atk1L1': 3,'Atk1L2': 4,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 3,'Atk1L4dmg': 4,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 3,'Atk2L2dmg': 3,'Atk2L3dmg': 4,'Atk2L4dmg': 5,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 4,'Atk3L2dmg': 5,'Atk3L3dmg': 5,'Atk3L4dmg': 6,'Dfns1': 3,'Dfns2': 3,'Dfns3': 4,'Dfns4': 5,}
Zombie = {'name': 'Zombie','HP1': 49,'HP2': 60,'HP3': 90,'HP4': 120,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 4,'Atk2L4dmg': 4,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 3,'Atk3L2dmg': 4,'Atk3L3dmg': 4,'Atk3L4dmg': 5,'Dfns1': 1,'Dfns2': 2,'Dfns3': 2,'Dfns4': 3,}
import random
def pickmonster (slotnumber):
global position
if slotnumber == 1: position = Cyclops
if slotnumber == 2: position = Genie
if slotnumber == 3: position = GiantApe
if slotnumber == 4: position = GiantLizard
if slotnumber == 5: position = GreyAlien
if slotnumber == 6: position = Leprechaun
if slotnumber == 7: position = Medusa
if slotnumber == 8: position = Ninja
if slotnumber == 9: position = OozeMonster
if slotnumber == 10: position = Pirate
if slotnumber == 11: position = Robot
if slotnumber == 12: position = Unicorn
if slotnumber == 13: position = Vampire
if slotnumber == 14: position = Werewolf
if slotnumber == 15: position = Wizard
if slotnumber == 16: position = Zombie
pickednumbers = []
def slotseeder ():
global randomnumber
randomnumber = (random.randrange(1,16))
if randomnumber in pickednumbers:
t = 1
else:
pickednumbers.append(randomnumber)
pickmonster (randomnumber)
slotseeder
P01 = position
print P01
| [
"There is several problems in the code. Like you are not calling function if it is not followed by opening and closing parenthesis.\nie: not slotseeder but slotseeder()\n(That is the one that breaks the code)\nI would probably write your sample code as below:\n### Monster Statistics ####\n\ndefault_stats = dict(nam... | [
5,
1,
0,
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0003373560_python_random.txt |
Q:
Python to recognize UNC path on cygwin
All machines are on Windows Server 2003.
If I only install cygwin on one of the machine and run my python script on it to manipulate files from all remote hosts. How can I access to those files via UNC path?
A:
Cygwin understands UNC pathnames that use two forward slashes (as opposed to the two backslashes typical of Windows -- in fact, under Cygwin, you must use forward slashes instead of backslashes anywhere in the path). I assume that this support would be propagated through to Python running on top of Cygwin, but I haven't ever tried it to confirm.
Edit: if you don't need to run python under cygwin, as you mention in a comment, then why are you doing so? Just install the native windows python from the python download site and forget about Cygwin. You'll probably have to double your backslashes in the path names, however, since IIRC Python uses backslash as an escape character, so to get one backslash in the final string you need to put in two.
| Python to recognize UNC path on cygwin | All machines are on Windows Server 2003.
If I only install cygwin on one of the machine and run my python script on it to manipulate files from all remote hosts. How can I access to those files via UNC path?
| [
"Cygwin understands UNC pathnames that use two forward slashes (as opposed to the two backslashes typical of Windows -- in fact, under Cygwin, you must use forward slashes instead of backslashes anywhere in the path). I assume that this support would be propagated through to Python running on top of Cygwin, but I ... | [
4
] | [] | [] | [
"cygwin",
"python"
] | stackoverflow_0003374365_cygwin_python.txt |
Q:
Python and Excel: Overwriting an existing file always prompts, despite XlSaveConflictResolution value
I'm using the Excel.Application COM object from a Python program to open a CSV file and save it as an Excel workbook. If the target file already exists, then I am prompted with this message: "A file named '...' already exists in this location. Do you want to replace it?" That message comes up despite the fact that I have set the XlSaveConflictResolution value to xlLocalSessionChanges, which is supposed to automatically overwrite the changes without prompting -- or so I thought.
I'm using Microsoft Office Excel 2007 (12.0.6535.5002) SP2 MSO and ActivePython 2.6.5.14. I have tried all three of the XlSaveConflictResolution values using both constants and integers. I have not tried different versions of Excel.
Here's a code snippet:
import win32com.client
xl = win32com.client.gencache.EnsureDispatch("Excel.Application")
wb = xl.Workbooks.Open(r"C:\somefile.csv")
wb.SaveAs(r"C:\somefile.xls", win32com.client.constants.xlWorkbookNormal, \
None, None, False, False, win32com.client.constants.xlNoChange, \
win32com.client.constants.xlLocalSessionChanges)
And here's the spec from Microsoft about the SaveAs method for an Excel workbook object: http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.saveas(VS.80).aspx
Could this be a new "feature" in Excel 2007, or did I just do something wrong?
A:
Before saving the file set DisplayAlerts to False to suppress the warning dialog:
xl.DisplayAlerts = False
After the file is saved it is usually a good idea to set DisplayAlerts back to True:
xl.DisplayAlerts = True
| Python and Excel: Overwriting an existing file always prompts, despite XlSaveConflictResolution value | I'm using the Excel.Application COM object from a Python program to open a CSV file and save it as an Excel workbook. If the target file already exists, then I am prompted with this message: "A file named '...' already exists in this location. Do you want to replace it?" That message comes up despite the fact that I have set the XlSaveConflictResolution value to xlLocalSessionChanges, which is supposed to automatically overwrite the changes without prompting -- or so I thought.
I'm using Microsoft Office Excel 2007 (12.0.6535.5002) SP2 MSO and ActivePython 2.6.5.14. I have tried all three of the XlSaveConflictResolution values using both constants and integers. I have not tried different versions of Excel.
Here's a code snippet:
import win32com.client
xl = win32com.client.gencache.EnsureDispatch("Excel.Application")
wb = xl.Workbooks.Open(r"C:\somefile.csv")
wb.SaveAs(r"C:\somefile.xls", win32com.client.constants.xlWorkbookNormal, \
None, None, False, False, win32com.client.constants.xlNoChange, \
win32com.client.constants.xlLocalSessionChanges)
And here's the spec from Microsoft about the SaveAs method for an Excel workbook object: http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.saveas(VS.80).aspx
Could this be a new "feature" in Excel 2007, or did I just do something wrong?
| [
"Before saving the file set DisplayAlerts to False to suppress the warning dialog:\nxl.DisplayAlerts = False\n\nAfter the file is saved it is usually a good idea to set DisplayAlerts back to True: \n xl.DisplayAlerts = True\n\n"
] | [
19
] | [] | [] | [
"activex",
"com",
"excel",
"excel_2007",
"python"
] | stackoverflow_0003373955_activex_com_excel_excel_2007_python.txt |
Q:
(Python) Closure created when it wasn't expected
I got an unexpected closure when creating a nested class. I suspect that this is something related to metaclasses, super, or both. It is definitely related to how closures get created. I am using python2.7.
Here are five simplified examples that demonstrate the same problem that I am seeing (they all build off the first):
EXAMPLE 1:
class Metaclass(type):
def __init__(self, name, bases, dict):
self.CONST = 5
class Base(object):
__metaclass__=Metaclass
def __init__(self):
"Set things up."
class Subclass(Base):
def __init__(self, name):
super(Subclass, self).__init__(self)
self.name = name
def other(self, something): pass
class Test(object):
def setup(self):
class Subclass(Base):
def __init__(self, name):
super(Subclass, self).__init__(self)
self.name = name
def other(self, something): pass
self.subclass = Subclass
class Subclass2(Base):
def __init__(self, name):
super(Subclass, self).__init__(self)
self.subclass2 = Subclass2
"0x%x" % id(Metaclass)
# '0x8257f74'
"0x%x" % id(Base)
# '0x825814c'
t=Test()
t.setup()
"0x%x" % id(t.subclass)
# '0x8258e8c'
"0x%x" % id(t.subclass2)
# '0x825907c'
t.subclass.__init__.__func__.__closure__
# (<cell at 0xb7d33d4c: Metaclass object at 0x8258e8c>,)
t.subclass.other.__func__.__closure__
# None
t.subclass2.__init__.__func__.__closure__
# (<cell at 0xb7d33d4c: Metaclass object at 0x8258e8c>,)
Subclass.__init__.__func__.__closure__
# None
EXAMPLE 2:
class Test2(object):
def setup(self):
class Subclass(Base):
def __init__(self, name):
self.name = name
def other(self, something): pass
self.subclass = Subclass
t2=Test2()
t2.setup()
t2.subclass.__init__.__func__.__closure__
# None
EXAMPLE 3:
class Test3(object):
def setup(self):
class Other(object):
def __init__(self):
super(Other, self).__init__()
self.other = Other
class Other2(object):
def __init__(self): pass
self.other2 = Other2
t3=Test3()
t3.setup()
"0x%x" % id(t3.other)
# '0x8259734'
t3.other.__init__.__func__.__closure__
# (<cell at 0xb7d33e54: type object at 0x8259734>,)
t3.other2.__init__.__func__.__closure__
# None
EXAMPLE 4:
class Metaclass2(type): pass
class Base2(object):
__metaclass__=Metaclass2
def __init__(self):
"Set things up."
class Base3(object):
__metaclass__=Metaclass2
class Test4(object):
def setup(self):
class Subclass2(Base2):
def __init__(self, name):
super(Subclass2, self).__init__(self)
self.subclass2 = Subclass2
class Subclass3(Base3):
def __init__(self, name):
super(Subclass3, self).__init__(self)
self.subclass3 = Subclass3
class Subclass4(Base3):
def __init__(self, name):
super(Subclass4, self).__init__(self)
self.subclass4 = Subclass4
"0x%x" % id(Metaclass2)
# '0x8259d9c'
"0x%x" % id(Base2)
# '0x825ac9c'
"0x%x" % id(Base3)
# '0x825affc'
t4=Test4()
t4.setup()
"0x%x" % id(t4.subclass2)
# '0x825b964'
"0x%x" % id(t4.subclass3)
# '0x825bcac'
"0x%x" % id(t4.subclass4)
# '0x825bff4'
t4.subclass2.__init__.__func__.__closure__
# (<cell at 0xb7d33d04: Metaclass2 object at 0x825b964>,)
t4.subclass3.__init__.__func__.__closure__
# (<cell at 0xb7d33e9c: Metaclass2 object at 0x825bcac>,)
t4.subclass4.__init__.__func__.__closure__
# (<cell at 0xb7d33ddc: Metaclass2 object at 0x825bff4>,)
EXAMPLE 5:
class Test5(object):
def setup(self):
class Subclass(Base):
def __init__(self, name):
Base.__init__(self)
self.subclass = Subclass
t5=Test5()
t5.setup()
"0x%x" % id(t5.subclass)
# '0x8260374'
t5.subclass.__init__.__func__.__closure__
# None
Here is what I understand (referencing examples):
Metaclasses are inherited, so Subclass gets Base’s metaclass.
Only __init__ is affected, Subclass.other method is not (#1).
Removing Subclass.other does not make a difference (#1).
Removing self.name=name from Subclass.__init__ does not make a difference (#1).
The object in the closure cell is not a function.
The object is not Metaclass or Base, but some object of type Metaclass, just like Base is (#1).
The object is actually an object of the type of the nested Subclass (#1).
The closure cells for t1.subclass.__init__ and t1.subclass2.__init__ are the same, even though they are from two different classes (#1).
When I do not nest the creation of Subclass (#1) then there is no closure created.
When I do not call super(...).__init__ in Subclass.init__ no closure is created (#2).
If I assign no __metaclass__ and inherit from object then the same behavior shows up (#3).
The object in the closure cell for t3.other.__init__ is t3.other (#3).
The same behavior happens if the metaclass has no __init__ (#4).
The same behavior happens if the Base has no __init__ (#4).
The closure cells for the three subclasses in example 4 are all different and each matches the corresponding class (#4).
When super(...).__init__ is replaced with Base.__init__(self), the closure disappears (#5).
Here is what I do not understand:
Why does a closure get set for __init__?
Why doesn't the closure get set for other?
Why is the object in the closure cell set to the class to which __init__ belongs?
Why does this only happen when super(...).__init__ is called?
Why doesn't this happen when Base.__init__(self) is called?
Does this actually have anything at all to do with using metaclasses (probably, since the default metaclass is type)?
Thanks for the help!
-eric
(Update) Here is something that I found then (based on Jason's insight):
def something1():
print "0x%x" % id(something1)
def something2():
def something3():
print "0x%x" % id(something1)
print "0x%x" % id(something2)
print "0x%x" % id(something3)
return something3
return something2
something1.__closure__
# None
something1().__closure__
# 0xb7d4056c
# (<cell at 0xb7d33eb4: function object at 0xb7d40df4>,)
something1()().__closure__
# 0xb7d4056c
# (<cell at 0xb7d33fec: function object at 0xb7d40e64>, <cell at 0xb7d33efc: function object at 0xb7d40e2c>)
something1()()()
# 0xb7d4056c
# 0xb7d4056c
# 0xb7d40e9c
# 0xb7d40ed4
First, a function's name is in scope within its own body. Second, functions get closures for the functions in which they are defined if they reference those functions.
I hadn't realized that the function name was in scope like that. The same goes for classes. When a class is defined within a function's scope, any references to that class name inside the class's methods cause the class to bound in a closure on that method's function, like so:
def test():
class Test(object):
def something(self):
print Test
return Test
test()
# <class '__main__.Test'>
test().something.__func__.__closure__
# (<cell at 0xb7d33c2c: type object at 0x825e304>,)
However, since closures cannot be created on non-functions the following fails:
def test():
class Test(object):
SELF=Test
def something(self):
print Test
return Test
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "<stdin>", line 2, in test
# File "<stdin>", line 3, in Test
# NameError: free variable 'Test' referenced before assignment in enclosing scope
Good stuff!
A:
Why does a closure get set for __init__?
It refers to a local variable (namely Subclass) in the enclosing function (namely setup).
Why doesn't the closure get set for other?
Because it doesn't refer to any local variables (or parameters) in any enclosing functions.
Why is the object in the closure cell set to the class to which __init__ belongs?
That is the value of the enclosing variable being referred to.
Why does this only happen when super(...).__init__ is called?
Why doesn't this happen when Base.__init__(self) is called?
Because Base is not a local variable in any enclosing function.
Does this actually have anything at all to do with using metaclasses?
No.
| (Python) Closure created when it wasn't expected | I got an unexpected closure when creating a nested class. I suspect that this is something related to metaclasses, super, or both. It is definitely related to how closures get created. I am using python2.7.
Here are five simplified examples that demonstrate the same problem that I am seeing (they all build off the first):
EXAMPLE 1:
class Metaclass(type):
def __init__(self, name, bases, dict):
self.CONST = 5
class Base(object):
__metaclass__=Metaclass
def __init__(self):
"Set things up."
class Subclass(Base):
def __init__(self, name):
super(Subclass, self).__init__(self)
self.name = name
def other(self, something): pass
class Test(object):
def setup(self):
class Subclass(Base):
def __init__(self, name):
super(Subclass, self).__init__(self)
self.name = name
def other(self, something): pass
self.subclass = Subclass
class Subclass2(Base):
def __init__(self, name):
super(Subclass, self).__init__(self)
self.subclass2 = Subclass2
"0x%x" % id(Metaclass)
# '0x8257f74'
"0x%x" % id(Base)
# '0x825814c'
t=Test()
t.setup()
"0x%x" % id(t.subclass)
# '0x8258e8c'
"0x%x" % id(t.subclass2)
# '0x825907c'
t.subclass.__init__.__func__.__closure__
# (<cell at 0xb7d33d4c: Metaclass object at 0x8258e8c>,)
t.subclass.other.__func__.__closure__
# None
t.subclass2.__init__.__func__.__closure__
# (<cell at 0xb7d33d4c: Metaclass object at 0x8258e8c>,)
Subclass.__init__.__func__.__closure__
# None
EXAMPLE 2:
class Test2(object):
def setup(self):
class Subclass(Base):
def __init__(self, name):
self.name = name
def other(self, something): pass
self.subclass = Subclass
t2=Test2()
t2.setup()
t2.subclass.__init__.__func__.__closure__
# None
EXAMPLE 3:
class Test3(object):
def setup(self):
class Other(object):
def __init__(self):
super(Other, self).__init__()
self.other = Other
class Other2(object):
def __init__(self): pass
self.other2 = Other2
t3=Test3()
t3.setup()
"0x%x" % id(t3.other)
# '0x8259734'
t3.other.__init__.__func__.__closure__
# (<cell at 0xb7d33e54: type object at 0x8259734>,)
t3.other2.__init__.__func__.__closure__
# None
EXAMPLE 4:
class Metaclass2(type): pass
class Base2(object):
__metaclass__=Metaclass2
def __init__(self):
"Set things up."
class Base3(object):
__metaclass__=Metaclass2
class Test4(object):
def setup(self):
class Subclass2(Base2):
def __init__(self, name):
super(Subclass2, self).__init__(self)
self.subclass2 = Subclass2
class Subclass3(Base3):
def __init__(self, name):
super(Subclass3, self).__init__(self)
self.subclass3 = Subclass3
class Subclass4(Base3):
def __init__(self, name):
super(Subclass4, self).__init__(self)
self.subclass4 = Subclass4
"0x%x" % id(Metaclass2)
# '0x8259d9c'
"0x%x" % id(Base2)
# '0x825ac9c'
"0x%x" % id(Base3)
# '0x825affc'
t4=Test4()
t4.setup()
"0x%x" % id(t4.subclass2)
# '0x825b964'
"0x%x" % id(t4.subclass3)
# '0x825bcac'
"0x%x" % id(t4.subclass4)
# '0x825bff4'
t4.subclass2.__init__.__func__.__closure__
# (<cell at 0xb7d33d04: Metaclass2 object at 0x825b964>,)
t4.subclass3.__init__.__func__.__closure__
# (<cell at 0xb7d33e9c: Metaclass2 object at 0x825bcac>,)
t4.subclass4.__init__.__func__.__closure__
# (<cell at 0xb7d33ddc: Metaclass2 object at 0x825bff4>,)
EXAMPLE 5:
class Test5(object):
def setup(self):
class Subclass(Base):
def __init__(self, name):
Base.__init__(self)
self.subclass = Subclass
t5=Test5()
t5.setup()
"0x%x" % id(t5.subclass)
# '0x8260374'
t5.subclass.__init__.__func__.__closure__
# None
Here is what I understand (referencing examples):
Metaclasses are inherited, so Subclass gets Base’s metaclass.
Only __init__ is affected, Subclass.other method is not (#1).
Removing Subclass.other does not make a difference (#1).
Removing self.name=name from Subclass.__init__ does not make a difference (#1).
The object in the closure cell is not a function.
The object is not Metaclass or Base, but some object of type Metaclass, just like Base is (#1).
The object is actually an object of the type of the nested Subclass (#1).
The closure cells for t1.subclass.__init__ and t1.subclass2.__init__ are the same, even though they are from two different classes (#1).
When I do not nest the creation of Subclass (#1) then there is no closure created.
When I do not call super(...).__init__ in Subclass.init__ no closure is created (#2).
If I assign no __metaclass__ and inherit from object then the same behavior shows up (#3).
The object in the closure cell for t3.other.__init__ is t3.other (#3).
The same behavior happens if the metaclass has no __init__ (#4).
The same behavior happens if the Base has no __init__ (#4).
The closure cells for the three subclasses in example 4 are all different and each matches the corresponding class (#4).
When super(...).__init__ is replaced with Base.__init__(self), the closure disappears (#5).
Here is what I do not understand:
Why does a closure get set for __init__?
Why doesn't the closure get set for other?
Why is the object in the closure cell set to the class to which __init__ belongs?
Why does this only happen when super(...).__init__ is called?
Why doesn't this happen when Base.__init__(self) is called?
Does this actually have anything at all to do with using metaclasses (probably, since the default metaclass is type)?
Thanks for the help!
-eric
(Update) Here is something that I found then (based on Jason's insight):
def something1():
print "0x%x" % id(something1)
def something2():
def something3():
print "0x%x" % id(something1)
print "0x%x" % id(something2)
print "0x%x" % id(something3)
return something3
return something2
something1.__closure__
# None
something1().__closure__
# 0xb7d4056c
# (<cell at 0xb7d33eb4: function object at 0xb7d40df4>,)
something1()().__closure__
# 0xb7d4056c
# (<cell at 0xb7d33fec: function object at 0xb7d40e64>, <cell at 0xb7d33efc: function object at 0xb7d40e2c>)
something1()()()
# 0xb7d4056c
# 0xb7d4056c
# 0xb7d40e9c
# 0xb7d40ed4
First, a function's name is in scope within its own body. Second, functions get closures for the functions in which they are defined if they reference those functions.
I hadn't realized that the function name was in scope like that. The same goes for classes. When a class is defined within a function's scope, any references to that class name inside the class's methods cause the class to bound in a closure on that method's function, like so:
def test():
class Test(object):
def something(self):
print Test
return Test
test()
# <class '__main__.Test'>
test().something.__func__.__closure__
# (<cell at 0xb7d33c2c: type object at 0x825e304>,)
However, since closures cannot be created on non-functions the following fails:
def test():
class Test(object):
SELF=Test
def something(self):
print Test
return Test
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "<stdin>", line 2, in test
# File "<stdin>", line 3, in Test
# NameError: free variable 'Test' referenced before assignment in enclosing scope
Good stuff!
| [
"\nWhy does a closure get set for __init__?\n\nIt refers to a local variable (namely Subclass) in the enclosing function (namely setup).\n\nWhy doesn't the closure get set for other?\n\nBecause it doesn't refer to any local variables (or parameters) in any enclosing functions.\n\nWhy is the object in the closure ce... | [
4
] | [] | [] | [
"closures",
"nested_class",
"python",
"super"
] | stackoverflow_0003374427_closures_nested_class_python_super.txt |
Q:
How does one put a link / url to the web-site's home page in Django?
In Django templates, is there a variable in the context (e.g. {{ BASE\_URL }}, {{ ROOT\_URL }}, or {{ MEDIA\_URL }} that one can use to link to the home url of a project?
I.e. if Django is running in the root of a project, the variable (let's call it R) {{ R }} in a template would be /. If the root url is a sub-folder http://host/X/ the variable {{ R }} would be /X/ (or http://host/X/).
It seems painfully simple, but I can't find an answer. :) Thank you!
A:
You could give the URL configuration which you're using to handle the home page a name and use that:
urls.py:
from django.conf.urls.defaults import *
urlpatterns = patterns('myproject.views',
url(r'^$', 'index', name='index'),
)
Templates:
<a href="{% url index %}">...
UPDATE: Newer versions of Django require quotation marks around the name of the view:
<a href="{% url 'index' %}">...
This note in the Django Book has some tips about deploying your applications to a subdirectory:
http://www.djangobook.com/en/1.0/chapter20/#cn43
A:
I always use something like <a href="/"> (assuming your home is at the root, of course). I seem to recall looking this up once, and couldn't find a Django variable for this path; at any rate, / seemed pretty easy, anyway.
A:
In your admin, go to "sites" and set the domain.
Pass context_instance=RequestContext(request) to the templates in question.
Now use {{ SITE_URL }} in any of those templates and you're golden.
Chapter 10 of the Django Book has more information than you'll need regading that context processor bit.
A:
(r'^$', 'django.views.generic.simple.redirect_to', {'url': '/home/'}),
works fine :)
| How does one put a link / url to the web-site's home page in Django? | In Django templates, is there a variable in the context (e.g. {{ BASE\_URL }}, {{ ROOT\_URL }}, or {{ MEDIA\_URL }} that one can use to link to the home url of a project?
I.e. if Django is running in the root of a project, the variable (let's call it R) {{ R }} in a template would be /. If the root url is a sub-folder http://host/X/ the variable {{ R }} would be /X/ (or http://host/X/).
It seems painfully simple, but I can't find an answer. :) Thank you!
| [
"You could give the URL configuration which you're using to handle the home page a name and use that:\nurls.py:\nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('myproject.views',\n url(r'^$', 'index', name='index'),\n)\n\nTemplates:\n<a href=\"{% url index %}\">...\n\nUPDATE: Newer versions of... | [
45,
13,
5,
2
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0000226528_django_django_urls_python.txt |
Q:
Why custom types accept ad-hoc attributes in Python (and built-ins don't)?
I'd like to know why one is able to create a new attribute ("new" means "not previously defined in the class body") for an instance of a custom type, but is not able to do the same for a built-in type, like object itself.
A code example:
>>> class SomeClass(object):
... pass
...
>>> sc = SomeClass()
>>> sc.name = "AAA"
>>> sc.name
'AAA'
>>> obj = object()
>>> obj.name = "BBB"
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'object' object has no attribute 'name'
A:
Some objects don't have the __dict__ attribute (which is a dictionary that stores all the custom 'newly defined' attributes). You can emulate the same behaviour using the __slots__ variable (see python reference). When you are subclassing a class with __dict__, the __slots__ variable has no effect. And as you are always subclassing object for new style classes, the object mustn't have __dict__, as that would make it impossible to use __slots__. The classes without __slots__ take less memory and are probably slightly faster.
| Why custom types accept ad-hoc attributes in Python (and built-ins don't)? | I'd like to know why one is able to create a new attribute ("new" means "not previously defined in the class body") for an instance of a custom type, but is not able to do the same for a built-in type, like object itself.
A code example:
>>> class SomeClass(object):
... pass
...
>>> sc = SomeClass()
>>> sc.name = "AAA"
>>> sc.name
'AAA'
>>> obj = object()
>>> obj.name = "BBB"
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'object' object has no attribute 'name'
| [
"Some objects don't have the __dict__ attribute (which is a dictionary that stores all the custom 'newly defined' attributes). You can emulate the same behaviour using the __slots__ variable (see python reference). When you are subclassing a class with __dict__, the __slots__ variable has no effect. And as you are ... | [
6
] | [] | [] | [
"attributes",
"custom_type",
"datamodel",
"python"
] | stackoverflow_0003374502_attributes_custom_type_datamodel_python.txt |
Q:
split a file name
How do i write a python script to split a file name
eg
LN0001_07272010_3.dat
and to rename the file to LN0001_JY_07272010?
also how do i place a '|' and the end of each line in this file(contents) each line is a record?
A:
fn = "LN0001_07272010_3.dat".split('_')
new_fn = '{0}_JY_{1}'.format(fn[0], fn[1])
Update forgot to add "JY" to new_fn
A:
filename="LN0001_07272010_3.dat"
newfilename=filename.split("_")[0]+"_JY_"+filename.split("_")[1]
linearr=[]
for line in open(filename).readlines():
linearr.append(line+"|")
f=open(newfilename, "w")
for line in linearr:
f.write(line)
f.close()
A:
name = "LN0001_07272010_3.dat"
parts = name.split('_') # gives you ["LN0001","07272010","3.dat"]
newname = parts[0] + "_STUFF_" + parts[1] ... etc
For rename you can either use the python filesystem function,
Or you can use python print to spit out a set of rename commands for your OS, capture that to a batch/shell file and AFTER checking that it looks correct - run it.
print "mv ",name,newname # gives; mv LN0001_07272010_3.dat LN0001_JY_07272010
A:
Because in-place operations are usually a bad idea, here is a code that creates a new file leaving the original unchanged:
fn = "LN0001_07272010_3.dat"
fn1, fn2 = fn.split("_")[:2]
new_fn = "_".join([fn1, "JY", fn2])
open(new_fn, "w").writelines(line.rstrip()+"|\n" for line in open(fn))
A:
file_name = 'LN0001_07272010_3.dat'
new_file_name = '{0}_JY_{1}'.format(file_name.split('_')[0], file_name.split('_')[1])
| split a file name | How do i write a python script to split a file name
eg
LN0001_07272010_3.dat
and to rename the file to LN0001_JY_07272010?
also how do i place a '|' and the end of each line in this file(contents) each line is a record?
| [
"fn = \"LN0001_07272010_3.dat\".split('_')\nnew_fn = '{0}_JY_{1}'.format(fn[0], fn[1])\n\nUpdate forgot to add \"JY\" to new_fn\n",
"filename=\"LN0001_07272010_3.dat\"\nnewfilename=filename.split(\"_\")[0]+\"_JY_\"+filename.split(\"_\")[1]\n\nlinearr=[]\nfor line in open(filename).readlines():\n linearr.appen... | [
5,
3,
2,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003373968_python_string.txt |
Q:
How to os.walk deep defaultdict for values?
I have a very large defaultdict(dict) that looks something like this:
data['w']['x']['y']['z']={'a':5,'b':10}
I'm trying to do produce a report that lists the hierarchy of all keys navigated for a particular final dictionary. In other words, I am looking for its "full pathname" as if the last dictionary were the file and the parent pathname were the keys used to find that particular dictionary. In this case, the report would have the following line:
w:x:y:z:a=5:b=10
I like using defaultdict, but one of the problems is pulling material out of a deeply nested defaultdict(dict).
Any help appreciated.
A:
If possible, just flatten the path:
data['w:x:y:z'] = {'a':5, 'b':10}
for path, d in data.items():
print '%s:%s' % (path, ':'.join("%s=%r" % pair for pair in d.items()))
If the depth of the dict is exactly 4 in all cases, you can write this:
for w, wvals in data.items():
for x, xvals in wvals.items():
for y, yvals in xvals.items():
for z, zvals in yvals.items():
print '%s:%s:%s:%s:%s' % (
w, x, y, z,
':'.join("%s=%r" % pair for pair in d.items()))
Otherwise you must resort to recursion.
def dump(data, path=''):
if isinstance(data, defaultdict):
for k, v in data.items():
dump(v, path + k + ":")
else:
print "%s%s" % (path, ':'.join("%s=%r" % pair for pair in d.items()))
dump(data)
| How to os.walk deep defaultdict for values? | I have a very large defaultdict(dict) that looks something like this:
data['w']['x']['y']['z']={'a':5,'b':10}
I'm trying to do produce a report that lists the hierarchy of all keys navigated for a particular final dictionary. In other words, I am looking for its "full pathname" as if the last dictionary were the file and the parent pathname were the keys used to find that particular dictionary. In this case, the report would have the following line:
w:x:y:z:a=5:b=10
I like using defaultdict, but one of the problems is pulling material out of a deeply nested defaultdict(dict).
Any help appreciated.
| [
"If possible, just flatten the path:\ndata['w:x:y:z'] = {'a':5, 'b':10}\n\nfor path, d in data.items():\n print '%s:%s' % (path, ':'.join(\"%s=%r\" % pair for pair in d.items()))\n\nIf the depth of the dict is exactly 4 in all cases, you can write this:\nfor w, wvals in data.items():\n for x, xvals in wvals.i... | [
1
] | [] | [] | [
"dictionary",
"python",
"search"
] | stackoverflow_0003374411_dictionary_python_search.txt |
Q:
Disable verify_exists on models.URLField at runtime?
How can I temporarily turn off verify_exists on a models.URLField at runtime? I would like to skip the check on certain URLs (they block EC2 IPs from their firewall).
I'm interfacing with the model through the ModelForm right now.
A:
class F(forms.Form):
url_field = forms.URLField(verify_exists = True)
form = F({"url_field":"http://blaghblagh.net"})
form.base_fields['url_field'].verify_exists = False
form.is_valid() # returns True
| Disable verify_exists on models.URLField at runtime? | How can I temporarily turn off verify_exists on a models.URLField at runtime? I would like to skip the check on certain URLs (they block EC2 IPs from their firewall).
I'm interfacing with the model through the ModelForm right now.
| [
" class F(forms.Form):\n url_field = forms.URLField(verify_exists = True)\n\nform = F({\"url_field\":\"http://blaghblagh.net\"})\nform.base_fields['url_field'].verify_exists = False\nform.is_valid() # returns True\n\n"
] | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0003374099_django_django_forms_django_models_python.txt |
Q:
modifying a python callable so it calls before() , actual function then after()
I am not sure if this is the best way to have before and after functions be called around a function f1().
class ba(object):
def __init__(self, call, before, after):
self.call = call
self.before = before
self.after = after
def __call__(self, *args):
self.before()
r = self.call(*args)
self.after()
return r
class test1(object):
def mybefore(self):
print "before func call"
def myafter(self):
print "after func call"
def meth1(a1, a2):
print "meth1(a1=%d, a2=%d)" % (a1, a2)
t = test1()
wmeth1 = ba(meth1, t.mybefore, t.myafter)
wmeth1(1, 2)
Please advise.
A:
I'd use a decorator, like so:
from functools import wraps
class withBeforeAfter(object):
def __init__(self, before, after):
self.before = before
self.after = after
def __call__(self, wrappedCall):
@wraps(wrappedCall)
def wrapCall(*args, **kwargs):
try:
self.before()
r = wrappedCall(*args, **kwargs)
finally:
self.after()
return r
return wrapCall
# to use it:
@withBeforeAfter(myBefore, myAFter)
def myFunc(...):
...
# or:
def myFunc(...):
...
# later...
myFunc = withBeforeAfter(myBefore, myAfter)(myFunc)
A:
You could use the @contextmanager decorator in the contextlib module along with a with statement for something along these lines:
from contextlib import contextmanager
class test1(object):
def mybefore(self):
print "before func call"
def myafter(self):
print "after func call"
@contextmanager
def wrapper(cls):
test = cls()
test.mybefore()
try:
yield
finally:
test.myafter()
def f1(a1, a2):
print "f1(a1=%d, a2=%d)" % (a1, a2)
with wrapper(test1):
f1(1, 2)
| modifying a python callable so it calls before() , actual function then after() | I am not sure if this is the best way to have before and after functions be called around a function f1().
class ba(object):
def __init__(self, call, before, after):
self.call = call
self.before = before
self.after = after
def __call__(self, *args):
self.before()
r = self.call(*args)
self.after()
return r
class test1(object):
def mybefore(self):
print "before func call"
def myafter(self):
print "after func call"
def meth1(a1, a2):
print "meth1(a1=%d, a2=%d)" % (a1, a2)
t = test1()
wmeth1 = ba(meth1, t.mybefore, t.myafter)
wmeth1(1, 2)
Please advise.
| [
"I'd use a decorator, like so:\nfrom functools import wraps\n\nclass withBeforeAfter(object):\n def __init__(self, before, after):\n self.before = before\n self.after = after\n def __call__(self, wrappedCall):\n @wraps(wrappedCall)\n def wrapCall(*args, **kwargs):\n try:... | [
14,
3
] | [] | [] | [
"callable",
"python"
] | stackoverflow_0003373188_callable_python.txt |
Q:
python twisted tutorial/question
Got a simple question regarding twisted.
I can create a trivial basic test with a web server like apache, where http://foo.com/index.php instantiates the index.php for the "foo" site/app...
I'm trying to figure out how the heck I can create a twisted server, where I run different backend functions based on the input!
I know, embarrasingly simple.. but none of what I've seen regarding twisted/server/client/etc.. discusses this.
Comments/pointers/samples are greatly welcome.
thanks
A:
Have you read this?
http://krondo.com/blog/?page_id=1327
A:
You may find http://twistedmatrix.com/documents/current/web/howto/web-in-60/index.html helpful.
| python twisted tutorial/question | Got a simple question regarding twisted.
I can create a trivial basic test with a web server like apache, where http://foo.com/index.php instantiates the index.php for the "foo" site/app...
I'm trying to figure out how the heck I can create a twisted server, where I run different backend functions based on the input!
I know, embarrasingly simple.. but none of what I've seen regarding twisted/server/client/etc.. discusses this.
Comments/pointers/samples are greatly welcome.
thanks
| [
"Have you read this?\nhttp://krondo.com/blog/?page_id=1327\n",
"You may find http://twistedmatrix.com/documents/current/web/howto/web-in-60/index.html helpful.\n"
] | [
3,
0
] | [] | [] | [
"client",
"python",
"twisted"
] | stackoverflow_0003374481_client_python_twisted.txt |
Q:
how do you include modified 3rd party modules when writing setup.py files?
I wrote a standalone script depends on a few modified modules. the directory structure looks like this:
client
setup.py
tsclient
__init__.py
tsup
utils.py
mutagen
__init__.py
blah.py
blah.py
...
colorama
__init__.py
blah.py
blah.py
...
currently, if I just symlink the usup script to my ~/bin directory, I can invoke the script directly and it works with no problems (everything imports properly with no problems).
Now I want to make a setup.py script so I can distribute it. I can't figure out how to do it. Here is what I have now:
setup(
name='tsclient',
version='1.0',
scripts=['tsclient/tsup'],
packages=['tsclient', 'tsclient.mutagen', 'tsclient.colorama'],
)
The problem is that I can't just do import mutagen in the tsup script because it's now tsclient.mutagen. If I change the import to say from tsclient import mutagen I get this error (from mutagen's __init__.py file):
ImportError: No module named mutagen._util
I don't think the best solution is to go through mutagen and change every single instance of "mutagen" and change it to "tsclient.mutagen". Is this my only option?
A:
Unfortunately you do need to edit mutagen to make this work.
Fortunately Python 2.5 and later have syntax to support exactly what you're doing.
See http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports .
Suppose mutagen currently says,
from mutagen import _util
If you change it to say
from . import _util
then it will continue to work as a top-level package; and if needed you can move the whole thing into a subpackage and it will still work.
(However, if you are using setuptools, you can instead add a install_requires= argument in setup.py to tell setuptools that your package requires mutagen to be installed. Then your package could just import mutagen directly.)
| how do you include modified 3rd party modules when writing setup.py files? | I wrote a standalone script depends on a few modified modules. the directory structure looks like this:
client
setup.py
tsclient
__init__.py
tsup
utils.py
mutagen
__init__.py
blah.py
blah.py
...
colorama
__init__.py
blah.py
blah.py
...
currently, if I just symlink the usup script to my ~/bin directory, I can invoke the script directly and it works with no problems (everything imports properly with no problems).
Now I want to make a setup.py script so I can distribute it. I can't figure out how to do it. Here is what I have now:
setup(
name='tsclient',
version='1.0',
scripts=['tsclient/tsup'],
packages=['tsclient', 'tsclient.mutagen', 'tsclient.colorama'],
)
The problem is that I can't just do import mutagen in the tsup script because it's now tsclient.mutagen. If I change the import to say from tsclient import mutagen I get this error (from mutagen's __init__.py file):
ImportError: No module named mutagen._util
I don't think the best solution is to go through mutagen and change every single instance of "mutagen" and change it to "tsclient.mutagen". Is this my only option?
| [
"Unfortunately you do need to edit mutagen to make this work.\nFortunately Python 2.5 and later have syntax to support exactly what you're doing.\nSee http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports .\nSuppose mutagen currently says,\nfrom mutagen import _util\n\nIf you change it to s... | [
2
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0003373779_python_setuptools.txt |
Q:
.py to .exe, three questions
I want to package a Python script so that it can run as a standalone program on Windows XP and later Windows versions. Now to do this I'm pretty sure I'll have to convert it to an .exe file. I know methods exist, what is the easiest/best method?
Now this is where the question gets a little more advanced. I also have some modules the program needs in order to run, can I/how do I package those so that my program can utilize them?
All the modules (if it matters):
import Tkinter
import time
import re
import pickle
import win32api
from win32api import GetSystemMetrics
from PIL import Image, ImageTk
from time import sleep
Next my program also uses PIL in order to display images used in my custom GUI. The thing here is that in order to get the image to run I have to have the complete file path. I have no idea how I'd get this file path on someone else's computer. In short the program requires .png files how do I transfer them so that the program can properly utilize them?
A:
Take a look at py2exe. It's not perfect, but it will convert your script and all dependencies into an executable. I haven't used it in a while, but I believe it makes a directory of dependencies in the directory of the executable. I suspect that you could change the png to a relative path and put it in that directory.
Good luck!
A:
I use Gui2exe and Inno Setup for a good looking windows installer.
Also Upx to compress exe/dll.. this keep the unpacked files after Inno setup small.
I dont use Tkinter dont like the look of Tkinter on windows,wxpython is my favorit python gui-toolkit.
| .py to .exe, three questions | I want to package a Python script so that it can run as a standalone program on Windows XP and later Windows versions. Now to do this I'm pretty sure I'll have to convert it to an .exe file. I know methods exist, what is the easiest/best method?
Now this is where the question gets a little more advanced. I also have some modules the program needs in order to run, can I/how do I package those so that my program can utilize them?
All the modules (if it matters):
import Tkinter
import time
import re
import pickle
import win32api
from win32api import GetSystemMetrics
from PIL import Image, ImageTk
from time import sleep
Next my program also uses PIL in order to display images used in my custom GUI. The thing here is that in order to get the image to run I have to have the complete file path. I have no idea how I'd get this file path on someone else's computer. In short the program requires .png files how do I transfer them so that the program can properly utilize them?
| [
"Take a look at py2exe. It's not perfect, but it will convert your script and all dependencies into an executable. I haven't used it in a while, but I believe it makes a directory of dependencies in the directory of the executable. I suspect that you could change the png to a relative path and put it in that direct... | [
3,
0
] | [] | [] | [
"exe",
"module",
"png",
"python",
"windows"
] | stackoverflow_0003374647_exe_module_png_python_windows.txt |
Q:
py2exe, problems
I'm attempting to convert a .py file to a .exe file. However, I get a weird output.
Output:
usage: module1 [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: module1 --help [cmd1 cmd2 ...]
or: module1 --help-commands
or: module1 cmd --help
error: no commands supplied
My code:
from distutils.core import setup
import py2exe
setup(console=['newstyledemo.py'])
Also when this is done where do I recover the .exe file? I'd like to place it on a flash drive for redistribution.
I'm running Python 2.6 on Windows-7, BTW
A:
Useing Gui2exe can be smart,i use it to both console and gui.
Here is a script i have used,and have worked ok.
from distutils.core import setup
import py2exe
import sys
if len(sys.argv) == 1:
sys.argv.append("py2exe")
setup( options = {"py2exe": {"compressed": 1, "optimize": 2, "ascii": 1, "bundle_files": 3}},
zipfile = None,
## data_files = ['apple.jpg', 'cheese.jpg'],
#Your py-file can use windows or console
windows = [{"script": 'my.py'}])
| py2exe, problems | I'm attempting to convert a .py file to a .exe file. However, I get a weird output.
Output:
usage: module1 [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: module1 --help [cmd1 cmd2 ...]
or: module1 --help-commands
or: module1 cmd --help
error: no commands supplied
My code:
from distutils.core import setup
import py2exe
setup(console=['newstyledemo.py'])
Also when this is done where do I recover the .exe file? I'd like to place it on a flash drive for redistribution.
I'm running Python 2.6 on Windows-7, BTW
| [
"Useing Gui2exe can be smart,i use it to both console and gui.\nHere is a script i have used,and have worked ok.\nfrom distutils.core import setup\nimport py2exe\nimport sys\n\nif len(sys.argv) == 1:\n sys.argv.append(\"py2exe\")\n\nsetup( options = {\"py2exe\": {\"compressed\": 1, \"optimize\": 2, \"ascii\": 1,... | [
1
] | [] | [] | [
"py2exe",
"python",
"windows_7"
] | stackoverflow_0003374913_py2exe_python_windows_7.txt |
Q:
Are there any existing batch log file aggregation solutions?
I wish to export from multiple nodes log files (in my case apache access and error logs) and aggregate that data in batch, as a scheduled job. I have seen multiple solutions that work with streaming data (i.e think scribe). I would like a tool that gives me the flexibility to define the destination. This requirement comes from the fact that I want to use HDFS as the destination.
I have not been able to find a tool that supports this in batch. Before re-creating the wheel I wanted to ask the StackOverflow community for their input.
If a solution exists already in python that would be even better.
A:
we use http://mergelog.sourceforge.net/ to merge all our apache logs..
A:
take a look at Zomhg, its an aggregation/reporting system for log files using Hbase and Hdfs: http://github.com/zohmg/zohmg
A:
Scribe can meet your requirements, there's a version (link) of scribe that can aggregate logs from multiple sources, and after reaching given threshold it stores everything in HDFS. I've used it and it works very well. Compilation is quite complicated, so if you have any problems ask a question.
| Are there any existing batch log file aggregation solutions? | I wish to export from multiple nodes log files (in my case apache access and error logs) and aggregate that data in batch, as a scheduled job. I have seen multiple solutions that work with streaming data (i.e think scribe). I would like a tool that gives me the flexibility to define the destination. This requirement comes from the fact that I want to use HDFS as the destination.
I have not been able to find a tool that supports this in batch. Before re-creating the wheel I wanted to ask the StackOverflow community for their input.
If a solution exists already in python that would be even better.
| [
"we use http://mergelog.sourceforge.net/ to merge all our apache logs..\n",
"take a look at Zomhg, its an aggregation/reporting system for log files using Hbase and Hdfs: http://github.com/zohmg/zohmg\n",
"Scribe can meet your requirements, there's a version (link) of scribe that can aggregate logs from multi... | [
1,
0,
0
] | [
"PiCloud may help.\n\nThe PiCloud Platform gives you the freedom to develop your algorithms\n and software without sinking time into all of the plumbing that comes\n with provisioning, managing, and maintaining servers.\n\n"
] | [
-1
] | [
"aggregation",
"export",
"hdfs",
"logfiles",
"python"
] | stackoverflow_0002358896_aggregation_export_hdfs_logfiles_python.txt |
Q:
Logical task for Python programmers. Make tuple of lists from list
I need to make tuple of list with 2 items.
For example if I have list range(10)
I need to make tuple like this:
[(0,1),(2,3),(4,5),(6,7),(8,9)]
How can I implement that?
A:
Many different ways. Just to show off a few:
As list comprehension, where l is a sequence (i.e. integer indexes): [(l[i], l[i+1]) for i in range(0,len(l),2)]
As generator function, works for all iterables:
def some_meaningful_name(it):
it = iter(it)
while True:
yield next(it), next(it)
Naive via list slicing (sucksy performance for larger lists) and copying, again using list comprehension: [pair for pair in zip(l[::2],l[1::2])].
I like the second best, and it's propably the most pythonic and generic (and since it's a generator, it runs in constant space).
A:
See the grouper recipe from the itertools docs:
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
"""
>>> grouper(3, 'ABCDEFG', 'x')
["ABC", "DEF", "Gxx"]
"""
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
This means that you can do:
[(el[0], el[1]) for el in grouper(2, range(10))]
Or more generally:
[(el[0], el[1]) for el in grouper(2, elements)]
A:
Can also be done with numpy:
import numpy
elements = range(10)
elements = [tuple(e) for e in numpy.array(elements).reshape(-1,2).tolist()]
# [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
| Logical task for Python programmers. Make tuple of lists from list | I need to make tuple of list with 2 items.
For example if I have list range(10)
I need to make tuple like this:
[(0,1),(2,3),(4,5),(6,7),(8,9)]
How can I implement that?
| [
"Many different ways. Just to show off a few:\nAs list comprehension, where l is a sequence (i.e. integer indexes): [(l[i], l[i+1]) for i in range(0,len(l),2)]\nAs generator function, works for all iterables:\ndef some_meaningful_name(it):\n it = iter(it)\n while True:\n yield next(it), next(it)\n\nNai... | [
3,
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003374955_list_python.txt |
Q:
Django template can't see CSS files
I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like:
MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')
MEDIA_URL = '/media/'
I've got the CSS files in /mysite/media/css/ and the template code contains:
<link rel="stylesheet" type="text/css" href="/media/css/site_base.css" />`
then, in the url.py file I have:
# DEVELOPMENT ONLY
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/media'}),
but the development server serves the plain html (without styles). What am I doing wrong?
--
OK - I got it working based on what you folks have said. The answer is:
settings.py:
MEDIA_ROOT = 'd://web//mysite//media//' #absolute path to media
MEDIA_URL = '/mymedia/' #because admin already using /media
site_base.html:
<link rel="stylesheet" type="text/css" href="/mymedia/css/site_base.css" />
urls.py
from mysite import settings
if settings.DEBUG:
urlpatterns += patterns('',
(r'^mymedia/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
And voila! It works.
A:
in the "development only" block in your urls.py you need to change
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/media'}),
to...
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
A:
ADMIN_MEDIA_PREFIX is set to \media\ by default, and is probably 'stealing' the path. Change that setting, or use a different one for non-admin media - eg site_media or assets.
A:
On the dev server, I like to cheat and put the following in my urls.py
if settings.DEBUG:
urlpatterns += patterns('',
(r'^includes/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/static/files'}),
)
That way anything in the project under the "/includes" folder is server by the dev server. You could just change that to "/media".
A:
It also worked for me, thanks guys !!
settings.py
MEDIA_ROOT = '/home/pi/ewspaces/ws-classic/xima/media'
MEDIA_URL = '/statics/'
urls.py
if settings.DEBUG:
urlpatterns += patterns('',
(r'^statics/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
inside templates:
<link type="text/css" href="/statics/css/base/jquery.ui.all.css" rel="stylesheet" />
A:
I had a similar problem when I was trying to get jQuery to work. My fix was to add an alias to my Apache httpd.conf file that pointed to the folder containing the .js. You could do the same with your CSS folder.
| Django template can't see CSS files | I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like:
MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')
MEDIA_URL = '/media/'
I've got the CSS files in /mysite/media/css/ and the template code contains:
<link rel="stylesheet" type="text/css" href="/media/css/site_base.css" />`
then, in the url.py file I have:
# DEVELOPMENT ONLY
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/media'}),
but the development server serves the plain html (without styles). What am I doing wrong?
--
OK - I got it working based on what you folks have said. The answer is:
settings.py:
MEDIA_ROOT = 'd://web//mysite//media//' #absolute path to media
MEDIA_URL = '/mymedia/' #because admin already using /media
site_base.html:
<link rel="stylesheet" type="text/css" href="/mymedia/css/site_base.css" />
urls.py
from mysite import settings
if settings.DEBUG:
urlpatterns += patterns('',
(r'^mymedia/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
And voila! It works.
| [
"in the \"development only\" block in your urls.py you need to change\n(r'^media/(?P<path>.*)$', 'django.views.static.serve',\n {'document_root': '/media'}),\n\nto...\n(r'^media/(?P<path>.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT}),\n\n",
"ADMIN_MEDIA_PREFIX is set to \\medi... | [
13,
5,
2,
1,
0
] | [] | [] | [
"css",
"django",
"django_templates",
"python"
] | stackoverflow_0001075753_css_django_django_templates_python.txt |
Q:
What is the search order for free variables in Python?
Specifically, how are free variables bound at definition for methods of a class? It is probably something like this:
enclosing function (temporary) scope => generate closure
global (permanent) scope => generate no closure (just look it up when the method body executes)
raise UnboundLocalError()
Here are two examples:
globalname = 0
class Test(object):
def method(self):
print globalname
print Test
def outer():
localname = 1
class Test(object):
def method(self):
print globalname
print localname
print Test
return Test
Test().method.__func__.__closure__
# None
outer()().method.__func__.__closure__
# (<cell at 0xb7d655b4: type object at 0x82412bc>, <cell at 0xb7d655cc: int object at 0x81b20b0>)
I couldn't find much documentation on specifically how they are treated at definition time. Is the above explanation correct?
A:
Python assumes a variable is local if and only if it is assigned to, within the current code block. So
spam = 0
def ham:
print( spam )
will make spam a global variable, but
spam = 0
def ham:
spam = 0
print( spam )
will make a separate variable, local to ham. A closure grabs all the variables local to the enclosing scope. In your first example, there are no local variables so no closure; in the second, localname is assigned to and thus method is a closure.
As always in Python, there are ways around this assumption. The global keyword declares a variable as global (!), so e.g.
spam = 0
def ham:
global spam
spam = 0
print( spam )
will not be a closure. Py3k introduces the nonlocal keyword, which tells Python to look upwards through the scopes until it finds the variable name and refer to that.
| What is the search order for free variables in Python? | Specifically, how are free variables bound at definition for methods of a class? It is probably something like this:
enclosing function (temporary) scope => generate closure
global (permanent) scope => generate no closure (just look it up when the method body executes)
raise UnboundLocalError()
Here are two examples:
globalname = 0
class Test(object):
def method(self):
print globalname
print Test
def outer():
localname = 1
class Test(object):
def method(self):
print globalname
print localname
print Test
return Test
Test().method.__func__.__closure__
# None
outer()().method.__func__.__closure__
# (<cell at 0xb7d655b4: type object at 0x82412bc>, <cell at 0xb7d655cc: int object at 0x81b20b0>)
I couldn't find much documentation on specifically how they are treated at definition time. Is the above explanation correct?
| [
"Python assumes a variable is local if and only if it is assigned to, within the current code block. So\nspam = 0\ndef ham:\n print( spam )\n\nwill make spam a global variable, but\nspam = 0\ndef ham:\n spam = 0\n print( spam )\n\nwill make a separate variable, local to ham. A closure grabs all the variabl... | [
2
] | [] | [] | [
"closures",
"python",
"scope"
] | stackoverflow_0003375217_closures_python_scope.txt |
Q:
Python XML and XPath to sort things out
Let's say I have an XML as follows.
<a>
<b>
<c>A</c>
</b>
<bb>
<c>B</c>
</bb>
<c>
X
</c>
</a>
I need to parse this XML into dictionary X for a/b/c and a/b'/c, but dictionary Y for a/c.
dictionary X
X[a_b_c] = A
X[a_bb_c] = B
dictionary T
T[a_c] = X
Q : I'd like to make a mapping file for this in XML file using XPath. How can I do this?
I think of having mapping.xml as follows.
<mapping>
<from>a/c</from><to>dictionary T<to>
....
</mapping>
And using 'a/c' to get X, and put it in dictionary T. Is there any better ways to go?
A:
Maybe you could do this with XSLT. This stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:key name="dict" match="item" use="@dict"/>
<xsl:key name="path" match="*[not(*)]" use="concat(name(../..),'/',
name(..),'/',
name())"/>
<xsl:variable name="map">
<item path="a/b/c" dict="X"/>
<item path="a/bb/c" dict="X"/>
<item path="/a/c" dict="T"/>
</xsl:variable>
<xsl:template match="/">
<xsl:variable name="input" select="."/>
<xsl:for-each select="document('')/*/xsl:variable[@name='map']/*[count(.|key('dict',@dict)[1])=1]">
<xsl:variable name="dict" select="@dict"/>
<xsl:variable name="path" select="../item[@dict=$dict]/@path"/>
<xsl:value-of select="concat('dictionary ',$dict,'
')"/>
<xsl:for-each select="$input">
<xsl:apply-templates select="key('path',$path)">
<xsl:with-param name="dict" select="$dict"/>
</xsl:apply-templates>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
<xsl:template match="*">
<xsl:param name="dict"/>
<xsl:variable name="path" select="concat(name(../..),'_',
name(..),'_',
name())"/>
<xsl:value-of select="concat($dict,'[',
translate(substring($path,
1,
1),
'_',
''),
substring($path,2),'] = ',
normalize-space(.),'
')"/>
</xsl:template>
</xsl:stylesheet>
Output:
dictionary X
X[a_b_c] = A
X[a_bb_c] = B
dictionary T
T[a_c] = X
EDIT: Pretty things a bit.
| Python XML and XPath to sort things out | Let's say I have an XML as follows.
<a>
<b>
<c>A</c>
</b>
<bb>
<c>B</c>
</bb>
<c>
X
</c>
</a>
I need to parse this XML into dictionary X for a/b/c and a/b'/c, but dictionary Y for a/c.
dictionary X
X[a_b_c] = A
X[a_bb_c] = B
dictionary T
T[a_c] = X
Q : I'd like to make a mapping file for this in XML file using XPath. How can I do this?
I think of having mapping.xml as follows.
<mapping>
<from>a/c</from><to>dictionary T<to>
....
</mapping>
And using 'a/c' to get X, and put it in dictionary T. Is there any better ways to go?
| [
"Maybe you could do this with XSLT. This stylesheet:\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n <xsl:key name=\"dict\" match=\"item\" use=\"@dict\"/>\n <xsl:key name=\"path\" match=\"*[not(*)]\" use=\"concat(name(../..),'/',\n ... | [
1
] | [] | [] | [
"python",
"xml",
"xpath"
] | stackoverflow_0003373028_python_xml_xpath.txt |
Q:
Voice recognition : voice driven control
Few days ago I asked for a project idea for my B.tech Final year project.
Unfortunately couldn't got any cool idea.
Now I have got an idea which really pleases me and motivates me.
I want to ask to intelligent guys out there is following thing is feasible in 5 months:
The Project idea is :
"A Voice Driven Controlling of The System"
I want to make an application which will listen to voice of the user of system and run commands by voice instructions:
simplest examples would be like:
open a media player, play list, change the song,
open any other application
close some application
close current window or application
If possible make the application capable of learning new things on run time also. (planned for Second Phase if lack of time for completion of first phase)
Even if I'll be able to implement this much examples only it will be good enough for now, as the same project I have to continue next semester.
I want to know the feasibility of the project. Also please suggest me that what would be the best language to develop this app.
Also All the suggestions are most welcome.
A:
I think somebody beat you to it:
http://code.google.com/p/dragonfly/
note that you can use the Microsoft Windows speech recognition engine or Nuance's Dragon NaturallySpeaking.
Good luck
| Voice recognition : voice driven control | Few days ago I asked for a project idea for my B.tech Final year project.
Unfortunately couldn't got any cool idea.
Now I have got an idea which really pleases me and motivates me.
I want to ask to intelligent guys out there is following thing is feasible in 5 months:
The Project idea is :
"A Voice Driven Controlling of The System"
I want to make an application which will listen to voice of the user of system and run commands by voice instructions:
simplest examples would be like:
open a media player, play list, change the song,
open any other application
close some application
close current window or application
If possible make the application capable of learning new things on run time also. (planned for Second Phase if lack of time for completion of first phase)
Even if I'll be able to implement this much examples only it will be good enough for now, as the same project I have to continue next semester.
I want to know the feasibility of the project. Also please suggest me that what would be the best language to develop this app.
Also All the suggestions are most welcome.
| [
"I think somebody beat you to it:\nhttp://code.google.com/p/dragonfly/\nnote that you can use the Microsoft Windows speech recognition engine or Nuance's Dragon NaturallySpeaking.\nGood luck\n"
] | [
0
] | [] | [] | [
"c#",
"c++",
"projects_and_solutions",
"python",
"voice_recognition"
] | stackoverflow_0003369158_c#_c++_projects_and_solutions_python_voice_recognition.txt |
Q:
Select element within a list/tuple
Hey bit of a beginners question here, I have connected to an imap server using the imaplib and fetched a email, it returns the following:
[('1 (BODY[HEADER.FIELDS (SUBJECT)] {62}', "Subject: Gmail is different. Here's what you need to know.\r\n\r\n"), ')']
My question is how do I select just the subject element ("Subject: Gmail is...").
I have tried a few combinations but yet to be successful.
Thanks for any help!
A:
a[0][1]
where a is the string.
A:
email=[('1 (BODY[HEADER.FIELDS (SUBJECT)] {62}', "Subject: Gmail is different. Here's what you need to know.\r\n\r\n"), ')']
for subj in (subject for element in email for subject in element if subject.startswith("Subject")):
print subj
""" Output
Subject: Gmail is different. Here's what you need to know.
"""
| Select element within a list/tuple | Hey bit of a beginners question here, I have connected to an imap server using the imaplib and fetched a email, it returns the following:
[('1 (BODY[HEADER.FIELDS (SUBJECT)] {62}', "Subject: Gmail is different. Here's what you need to know.\r\n\r\n"), ')']
My question is how do I select just the subject element ("Subject: Gmail is...").
I have tried a few combinations but yet to be successful.
Thanks for any help!
| [
"a[0][1]\n\nwhere a is the string.\n",
" email=[('1 (BODY[HEADER.FIELDS (SUBJECT)] {62}', \"Subject: Gmail is different. Here's what you need to know.\\r\\n\\r\\n\"), ')']\n for subj in (subject for element in email for subject in element if subject.startswith(\"Subject\")):\n print subj\n\"\"\" Outp... | [
4,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003375375_list_python.txt |
Q:
Writing binary data to stdout with IronPython
I have two Python scripts which I am running on Windows with IronPython 2.6 on .NET 2.0. One outputs binary data and the other processes the data. I was hoping to be able to stream data from the first to the second using pipes. The problem I encountered here is that, when run from the Windows command-line, sys.stdout uses CP437 character encoding and text mode instead of binary mode ('w' instead of 'wb'). This causes some bytes greater than 127 to be written as the wrong character (i.e., different byte values produce the same character in the output and are thus indistinguishable by the script reading them).
For example, this script prints the same character (an underscore) twice:
import sys
sys.stdout.write(chr(95))
sys.stdout.write(chr(222))
So when I try to read the data I get something different than what I originally wrote.
I wrote this script to check if the problem was writing in 'w' mode or the encoding:
import sys
str = chr(222)
# try writing chr(222) in ASCII in both write modes
# ASCII is the default encoding
open('ascii_w', 'w').write(str)
open('ascii_wb', 'wb').write(str)
# set encoding to CP437 and try writing chr(222) in both modes
reload(sys)
sys.setdefaultencoding("cp437")
open('cp437_w', 'w').write(str)
open('cp437_wb', 'wb').write(str)
After running that, the file cp437_w contains character 95 and the other three each contain character 222. Therefore, I believe that the problem is caused by the combination of CP437 encoding and writing in 'w' mode. In this case it would be solved if I could force stdout to use binary mode (I'm assuming that getting it to use ASCII encoding is impossible given that cmd.exe uses CP437). This is where I'm stuck; I can't find any way to do this.
Some potential solutions I found that didn't work:
running ipy -u doesn't seem to have any effect (I also tested to see if it would cause Unix-style newlines to be printed; it doesn't, so I suspect that -u doesn't work with IronPython at all)
I can't use this solution because msvcrt is not supported in IronPython
with Python 3.x you can access unbuffered stdout through sys.stdout.buffer; this isn't available in 2.6
os.fdopen(sys.stdout.fileno(), 'wb', 0) just returns stdout in 'w' mode
So yeah, any ideas? Also, if there's a better way of streaming binary data that doesn't use stdout, I'm certainly open to suggestions.
A:
sys.stdout is just a variable that points to the same thing as sys.__stdout__
Therefore, just open up a file in binary mode, assign the file to sys.stdout and use it. If you ever need the real, normal stdout back again, you can get it with
sys.stdout = sys.__stdout__
| Writing binary data to stdout with IronPython | I have two Python scripts which I am running on Windows with IronPython 2.6 on .NET 2.0. One outputs binary data and the other processes the data. I was hoping to be able to stream data from the first to the second using pipes. The problem I encountered here is that, when run from the Windows command-line, sys.stdout uses CP437 character encoding and text mode instead of binary mode ('w' instead of 'wb'). This causes some bytes greater than 127 to be written as the wrong character (i.e., different byte values produce the same character in the output and are thus indistinguishable by the script reading them).
For example, this script prints the same character (an underscore) twice:
import sys
sys.stdout.write(chr(95))
sys.stdout.write(chr(222))
So when I try to read the data I get something different than what I originally wrote.
I wrote this script to check if the problem was writing in 'w' mode or the encoding:
import sys
str = chr(222)
# try writing chr(222) in ASCII in both write modes
# ASCII is the default encoding
open('ascii_w', 'w').write(str)
open('ascii_wb', 'wb').write(str)
# set encoding to CP437 and try writing chr(222) in both modes
reload(sys)
sys.setdefaultencoding("cp437")
open('cp437_w', 'w').write(str)
open('cp437_wb', 'wb').write(str)
After running that, the file cp437_w contains character 95 and the other three each contain character 222. Therefore, I believe that the problem is caused by the combination of CP437 encoding and writing in 'w' mode. In this case it would be solved if I could force stdout to use binary mode (I'm assuming that getting it to use ASCII encoding is impossible given that cmd.exe uses CP437). This is where I'm stuck; I can't find any way to do this.
Some potential solutions I found that didn't work:
running ipy -u doesn't seem to have any effect (I also tested to see if it would cause Unix-style newlines to be printed; it doesn't, so I suspect that -u doesn't work with IronPython at all)
I can't use this solution because msvcrt is not supported in IronPython
with Python 3.x you can access unbuffered stdout through sys.stdout.buffer; this isn't available in 2.6
os.fdopen(sys.stdout.fileno(), 'wb', 0) just returns stdout in 'w' mode
So yeah, any ideas? Also, if there's a better way of streaming binary data that doesn't use stdout, I'm certainly open to suggestions.
| [
"sys.stdout is just a variable that points to the same thing as sys.__stdout__\nTherefore, just open up a file in binary mode, assign the file to sys.stdout and use it. If you ever need the real, normal stdout back again, you can get it with\nsys.stdout = sys.__stdout__\n\n"
] | [
0
] | [] | [] | [
"character_encoding",
"ironpython",
"python",
"stdout"
] | stackoverflow_0003375111_character_encoding_ironpython_python_stdout.txt |
Q:
Call javascript functions in IE with Python/Com
http://win32com.goermezer.de/content/view/170/291/
Tried the above. I am able to call Javascript functions declared in the html file. However, for javascript functions in external js files included in the html, I am not able to call those functions using the above method. Any work arounds for this ?
A:
This sounds like a timing problem that is common with Javascript in the web page. AJAX programmers often need to tell the browser to wait until the page is fully loaded before executing their scripts.
One way to deal with that outside of the browser is to simply insert a time delay, i.e. call some innocuous function on the page, wait a second or two, then call the one you need.
Alternatively, if this method allows you to execute arbitrary Javascript inside the browser, like the way bookmarklets work with javascript: URLs, then use that to attach an event listener to the onload event and make that event listener function call the one that you need.
| Call javascript functions in IE with Python/Com | http://win32com.goermezer.de/content/view/170/291/
Tried the above. I am able to call Javascript functions declared in the html file. However, for javascript functions in external js files included in the html, I am not able to call those functions using the above method. Any work arounds for this ?
| [
"This sounds like a timing problem that is common with Javascript in the web page. AJAX programmers often need to tell the browser to wait until the page is fully loaded before executing their scripts.\nOne way to deal with that outside of the browser is to simply insert a time delay, i.e. call some innocuous funct... | [
0
] | [] | [] | [
"com",
"python"
] | stackoverflow_0003366026_com_python.txt |
Q:
Having Problems with importing xlwt?
I am using Eclipse with the PyDev plugin. I am using xlwt which is for writing to an excel sheet. I have the xlwt library in my src file. I have another python file called gene_sorter.py where i try to import xlwt. using
import xlwt
I keep gettting back this error:
File "C:\Documents and Settings\Ben Fossen\Pythonworkspace\MTBgenes\src\gene_sorter.py", line 1, in <module>
from xlwt import *
File "C:\Documents and Settings\Ben Fossen\Pythonworkspace\MTBgenes\src\xlwt\__init__.py", line 10, in <module>
from Workbook import Workbook
ImportError: No module named Workbook
I am new to using PyDev and eclipse so mabye I am making a simple mistake. I can't seem to see what I am doing wrong. I am using a new enough version of python so that shouldn't be a problem. Has anyone else had this problem it seems very strange?
A:
"New enough version of Python" could well be "too new"; please edit your question to show the actual version number. In future, don't be coy; save the time and energy of everybody (including yourself) by including such essential information in your question.
If you are trying to run it under Python 3.1:
Don't bother; it's not supported (yet).
Please say where you got the notion that it was supported on 3.X, so that it can be corrected.
Otherwise:
Any particular reason why you wouldn't just run the Windows installer and install it in the default directory?
| Having Problems with importing xlwt? | I am using Eclipse with the PyDev plugin. I am using xlwt which is for writing to an excel sheet. I have the xlwt library in my src file. I have another python file called gene_sorter.py where i try to import xlwt. using
import xlwt
I keep gettting back this error:
File "C:\Documents and Settings\Ben Fossen\Pythonworkspace\MTBgenes\src\gene_sorter.py", line 1, in <module>
from xlwt import *
File "C:\Documents and Settings\Ben Fossen\Pythonworkspace\MTBgenes\src\xlwt\__init__.py", line 10, in <module>
from Workbook import Workbook
ImportError: No module named Workbook
I am new to using PyDev and eclipse so mabye I am making a simple mistake. I can't seem to see what I am doing wrong. I am using a new enough version of python so that shouldn't be a problem. Has anyone else had this problem it seems very strange?
| [
"\"New enough version of Python\" could well be \"too new\"; please edit your question to show the actual version number. In future, don't be coy; save the time and energy of everybody (including yourself) by including such essential information in your question.\nIf you are trying to run it under Python 3.1:\n\nDo... | [
1
] | [] | [] | [
"import",
"python",
"xlwt"
] | stackoverflow_0003375384_import_python_xlwt.txt |
Q:
communication between python programs
I have a python program that is running as a daemon on Linux.
How to send this daemon a signal from another python program?
A:
Use os.kill to send signals. The signals are defined in the signal module. You'll just need to get the pid of the daemon in some way.
One more thing - you can use the signal module to register signal handlers as well.
A:
If you need something more sophisticated than simple signals, consider using an RPC library like PYRO. The advantage of this is that you can use it even if you have to move your processes to separate servers.
Or, if you mainly target Linux systems, then look at using DBUS instead. There is a python library and it is now even supported on Windows.
A:
Have you tried reading through the docs on interprocess communication in Python? Here is a link:
http://docs.python.org/library/ipc.html
A:
The daemon could have an open (network) socket, where it accepts commands.
It could monitor changes in a file.
Any other kind of signalling is possible, but these would probably be the most common.
| communication between python programs | I have a python program that is running as a daemon on Linux.
How to send this daemon a signal from another python program?
| [
"Use os.kill to send signals. The signals are defined in the signal module. You'll just need to get the pid of the daemon in some way.\nOne more thing - you can use the signal module to register signal handlers as well.\n",
"If you need something more sophisticated than simple signals, consider using an RPC lib... | [
4,
3,
2,
1
] | [] | [] | [
"process",
"python"
] | stackoverflow_0003363831_process_python.txt |
Q:
python: print values from a dictionary
generic_drugs_mapping={'MORPHINE':[86],
'OXYCODONE':[87],
'OXYMORPHONE':[99],
'METHADONE':[82],
'BUPRENORPHINE':[28],
'HYDROMORPHONE':[54],
'CODEINE':[37],
'HYDROCODONE':[55]}
How do I return 86?
This does not seem to work:
print generic_drugs_mapping['MORPHINE'[0]]
A:
You have a bracket in the wrong place:
print generic_drugs_mapping['MORPHINE'][0]
Your code is indexing the string 'MORPHINE', so it's equivalent to
print generic_drugs_mapping['M']
Since 'M' is not a key in your dictionary, you won't get the results you expect.
A:
The list is the value stored under the key. The part that gets the value out is generic_drugs_mapping['MORPHINE'] so this has the value [86]. Try moving the index outside like this :
generic_drugs_mapping['MORPHINE'][0]
| python: print values from a dictionary | generic_drugs_mapping={'MORPHINE':[86],
'OXYCODONE':[87],
'OXYMORPHONE':[99],
'METHADONE':[82],
'BUPRENORPHINE':[28],
'HYDROMORPHONE':[54],
'CODEINE':[37],
'HYDROCODONE':[55]}
How do I return 86?
This does not seem to work:
print generic_drugs_mapping['MORPHINE'[0]]
| [
"You have a bracket in the wrong place:\nprint generic_drugs_mapping['MORPHINE'][0]\n\nYour code is indexing the string 'MORPHINE', so it's equivalent to\nprint generic_drugs_mapping['M']\n\nSince 'M' is not a key in your dictionary, you won't get the results you expect.\n",
"The list is the value stored under th... | [
6,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003375804_dictionary_python.txt |
Q:
python: comparing values string/integer
i will be comparing two values like this:\
value1>value2
i know that value2 is always an integer, but sometimes value1 is None or a string, how do force the comparison ONLY if value1 is numerical?
value1 is a decimal
A:
Python 3
try:
value1 > value2
except TypeError:
pass
Python <3
if isinstance( value2, int ):
value1 > value2
This latter is unpythonic, because this type of comparison is unpythonic. You should filter your data first.
A:
try:
int(value1) > value2
except (TypeError, ValueError):
pass
A:
if value1:
Decimal(value1) > value2
| python: comparing values string/integer | i will be comparing two values like this:\
value1>value2
i know that value2 is always an integer, but sometimes value1 is None or a string, how do force the comparison ONLY if value1 is numerical?
value1 is a decimal
| [
"Python 3\ntry:\n value1 > value2\nexcept TypeError:\n pass\n\nPython <3\nif isinstance( value2, int ):\n value1 > value2\n\nThis latter is unpythonic, because this type of comparison is unpythonic. You should filter your data first.\n",
"try:\n int(value1) > value2\nexcept (TypeError, ValueError):\n ... | [
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003375845_python.txt |
Q:
Python: upload images
Can python upload images onto the internet and provide a URL for it? For example is it possible for python to upload an image onto photobucket or any other uploading image service and then retreive the URL for it?
A:
Certainly. You'll need to find an image hosting service with an API (hint: Flickr), and then write some Python code to interact with it (hint: XML-RPC).
Pseudocode
import xmlrpclib
with open( "..." ) as imagelist:
for image in imagelist:
message = xmlrpclib.make_some_message_or_other
response = message.send( )
response.parse( )
You'll need a more specific question if you want a more specific answer!
A:
Sure!
To do it, you basically have to have Python pretend to be a web browser. You need to go get the upload form, fill in all the fields, and pick your image. Then you need to submit the form data, uploading the image. Once that's done, you need to get the "upload complete" page from the site, and find the URL where the image went.
A good library to start with might be the Python version of Perl's famous WWW::Mechanize module. The library is basically a programmable Web browser that you can script in Python.
EDIT: If you plan to do this a lot, you probably do want to use an actual supported API. Otherwise the image hoster might get mad that your python bot is spamming their site.
| Python: upload images | Can python upload images onto the internet and provide a URL for it? For example is it possible for python to upload an image onto photobucket or any other uploading image service and then retreive the URL for it?
| [
"Certainly. You'll need to find an image hosting service with an API (hint: Flickr), and then write some Python code to interact with it (hint: XML-RPC).\nPseudocode\nimport xmlrpclib\n\nwith open( \"...\" ) as imagelist:\n for image in imagelist:\n message = xmlrpclib.make_some_message_or_other\n ... | [
2,
0
] | [] | [] | [
"image",
"python",
"upload"
] | stackoverflow_0003375875_image_python_upload.txt |
Q:
python: accessing a list using a dictionary
i read a csv into a variable called b
now i am going through every row in it like this:
for row in b:
this dictionary gives me the positions of where these drugs are in the row:
generic_drugs_mapping={'MORPHINE':[86],
'OXYCODONE':[87],
'OXYMORPHONE':[99],
'METHADONE':[82],
'BUPRENORPHINE':[28],
'HYDROMORPHONE':[54],
'CODEINE':[37],
'HYDROCODONE':[55]}
i am setting drug = 'MORPHINE'
am i able to do this:
row[generic_drugs_mapping[drug][0]]!=''
to check whether there is a value in the row[86]!='' ??
A:
Yes, that should work, assuming those are 0-based indexes into row. Is there a reason the elements of the dictionary are lists?
| python: accessing a list using a dictionary | i read a csv into a variable called b
now i am going through every row in it like this:
for row in b:
this dictionary gives me the positions of where these drugs are in the row:
generic_drugs_mapping={'MORPHINE':[86],
'OXYCODONE':[87],
'OXYMORPHONE':[99],
'METHADONE':[82],
'BUPRENORPHINE':[28],
'HYDROMORPHONE':[54],
'CODEINE':[37],
'HYDROCODONE':[55]}
i am setting drug = 'MORPHINE'
am i able to do this:
row[generic_drugs_mapping[drug][0]]!=''
to check whether there is a value in the row[86]!='' ??
| [
"Yes, that should work, assuming those are 0-based indexes into row. Is there a reason the elements of the dictionary are lists?\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003376043_python.txt |
Q:
Append a value to a list and move all values over
if i start off with :
a=[1,2,4]
and i want the result to be
a=[1,3,2,4]
how do i do this append?
A:
In [18]: a=[1,2,4]
In [19]: a[1:1]=[3]
In [20]: a
Out[20]: [1, 3, 2, 4]
or
In [22]: a.insert(1,3)
In [24]: a
Out[24]: [1, 3, 2, 4]
With the first (slice) notation, you can even insert multiple elements (similar to extend, but not necessarily at the end of the list):
In [26]: a[1:1]=[3,5]
In [27]: a
Out[27]: [1, 3, 5, 2, 4]
whereas with the insert method, you can only insert one element:
In [30]: a.insert(1,[3,5])
In [31]: a
Out[31]: [1, [3, 5], 2, 4]
The slice notation can also be used to modify or remove parts of a list.
A:
You can do this with the slice operator:
a[1:1] = (3,)
Or with the insert function:
a.insert(1, 3)
In both cases, position 1 refers to the second slot in the list.
A:
a.insert( 1, 3 )
| Append a value to a list and move all values over | if i start off with :
a=[1,2,4]
and i want the result to be
a=[1,3,2,4]
how do i do this append?
| [
"In [18]: a=[1,2,4]\n\nIn [19]: a[1:1]=[3]\n\nIn [20]: a\nOut[20]: [1, 3, 2, 4]\n\nor\nIn [22]: a.insert(1,3)\n\nIn [24]: a\nOut[24]: [1, 3, 2, 4]\n\nWith the first (slice) notation, you can even insert multiple elements (similar to extend, but not necessarily at the end of the list):\nIn [26]: a[1:1]=[3,5]\n\nIn [... | [
6,
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0003376160_python.txt |
Q:
Finding Regex Pattern after doing re.findall
This is in continuation of my earlier question where I wanted to compile many patterns as one regular expression and after the discussion I did something like this
REGEX_PATTERN = '|'.join(self.error_patterns.keys())
where self.error_patterns.keys() would be pattern like
: error:
: warning:
cc1plus:
undefine reference to
Failure:
and do
error_found = re.findall(REGEX_PATTERN,line)
Now when I run it against some file which might contain one or more than one patterns, how do I know what pattern exactly matched? I mean I can anyway see the line manually and find it out, but want to know if after doing re.findall I can find out the pattern like re.group() or something
Thank you
A:
re.findall will return all portions of text that matched your expression.
If that is not sufficient to identify the pattern unambiguously, you can still do a second re.match/re.find against the individual subpatterns you have join()ed. At the time of applying your initial regular expression, the matcher is no longer aware that you have composed it of several subpatterns however, hence it cannot provide more detailed information which subpattern has matched.
Another, equally unwieldy option would be to enclose each pattern in a group (...). Then, re.findall will return an array of None values (for all the non-matching patterns), with the exception of the one group that matched the pattern.
A:
MatchObject has a lastindex property that contains the index of the last capturing group that participated in the match. If you enclose each pattern in its own capturing group, like this:
(: error:)|(: warning:)
...lastindex will tell you which one matched (assuming you know the order in which the patterns appear in the regex). You'll probably want to use finditer() (which creates an iterator of MatchObjects) instead of findall() (which returns a list of strings). Also, make sure there are no other capturing groups in the regex, to throw your indexing out of sync.
| Finding Regex Pattern after doing re.findall | This is in continuation of my earlier question where I wanted to compile many patterns as one regular expression and after the discussion I did something like this
REGEX_PATTERN = '|'.join(self.error_patterns.keys())
where self.error_patterns.keys() would be pattern like
: error:
: warning:
cc1plus:
undefine reference to
Failure:
and do
error_found = re.findall(REGEX_PATTERN,line)
Now when I run it against some file which might contain one or more than one patterns, how do I know what pattern exactly matched? I mean I can anyway see the line manually and find it out, but want to know if after doing re.findall I can find out the pattern like re.group() or something
Thank you
| [
"re.findall will return all portions of text that matched your expression.\nIf that is not sufficient to identify the pattern unambiguously, you can still do a second re.match/re.find against the individual subpatterns you have join()ed. At the time of applying your initial regular expression, the matcher is no lon... | [
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003374456_python_regex.txt |
Q:
request.POST pylons, getting array like in php
I have a dynamic form, i must bulid some post array to field witch some id.
For example:
<input type="checkbox" name="field[124][]" value="1">
<input type="checkbox" name="field[124][]" value="2">
In php i can simply get value and key.
foreach($_POST as $key => $value){
if(is_array($value){
foreach($value as $key2 => $value2){
//i get key=>124 and all values for this key
}
}
}
<input type="checkbox" name="field" value="1">
<input type="checkbox" name="field" value="2">
In pylons for array of checkbox i can use
request.POST[field].getall()
How can i create in pylons post array like in PHP?
Thanks.
A:
You can use .getall() of multidict object, for example:
html:
<input type="checkbox" name="field[124][]" value="1">
<input type="checkbox" name="field[124][]" value="2">
controller:
values = request.POST.getall('field[124][]')
# >>> values
# [u'1', u'2']
another way to get this list is by using .dict_of_lists(), example:
controller:
d = request.POST.dict_of_lists()
values = d['field[124][]']
# >>> d
# {'field[124][]':[u'1', u'2']}
# >>> values
# [u'1', u'2']
| request.POST pylons, getting array like in php | I have a dynamic form, i must bulid some post array to field witch some id.
For example:
<input type="checkbox" name="field[124][]" value="1">
<input type="checkbox" name="field[124][]" value="2">
In php i can simply get value and key.
foreach($_POST as $key => $value){
if(is_array($value){
foreach($value as $key2 => $value2){
//i get key=>124 and all values for this key
}
}
}
<input type="checkbox" name="field" value="1">
<input type="checkbox" name="field" value="2">
In pylons for array of checkbox i can use
request.POST[field].getall()
How can i create in pylons post array like in PHP?
Thanks.
| [
"You can use .getall() of multidict object, for example:\nhtml:\n<input type=\"checkbox\" name=\"field[124][]\" value=\"1\">\n<input type=\"checkbox\" name=\"field[124][]\" value=\"2\">\n\ncontroller:\nvalues = request.POST.getall('field[124][]')\n# >>> values\n# [u'1', u'2']\n\n\nanother way to get this list is by... | [
2
] | [] | [] | [
"php",
"pylons",
"python"
] | stackoverflow_0003366074_php_pylons_python.txt |
Q:
Approximate session data from apache access.log - python
How might one use the ip and timestamp from Apache's access log to approximate a "session" for a given visitor? A session would include all consecutive requests within a given period, say 60secs.
I have a class to parse the log file, and follow an IP address through it (the log is in timestamp order, thankfully). The class creates a tuple of dictionaries, which contain the various log fields and a python datetime object for the access timestamp.
class ApacheLogParser(object):
def __init__(self, file):
self.lines = __parse(file)
def __parse(self, file):
""" use a regex to parse the file
return a tuple of dictionaries
"""
def follow_ip(self, ip):
""" all entries for a given ip, in order of appearance in the log """
return (line for line in self.lines if re.search(ip, line['ip']))
log = ApacheLogParser('access.log')
for line in log.follow_ip('1.2.3.4'):
print "%s %s" % (line['path'], line['datetime'].date())
How might I add functionality to this class to be able to iterate through these approximated "sessions"?
Thanks!
EDIT:
While forming my edit, I came up with this:
ip = '1.2.3.4'
ipdata = list(log.track_ip(ip))
initial_dt = ipdata[0]['datetime']
sess = [x for x in ipdata if x['datetime'] < initial_dt + datetime.timedelta(0,60)]
It seems to work, do you have any comments?
A:
I wrote you some code then did a fail and lost it =(.
One way, not necessarily the best, is to iterate through the lines, maintaining a dictionary of IP address -> list of lines in its session. For each line, if it's already in the dict just append it to the list; otherwise, make a new session for it. Then, within the loop, check all sessions for expiry (their last element's datetime being over 60 seconds before the current line's); if one has expired, yield it and delete it from the dict.
| Approximate session data from apache access.log - python | How might one use the ip and timestamp from Apache's access log to approximate a "session" for a given visitor? A session would include all consecutive requests within a given period, say 60secs.
I have a class to parse the log file, and follow an IP address through it (the log is in timestamp order, thankfully). The class creates a tuple of dictionaries, which contain the various log fields and a python datetime object for the access timestamp.
class ApacheLogParser(object):
def __init__(self, file):
self.lines = __parse(file)
def __parse(self, file):
""" use a regex to parse the file
return a tuple of dictionaries
"""
def follow_ip(self, ip):
""" all entries for a given ip, in order of appearance in the log """
return (line for line in self.lines if re.search(ip, line['ip']))
log = ApacheLogParser('access.log')
for line in log.follow_ip('1.2.3.4'):
print "%s %s" % (line['path'], line['datetime'].date())
How might I add functionality to this class to be able to iterate through these approximated "sessions"?
Thanks!
EDIT:
While forming my edit, I came up with this:
ip = '1.2.3.4'
ipdata = list(log.track_ip(ip))
initial_dt = ipdata[0]['datetime']
sess = [x for x in ipdata if x['datetime'] < initial_dt + datetime.timedelta(0,60)]
It seems to work, do you have any comments?
| [
"I wrote you some code then did a fail and lost it =(.\nOne way, not necessarily the best, is to iterate through the lines, maintaining a dictionary of IP address -> list of lines in its session. For each line, if it's already in the dict just append it to the list; otherwise, make a new session for it. Then, withi... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003376218_python.txt |
Q:
How do I add a new column of data to a csv file
I am reading a csv file into a variable data like this:
def get_file(start_file): #opens original file, reads it to array
with open(start_file,'rb') as f:
data=list(csv.reader(f))
data is the entire csv file. How do I add an extra column to this data?
A:
data is a list of lists of strings, so...:
for row, itm in zip(data, column):
row.append(str(itm))
of course you need column to be the right length so you may want to check that, eg raise an exc if len(data) != len(column).
A:
.append a value to the end of each row in data, and then use a csv.writer to write the updated data.
A:
Short answer: open up the CSV file in your favourite editor and add a column
Long answer: well, first, you should use csv.reader to read the file; this handles all the details of splitting the lines, malformed lines, quoted commas, and so on. Then, wrap the reader in another method which adds a column.
def get_file( start_file )
f = csv.reader( start_file )
def data( csvfile ):
for line in csvfile:
yield line + [ "your_column" ]
return data( f )
Edit
As you asked in your other question:
def get_file( start_file )
f = csv.reader( start_file )
def data( csvfile ):
for line in csvfile:
line[ 1 ] += "butter"
yield line
return data( f )
which you use like
lines = get_file( "my_file.csv" )
for line in lines:
# do stuff
| How do I add a new column of data to a csv file | I am reading a csv file into a variable data like this:
def get_file(start_file): #opens original file, reads it to array
with open(start_file,'rb') as f:
data=list(csv.reader(f))
data is the entire csv file. How do I add an extra column to this data?
| [
"data is a list of lists of strings, so...:\nfor row, itm in zip(data, column):\n row.append(str(itm))\n\nof course you need column to be the right length so you may want to check that, eg raise an exc if len(data) != len(column).\n",
".append a value to the end of each row in data, and then use a csv.writer to ... | [
3,
3,
3
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003376236_csv_python.txt |
Q:
make a change to an element within a list within a list
i am reading a csv file into a data:
def get_file(start_file): #opens original file, reads it to array
with open(start_file,'rb') as f:
data=list(csv.reader(f))
i need to go through every row and add a value to row[1] like this. initially row[1] = 'Peanut', i need to add 'Butter' so the result would be
row[1]='PeanutButter'
i need to do this for every row like this
for row in data:
row+='Butter'
is this the correct way of doing it?
A:
You want
for row in data:
row[ 1 ] += "Butter"
but the right way to do this is not to iterate through every row of data again but to modify the way you generate data in the first place. Go look at my answer in your other question.
Copy-paste from your previous question
def get_file( start_file )
f = csv.reader( start_file )
def data( csvfile ):
for line in csvfile:
line[ 1 ] += "butter"
yield line
return data( f )
which you use like
lines = get_file( "my_file.csv" )
for line in lines:
# do stuff
Explanation
The issue here is that we want to modify the data held in data. We could look through and change every element in data, but that's slow, especially given that we're going to look through every element again shortly. Instead, a much nicer way is to change the lines as they are inserted into the data holder, because that saves you one pass.
Here goes:
f = csv.reader( start_file )
I have modified the code to use csv.reader, because that's a much more robust way of reading CSV data. It's basically a trivial change; it works like open but each line is a tuple of the values, already separated for you.
def data( csvfile )
This is different! Instead of making data a variable, we're making it a function. That doesn't sound right, but bear with me.
for line in csvfile:
OK, data is a function of csvfile so we're just iterating through the lines in the first argument. So far, so good.
line[ 1 ] += butter
This is the change you wanted to make: we add "butter" to the second element of line. You could also make other changes here: add a column to each row, delete columns, skip rows, the list goes on!
yield line
This is clever Python trickery. It basically works like return, but without stopping the function from running. Instead, it is paused until we ask for the next value.
So now data is a function which returns each of the lines (modified just as you wanted them) in turn. What now? Easy:
return data( f )
Make get_file return data!
What does this mean? Well, we can now use it as the iterable in a for loop:
for line in get_file( "my_file.csv" ):
and everything will work!!! Magic!! =p
A couple of other points:
Previously, you used with ... as ... syntax. This is a context manager: it automatically closes the file when you're done with it. But in this case we don't want to do that, since we are reading lines from the file as we go through. Casting it to a list copies the whole thing into memory, which is sloooooow. You should add f.close() elsewhere in the code if you're worried about memory leaks.
I had another point, but I can't remember it...
A:
for flist in data:
for element in flist:
element += 'butter'
Is that what you want?
| make a change to an element within a list within a list | i am reading a csv file into a data:
def get_file(start_file): #opens original file, reads it to array
with open(start_file,'rb') as f:
data=list(csv.reader(f))
i need to go through every row and add a value to row[1] like this. initially row[1] = 'Peanut', i need to add 'Butter' so the result would be
row[1]='PeanutButter'
i need to do this for every row like this
for row in data:
row+='Butter'
is this the correct way of doing it?
| [
"You want\nfor row in data:\n row[ 1 ] += \"Butter\"\n\nbut the right way to do this is not to iterate through every row of data again but to modify the way you generate data in the first place. Go look at my answer in your other question.\n\nCopy-paste from your previous question\ndef get_file( start_file )\n ... | [
5,
0
] | [] | [] | [
"csv",
"list",
"python"
] | stackoverflow_0003376299_csv_list_python.txt |
Q:
GAE/Django Templates (0.96) filters to get LENGTH of GqlQuery and filter it
I pass the query with comments to my template:
COMM = CommentModel.gql("ORDER BY created")
doRender(self,CP.template,{'CP':CP,'COMM':COMM, 'authorize':authorize()})
And I want to output the number of comments as a result, and I try to do things like that:
<a href="...">{{ COMM|length }} comments</a>
Thats does not work (yeah, since COMM is GqlQuery, not a list). What can I do with that? Is there a way to convert GqlQuery to list or is there another solution? (first question)[1]
Second question [2] is, how to filter this list in template? Is there a construct like this:
<a href="...">{{ COMM|where(reference=smth)|length }} comments</a>
so that I can get not only the number of all comments, but only comments with certain db.ReferenceProperty() property, for example.
Last question [3]: is it weird to do such things using templates?
UPD: Questions [1] and [3] are pretty much clear to me, thanks to Nick Johnson and Alex Martelli.
Question [2] is tricky and maybe against the idea of MVC, but I really hope to solve it with templates only :(there are some reasons). It may be as ugly as it gets.
A:
Call .fetch() on the query, returning a list of results, before passing it to the template. Any other solution - such as calling .count() - will result in executing the query multiple times, which wastes CPU and wall-clock time.
Likewise, if you need to filter the query, you should do this in your own code, before passing the results to the template system.
A:
You could use count on your GqlQuery object, but a GqlQuery doesn't let you add where clauses and the like -- you need Query for that (and its filter method).
Yes, it's very unusual to "pollute" the view logic (i.e., templates) with business logic aspects such as filtering. Normally, the server-side Python code would perform such calls and inject the results in the context, leaving the view logic (template) to deal strictly with presentation issues only -- server side decides what to show, view logic decides only how to show it.
If you prefer a less usual style, with lots of logic in the templates (an architecture that many do consider weird), consider alternative templating systems such as Mako, because the Django templating system is really designed against such "weird architecture";-).
A:
I'm not exactly sure what your trying to accomplish, but you could possibly benefit from URL Mapping, however it will require some extra code. The basic idea is that you would turn whatever value you want to filter against into a "directory". Examples will help:
<a href="basepath/{{ value.tofilterfrom }}">link text</a>
Then in your python code you would need modify your WSGIApplication object with a unique handler. Something like:
application = WSGIApplication(
[('/', MainPage),
(r'/basepath/(.*)', Products),
Just create a new class called Products, and it will automatically pick up the filter value and store it in a variable for you, like so:
class Products(webapp.RequestHandler):
def get(self, ProductID):
And thats it, you can expand this as much as you want, add more levels. In the class Products you would just filter your Query object using the ProductID variable as your criteria.
I have a more in depth write up at my Blog if you want to read more on this.
| GAE/Django Templates (0.96) filters to get LENGTH of GqlQuery and filter it | I pass the query with comments to my template:
COMM = CommentModel.gql("ORDER BY created")
doRender(self,CP.template,{'CP':CP,'COMM':COMM, 'authorize':authorize()})
And I want to output the number of comments as a result, and I try to do things like that:
<a href="...">{{ COMM|length }} comments</a>
Thats does not work (yeah, since COMM is GqlQuery, not a list). What can I do with that? Is there a way to convert GqlQuery to list or is there another solution? (first question)[1]
Second question [2] is, how to filter this list in template? Is there a construct like this:
<a href="...">{{ COMM|where(reference=smth)|length }} comments</a>
so that I can get not only the number of all comments, but only comments with certain db.ReferenceProperty() property, for example.
Last question [3]: is it weird to do such things using templates?
UPD: Questions [1] and [3] are pretty much clear to me, thanks to Nick Johnson and Alex Martelli.
Question [2] is tricky and maybe against the idea of MVC, but I really hope to solve it with templates only :(there are some reasons). It may be as ugly as it gets.
| [
"Call .fetch() on the query, returning a list of results, before passing it to the template. Any other solution - such as calling .count() - will result in executing the query multiple times, which wastes CPU and wall-clock time.\nLikewise, if you need to filter the query, you should do this in your own code, befor... | [
3,
1,
0
] | [] | [] | [
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0002533306_django_templates_google_app_engine_python.txt |
Q:
sqlachemy, says decimal is not defined?
Trying to make a column of type decimal:
Column('cost', DECIMAL)
Erorr, name 'DECIMAL' is not defined.
SqlAlch seems to support decimal, am I missing an import?
BTW, how do I also create a longtext column?
I'm using mysql.
A:
try
import sqlalchemy.types.DECIMAL as DECIMAL
| sqlachemy, says decimal is not defined? | Trying to make a column of type decimal:
Column('cost', DECIMAL)
Erorr, name 'DECIMAL' is not defined.
SqlAlch seems to support decimal, am I missing an import?
BTW, how do I also create a longtext column?
I'm using mysql.
| [
"try\nimport sqlalchemy.types.DECIMAL as DECIMAL\n\n"
] | [
3
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0003376465_mysql_python_sqlalchemy.txt |
Q:
help on getting image src from a table cell using BeautifulSoup
So I have a html page that has a form, and a table inside the form that has rows of products.
I got to the point now where I am looping through the table rows, and in each loop I grab all the table cells.
for tr in t.findAll('tr'):
td = tr.findAll('td')
Now I want to grab the image src url from the first td.
Html looks like:
<tr>
<td ...>
<a href ... >
<img ... src="asdf/asdf.jpg" .. >
</a>
</td>
...
</tr>
How would I go about doing this? I keep thinking in terms of regex.
I tried:
td[0].a.image.src but that didn't work as it says no attribute 'src'.
A:
Use
td[0].a.img['src']
I imagine your use of image for img in the question was just a transcription error, but the important point is that, in BeautifulSoup, in order to access a tag's HTML attributes you use indexing notation (like the ['src'] in my code snippet above), not dot-syntax -- the dot-syntax notation actually proceeds down the tree instead (just as it's doing above for the two dots, one each just before a and img).
| help on getting image src from a table cell using BeautifulSoup | So I have a html page that has a form, and a table inside the form that has rows of products.
I got to the point now where I am looping through the table rows, and in each loop I grab all the table cells.
for tr in t.findAll('tr'):
td = tr.findAll('td')
Now I want to grab the image src url from the first td.
Html looks like:
<tr>
<td ...>
<a href ... >
<img ... src="asdf/asdf.jpg" .. >
</a>
</td>
...
</tr>
How would I go about doing this? I keep thinking in terms of regex.
I tried:
td[0].a.image.src but that didn't work as it says no attribute 'src'.
| [
"Use\ntd[0].a.img['src']\n\nI imagine your use of image for img in the question was just a transcription error, but the important point is that, in BeautifulSoup, in order to access a tag's HTML attributes you use indexing notation (like the ['src'] in my code snippet above), not dot-syntax -- the dot-syntax notati... | [
6
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003376507_beautifulsoup_python.txt |
Q:
how do I halt execution in a python script?
Possible Duplicates:
Programatically stop execution of python script?
Terminating a Python script
I want to print a value, and then halt execution of the script.
Do I just use return?
A:
You can use return inside the main function in you have one, but this isn't guaranteed to quit the script if there is more code after your call to main.
The simplest that nearly always works is sys.exit():
import sys
sys.exit()
Other possibilities:
Raise an error which isn't caught.
Let the execution point reach the end of the script.
If you are in a thread other than the main thread use thread.interrupt_main().
A:
There's exit function in sys module ( docs ):
import sys
sys.exit( 0 ) # 0 will be passed to OS
You can also
raise SystemExit
or any other exception that won't be caught.
A:
sys.exit
| how do I halt execution in a python script? |
Possible Duplicates:
Programatically stop execution of python script?
Terminating a Python script
I want to print a value, and then halt execution of the script.
Do I just use return?
| [
"You can use return inside the main function in you have one, but this isn't guaranteed to quit the script if there is more code after your call to main.\nThe simplest that nearly always works is sys.exit():\nimport sys\nsys.exit()\n\nOther possibilities:\n\nRaise an error which isn't caught.\nLet the execution poi... | [
21,
7,
6
] | [] | [] | [
"python"
] | stackoverflow_0003376534_python.txt |
Q:
How to get rid of spacing in SimpleDocTemplate(). Python. ReportLab
Do someone know if it possible to delete default spancing when i'm making PDF document with SimpleDocTemplate().
I want it to print from corner to corner.
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
# Our container for 'Flowable' objects
elements = []
# A large collection of style sheets pre-made for us
styles = getSampleStyleSheet()
# A basic document for us to write to 'rl_hello_table.pdf'
doc = SimpleDocTemplate(response)
# elements.append(Paragraph("Wumpus vs Cave Population Report",
# styles['Title']))
data = [
['Deep Ditch', 50],
['Death Gully', 5000],
['Dire Straits', 600],
['Deadly Pit', 5],
['Deep Ditch', 50],
['Deep Ditch', 50],
['Death Gully', 5000],
['Dire Straits', 600],
['Deadly Pit', 5],
['Deep Ditch', 50],
]
# Create the table with the necessary style, and add it to the
# elements list.
table = Table(data, colWidths=270, rowHeights=70)
elements.append(table)
# Write the document to response
doc.build(elements)
return response
A:
Try:
doc = SimpleDocTemplate(response, rightMargin=0, leftMargin=0, topMargin=0, bottomMargin=0)
| How to get rid of spacing in SimpleDocTemplate(). Python. ReportLab | Do someone know if it possible to delete default spancing when i'm making PDF document with SimpleDocTemplate().
I want it to print from corner to corner.
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
# Our container for 'Flowable' objects
elements = []
# A large collection of style sheets pre-made for us
styles = getSampleStyleSheet()
# A basic document for us to write to 'rl_hello_table.pdf'
doc = SimpleDocTemplate(response)
# elements.append(Paragraph("Wumpus vs Cave Population Report",
# styles['Title']))
data = [
['Deep Ditch', 50],
['Death Gully', 5000],
['Dire Straits', 600],
['Deadly Pit', 5],
['Deep Ditch', 50],
['Deep Ditch', 50],
['Death Gully', 5000],
['Dire Straits', 600],
['Deadly Pit', 5],
['Deep Ditch', 50],
]
# Create the table with the necessary style, and add it to the
# elements list.
table = Table(data, colWidths=270, rowHeights=70)
elements.append(table)
# Write the document to response
doc.build(elements)
return response
| [
"Try:\ndoc = SimpleDocTemplate(response, rightMargin=0, leftMargin=0, topMargin=0, bottomMargin=0)\n\n"
] | [
6
] | [] | [] | [
"django",
"pdf_generation",
"python"
] | stackoverflow_0003374296_django_pdf_generation_python.txt |
Q:
Store Information In MySQL Database with Python
I am working on a huge project. I have been working on it for a while now, and decided to "up" the security on the way the software handles data. I already know how to encrypt and decrypt the data strings using DES encryption, but what I am not sure about is where to put that encrypted data. I would like to store everything in a MySQL database, but haven't quite figured out how to work with the database. I have done some Googling, but to no prevail.
I need to store the following for each account:
Username
Password
Sec. Question
Sec. Answer
Email
List of keywords
List of web URLs
I think storing this information would be like creating tables in the database, but I'm not sure. Maybe a table for the user, then more tables for the rest inside the table for the user? I am not sure how to work with MySQL databases from Python, so any help will be greatly appreciated.
Sorry for the late edit, I just realized I needed to clean it up a little.
A:
Here's an example of what the schema could look like:
user
user_id (PK)
username (char)
password (char)
security_question_id (FK)
security_answer (char)
email_address (char)
security_question
security_question_id (PK)
question (char)
keyword
keyword_id (PK)
keyword (char)
user_keyword
user_keyword_id (PK)
user_id (FK)
keyword_id (FK)
url
url_id (PK)
user_id (FK)
url (char)
PK = Primary Key
FK = Foreign Key
char = varchar of some max length that you define
Assumptions:
There is a standard list of security questions to choose from.
A lot of users may have the same keyword, so they're put in their own table.
URLs are more unique, so just store the url and user_id together. If you want, you could change this to the shared pattern the keywords use.
Nothing is nullable, all fields are required.
As I commented, I recommend hasing passwords (with a salt). No need to be recoverable, they can reset the password. I've mimicked Django's password style in the past:
sha1$8ac10f$a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
That's: hash method, salt and password hash, delimited by $ characters. You can just generate a random string as salt. Add it to the password before hashing. Store a string like that one shown in the password field. To test a password for correctness, extract those 3 fields, append the salt to the user-entered password, apply the hash and compare to the hash (3rd field) in the database. If they match, the password is correct.
I would personally use SQLAlchemy.
A:
You have two choices, essentially:
Use the mysqldb module
Use an Object Relation Manager (ORM) like SQLAlchemy
Do you know how to make a table, in general?
For mysql, you'd make your example DB by logging in, creating a database, selecting (use) that database, then
create table account(
username varchar(32),
password varchar(128),
sec_question varchar(512),
sec_answer varchar(128),
email_address varchar(128)
);
The list or URLs and keywords would be best done as separate tables, though describing that is out of the scope of this answer!
Note that's not a comprehensive or the best way to do your table necessarily, and not the way you'd probably create it with an ORM, but is just an example.
To create a secure and credible password system, you're going to need to do a lot of research on that. I'm sure people around here would be happy to help you understand hashing, etc.
Here's a link to a good article on using the MySQLdb module.
| Store Information In MySQL Database with Python | I am working on a huge project. I have been working on it for a while now, and decided to "up" the security on the way the software handles data. I already know how to encrypt and decrypt the data strings using DES encryption, but what I am not sure about is where to put that encrypted data. I would like to store everything in a MySQL database, but haven't quite figured out how to work with the database. I have done some Googling, but to no prevail.
I need to store the following for each account:
Username
Password
Sec. Question
Sec. Answer
Email
List of keywords
List of web URLs
I think storing this information would be like creating tables in the database, but I'm not sure. Maybe a table for the user, then more tables for the rest inside the table for the user? I am not sure how to work with MySQL databases from Python, so any help will be greatly appreciated.
Sorry for the late edit, I just realized I needed to clean it up a little.
| [
"Here's an example of what the schema could look like:\nuser\n user_id (PK)\n username (char)\n password (char)\n security_question_id (FK)\n security_answer (char)\n email_address (char)\n\nsecurity_question\n security_question_id (PK)\n question (char)\n\nkeyword\n keyword_id (PK)\n ... | [
2,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003376634_mysql_python.txt |
Q:
Using BeautifulSoup, how to guard against elements not being found?
I am looping through table rows in a table, but the first 1 or 2 rows doesn't have the elements I am looking for (they are for table column headers etc.).
So after say the 3rd table row, there are elements in the table cells (td) that have what I am looking for.
e.g.
td[0].a.img['src']
But calling this fails since the first few rows don't have this.
How can I guard against these cases so my script doesn't fail?
I get errors like:
nonetype object is unsubscriptable
A:
Simplest and clearest, if you want your code "in line":
theimage = td[0].a.img
if theimage is not None:
use(theimage['src'])
Or, preferably, wrap the None check in a tiny function of your own, e.g.:
def getsrc(image):
return None if image is None else image['src']
and use getsrc(td[0].a.img).
A:
Starting from tr:
for td in tr.findChildren('td'):
img = td.findChild('img')
if img:
src = img.get('src', '') # return a blank string if there's no src attribute
if src:
# do something with src
| Using BeautifulSoup, how to guard against elements not being found? | I am looping through table rows in a table, but the first 1 or 2 rows doesn't have the elements I am looking for (they are for table column headers etc.).
So after say the 3rd table row, there are elements in the table cells (td) that have what I am looking for.
e.g.
td[0].a.img['src']
But calling this fails since the first few rows don't have this.
How can I guard against these cases so my script doesn't fail?
I get errors like:
nonetype object is unsubscriptable
| [
"Simplest and clearest, if you want your code \"in line\":\ntheimage = td[0].a.img\nif theimage is not None:\n use(theimage['src'])\n\nOr, preferably, wrap the None check in a tiny function of your own, e.g.:\ndef getsrc(image):\n return None if image is None else image['src']\n\nand use getsrc(td[0].a.img).\n",... | [
5,
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003376666_beautifulsoup_python.txt |
Q:
Object propert is an integer, have to use regex to clean input, looking for good style
I have some text that looks like:
California(2342)
My object has a property that I need to assign the value 2342 to.
I'm looking for input on how to go about doing this, and guarding against any potential for errors in the input.
c = SomeClass()
c.count = re.compile(r'(\d*)').groups[0]
Does that look ok? Or should I do an IF statement and set the count to 0 in case the input was bad?
P.S any help in the regex would be appreciated, this is my first serious python script.
A:
import re
pat = re.compile(r'\w+\((\d+)\)')
s = 'California(2342)'
match = pat.match(s)
if match:
c.count = match.group(1)
print c.count
# '2342'
else:
c.count = '0' # or 0 if numeric
If you want a number back instead of a string just modify:
value = int(match.group(1))
| Object propert is an integer, have to use regex to clean input, looking for good style | I have some text that looks like:
California(2342)
My object has a property that I need to assign the value 2342 to.
I'm looking for input on how to go about doing this, and guarding against any potential for errors in the input.
c = SomeClass()
c.count = re.compile(r'(\d*)').groups[0]
Does that look ok? Or should I do an IF statement and set the count to 0 in case the input was bad?
P.S any help in the regex would be appreciated, this is my first serious python script.
| [
"import re\n\npat = re.compile(r'\\w+\\((\\d+)\\)')\n\ns = 'California(2342)'\nmatch = pat.match(s)\nif match:\n c.count = match.group(1)\n print c.count\n # '2342'\nelse:\n c.count = '0' # or 0 if numeric\n\nIf you want a number back instead of a string just modify:\nvalue = int(match.group(1))\n\n"
] | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003376700_python_regex.txt |
Q:
Can someone please explain this bit of Python code?
I started working in Python just recently and haven't fully learned all the nuts and bolts of it, but recently I came across this post that explains why python has closures, in there, there is a sample code that goes like this:
y = 0
def foo():
x = [0]
def bar():
print x[0], y
def change(z):
global y
x[0] = y = z
change(1)
bar()
change(2)
bar()
change(3)
bar()
change(4)
bar()
foo()
1 1
2 2
3 3
and basically I don't understand how it actually works, and what construct like x[0] does in this case, or actually I understand what it's doing, I just don't get how is it this :)
A:
Before the nonlocal keyword was added in Python 3 (and still today, if you're stuck on 2.* for whatever reason), a nested function just couldn't rebind a local barename of its outer function -- because, normally, an assignment statement to a barename, such as x = 23, means that x is a local name for the function containing that statement. global exists (and has existed for a long time) to allow assignments to bind or rebind module-level barenames -- but nothing (except for nonlocal in Python 3, as I said) to allow assignments to bind or rebind names in the outer function.
The solution is of course very simple: since you cannot bind or rebind such a barename, use instead a name that is not bare -- an indexing or an attribute of some object named in the outer function. Of course, said object must be of a type that lets you rebind an indexing (e.g., a list), or one that lets you bind or rebind an attribute (e.g., a function), and a list is normally the simplest and most direct approach for this. x is exactly that list in this code sample -- it exists only in order to let nested function change rebind x[0].
A:
It might be simpler to understand if you look at this simplified code where I have removed the global variable:
def foo():
x = [0]
def bar():
print x[0]
def change(z):
x[0] = z
change(1)
bar()
foo()
The first line in foo creates a list with one element. Then bar is defined to be a function which prints the first element in x and the function change modifies the first element of the list. When change(1) is called the value of x becomes [1].
A:
This code is trying to explain when python creates a new variable, and when python reuses an existing variable. I rewrote the above code slightly to make the point more clear.
y = "lion"
def foo():
x = ["tiger"]
w = "bear"
def bar():
print y, x[0], w
def change(z):
global y
x[0] = z
y = z
w = z
bar()
change("zap")
bar()
foo()
This will produce this output:
lion tiger bear
zap zap bear
The point is that the inner function change is able to affect the variable y, and the elements of array x, but it does not change w (because it gets its own local variable w that is not shared).
A:
x = [0] creates a new list with the value 0 in it. x[0] references the zero-eth element in the list, which also happens to be zero.
The example is referencing closures, or passable blocks of code within code.
| Can someone please explain this bit of Python code? | I started working in Python just recently and haven't fully learned all the nuts and bolts of it, but recently I came across this post that explains why python has closures, in there, there is a sample code that goes like this:
y = 0
def foo():
x = [0]
def bar():
print x[0], y
def change(z):
global y
x[0] = y = z
change(1)
bar()
change(2)
bar()
change(3)
bar()
change(4)
bar()
foo()
1 1
2 2
3 3
and basically I don't understand how it actually works, and what construct like x[0] does in this case, or actually I understand what it's doing, I just don't get how is it this :)
| [
"Before the nonlocal keyword was added in Python 3 (and still today, if you're stuck on 2.* for whatever reason), a nested function just couldn't rebind a local barename of its outer function -- because, normally, an assignment statement to a barename, such as x = 23, means that x is a local name for the function c... | [
9,
5,
4,
2
] | [] | [] | [
"closures",
"python"
] | stackoverflow_0003376643_closures_python.txt |
Q:
Width of widget
In PyGTK what is the easiest way to figure out the dimensions of a widget? I know that it is easy to do with the gtk.Window object, but I can't find in the reference manual any way to get dimensions for the other objects.
Any help is greatly appreciated thanks :D
A:
You may be looking for the get_allocation method:
The get_allocation() method returns a
gtk.gdk.Rectangle containing the
bounds of the widget's allocation.
or size_request:
The size_request() method returns the
preferred size of a widget as a tuple
containing its required width and
height. This method is typically used
when implementing a gtk.Container
subclass to arrange the container's
child widgets and decide what size
allocations to give them with the
size_allocate() method. Obtaining a
size request requires that the widget
be associated with a screen, because
font information may be needed.
Also remember that the size request is
not necessarily the size a widget will
actually be allocated.
The latter is what the widget would like to have as its size (given font information), the former what it's actually given by its container when it lays out the widgets.
| Width of widget | In PyGTK what is the easiest way to figure out the dimensions of a widget? I know that it is easy to do with the gtk.Window object, but I can't find in the reference manual any way to get dimensions for the other objects.
Any help is greatly appreciated thanks :D
| [
"You may be looking for the get_allocation method:\n\nThe get_allocation() method returns a\n gtk.gdk.Rectangle containing the\n bounds of the widget's allocation.\n\nor size_request:\n\nThe size_request() method returns the\n preferred size of a widget as a tuple\n containing its required width and\n height. ... | [
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003376791_gtk_pygtk_python.txt |
Q:
Captcha solution which can be used with App Engine?
Is there a simple captcha solution which can be easily integrated with a form deployed using Google App Engine? I am using Python.
A:
Recaptcha. It does work with Python.
http://www.google.com/recaptcha
http://code.google.com/apis/recaptcha/docs/otherplatforms.html
http://pypi.python.org/pypi/recaptcha-client
A:
I didn't test, but I guess this can work: http://daily.profeth.de/2008/04/using-recaptcha-with-google-app-engine.html, he use reCaptcha
| Captcha solution which can be used with App Engine? | Is there a simple captcha solution which can be easily integrated with a form deployed using Google App Engine? I am using Python.
| [
"Recaptcha. It does work with Python.\nhttp://www.google.com/recaptcha\nhttp://code.google.com/apis/recaptcha/docs/otherplatforms.html\nhttp://pypi.python.org/pypi/recaptcha-client\n",
"I didn't test, but I guess this can work: http://daily.profeth.de/2008/04/using-recaptcha-with-google-app-engine.html, he use re... | [
5,
1
] | [] | [] | [
"api",
"captcha",
"google_app_engine",
"python"
] | stackoverflow_0003376797_api_captcha_google_app_engine_python.txt |
Q:
sqlachemy created mysql table, but I modified table now says 'unknown column url'
I added a url column in my table, and now sqlalchemy is saying 'unknown column url'.
Why isn't it updating the table?
There must be a setting when I create the session?
I am doing:
Session = sessionmaker(bind=engine)
Is there something I am missing?
I want it to update any table that doesn't have a property that I added to my Table structure in my python code.
A:
I'm not sure SQLAlchemy supports schema migration that well (atleast the last time I touched it, it wasn't there).
A couple of options.
Don't manually specify your tables. Use the autoload feature to have SQLAlchemy automatically read out the columns from your database. This will require tests to make sure that it works but you get the idea in generally. DRY.
Try SQLAlchemy migrate.
Manually update the table after you change the model specification.
A:
In cases when you just add new columns, you can safely use metadata.create_all(bind=engine) to update your schema from your class definitions.
However this will NOT modify existing columns or remove columns from DB schema if you remove them in SQLA definition.
| sqlachemy created mysql table, but I modified table now says 'unknown column url' | I added a url column in my table, and now sqlalchemy is saying 'unknown column url'.
Why isn't it updating the table?
There must be a setting when I create the session?
I am doing:
Session = sessionmaker(bind=engine)
Is there something I am missing?
I want it to update any table that doesn't have a property that I added to my Table structure in my python code.
| [
"I'm not sure SQLAlchemy supports schema migration that well (atleast the last time I touched it, it wasn't there). \nA couple of options. \n\nDon't manually specify your tables. Use the autoload feature to have SQLAlchemy automatically read out the columns from your database. This will require tests to make sure t... | [
1,
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003376788_python_sqlalchemy.txt |
Q:
beautifulsoup, Find th with text 'price', then get price from next th
My html looks like:
<td>
<table ..>
<tr>
<th ..>price</th>
<th>$99.99</th>
</tr>
</table>
</td>
So I am in the current table cell, how would I get the 99.99 value?
I have so far:
td[3].findChild('th')
But I need to do:
Find th with text 'price', then get next th tag's string value.
A:
Think about it in "steps"... given that some x is the root of the subtree you're considering,
x.findAll(text='price')
is the list of all items in that subtree containing text 'price'. The parents of those items then of course will be:
[t.parent for t in x.findAll(text='price')]
and if you only want to keep those whose "name" (tag) is 'th', then of course
[t.parent for t in x.findAll(text='price') if t.parent.name=='th']
and you want the "next siblings" of those (but only if they're also 'th's), so
[t.parent.nextSibling for t in x.findAll(text='price')
if t.parent.name=='th' and t.parent.nextSibling and t.parent.nextSibling.name=='th']
Here you see the problem with using a list comprehension: too much repetition, since we can't assign intermediate results to simple names. Let's therefore switch to a good old loop...:
Edit: added tolerance for a string of text between the parent th and the "next sibling" as well as tolerance for the latter being a td instead, per OP's comment.
for t in x.findAll(text='price'):
p = t.parent
if p.name != 'th': continue
ns = p.nextSibling
if ns and not ns.name: ns = ns.nextSibling
if not ns or ns.name not in ('td', 'th'): continue
print ns.string
I've added ns.string, that will give the next sibling's contents if and only if they're just text (no further nested tags) -- of course you can instead analize further at this point, depends on your application's needs!-). Similarly, I imagine you won't be doing just print but something smarter, but I'm giving you the structure.
Talking about the structure, notice that twice I use if...: continue: this reduces nesting compared to the alternative of inverting the if's condition and indenting all the following statements in the loop -- and "flat is better than nested" is one of the koans in the Zen of Python (import this at an interactive prompt to see them all and meditate;-).
A:
With pyparsing, it's easy to reach into the middle of some HTML for a tag pattern like this:
from pyparsing import makeHTMLTags, Combine, Word, nums
th,thEnd = makeHTMLTags("TH")
floatnum = Combine(Word(nums) + "." + Word(nums))
priceEntry = (th + "price" + thEnd +
th + "$" + floatnum("price") + thEnd)
tokens,startloc,endloc = priceEntry.scanString(html).next()
print tokens.price
Pyparsing's makeHTMLTags helper returns a pair of pyparsing expressions, one for the start tag and one for the end tag. The start tag pattern is much more than just adding "<>"s around the given string, but also allows for extra whitespace, variable case, and the presence or absence of tag attributes. For instance, note that even though I specified "TH" as the table head tag, it will also match "th", "Th", "tH" and "TH". Pyparsing's default whitespace skipping behavior will also handle extra spaces, between tag and "$", between "$" and numeric price, etc., without having to sprinkle "zero or more whitespace chars could go here" indicators. Lastly, by assigning the results name "price" (following floatum in the definition of priceEntry), it makes it very simple to access that specific value from the full list of tokens matching the overall priceEntry expression.
(Combine is used for 2 purposes: it disallows whitespace between the components of the number; and returns a single combined token "99.99" instead of the list ["99", ".", "99"].)
| beautifulsoup, Find th with text 'price', then get price from next th | My html looks like:
<td>
<table ..>
<tr>
<th ..>price</th>
<th>$99.99</th>
</tr>
</table>
</td>
So I am in the current table cell, how would I get the 99.99 value?
I have so far:
td[3].findChild('th')
But I need to do:
Find th with text 'price', then get next th tag's string value.
| [
"Think about it in \"steps\"... given that some x is the root of the subtree you're considering,\nx.findAll(text='price')\n\nis the list of all items in that subtree containing text 'price'. The parents of those items then of course will be:\n[t.parent for t in x.findAll(text='price')]\n\nand if you only want to k... | [
8,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003376803_beautifulsoup_python.txt |
Q:
Python - SqlAlchemy. How to relate tables from different modules or files?
I have this class in one file and item class in another file in the same module. If they are in different modules or files when I define a new Channel, I got an error because Item is not in the same file. How can I solve this problem? If both classes are in the same file, I don't get any error.
ChannelTest.py
from ItemTest import Item
metadata = rdb.MetaData()
channel_items = Table(
"channel_items",
metadata,
Column("channel_id", Integer,
ForeignKey("channels.id")),
Column("item_id", Integer,
ForeignKey("items.id"))
)
class Channel(rdb.Model):
""" Set up channels table in the database """
rdb.metadata(metadata)
rdb.tablename("channels")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
items = relation("Item",
secondary=channel_items, backref="channels")
Item.py Different file, but in the same module
class Item(rdb.Model):
""" Set up items table in the database """
rdb.metadata(metadata)
rdb.tablename("items")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
Thanks in advance!
A:
"NoReferencedTableError: Could not find table 'items' with which to generate a foreign key"
All your table definitions should share metadata object.
So you should do metadata = rdb.MetaData() in some separate module, and then use this metadata instance in ALL Table()'s.
A:
The string method should work, but if it doesn't than there is also the option of simply importing the module.
And if that gives you import loops than you can still add the property after instantiating the class like this:
import item
Channel.items = relation(item.Item,
secondary=item.channel_items,
backref='channels')
| Python - SqlAlchemy. How to relate tables from different modules or files? | I have this class in one file and item class in another file in the same module. If they are in different modules or files when I define a new Channel, I got an error because Item is not in the same file. How can I solve this problem? If both classes are in the same file, I don't get any error.
ChannelTest.py
from ItemTest import Item
metadata = rdb.MetaData()
channel_items = Table(
"channel_items",
metadata,
Column("channel_id", Integer,
ForeignKey("channels.id")),
Column("item_id", Integer,
ForeignKey("items.id"))
)
class Channel(rdb.Model):
""" Set up channels table in the database """
rdb.metadata(metadata)
rdb.tablename("channels")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
items = relation("Item",
secondary=channel_items, backref="channels")
Item.py Different file, but in the same module
class Item(rdb.Model):
""" Set up items table in the database """
rdb.metadata(metadata)
rdb.tablename("items")
id = Column("id", Integer, primary_key=True)
title = Column("title", String(100))
Thanks in advance!
| [
"\n\"NoReferencedTableError: Could not find table 'items' with which to generate a foreign key\"\n\nAll your table definitions should share metadata object. \nSo you should do metadata = rdb.MetaData() in some separate module, and then use this metadata instance in ALL Table()'s.\n",
"The string method should wor... | [
1,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003357825_python_sqlalchemy.txt |
Q:
Having some trouble creating my Model in Pylons
I've been reading the Pylons Book and, having got to the part about Models, realise it's out of date. So I then switched over to the official Pylons documentation for creating Models in Pylons 1.0 - http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/
I've followed what they've got and it's still failing.
./blog/model/init.py
"""The application's model objects"""
from sqlalchemy import orm, Column, Unicode, UnicodeText
from blog.model.meta import Session, Base
def init_model(engine):
"""Call me before using any of the tables or classes in the model"""
Session.configure(bind=engine)
class Page(Base):
__tablename__ = 'pages'
title = Column(Unicode(40), primary_key=True)
content = Column(UnicodeText(), default=u'')
class Page(object):
def __init__(self, title, content=None):
self.title = title
self.content = content
def __unicode__(self):
return self.title
__str__ = __unicode__
orm.mapper(Page, pages_table)
Having two classes with the same name kind of blows my mind... But nevertheless, it's what the tutorial says to do.
When I try to run my code, however, I get:
28, in <module>
orm.mapper(Page, pages_table)
NameError: name 'pages_table' is not defined
Sup with this? How can I get this to not fail? :/
A:
First, you should not declare two classes with same name. How is that supposed to work at all?
Second, you probably would want to read official SQLA docs, not Pylons. Pylons docs are a bit messy after upgrade, and still have a lot of 0.9.7 references.
Declarative extension is described here: http://www.sqlalchemy.org/docs/reference/ext/declarative.html
Third, declarative means you do not need to bind class to table, it is done in the class definition.
This is sufficient declaration of the mapping, you can proceed to using it:
class Page(Base):
__tablename__ = 'pages'
title = Column(Unicode(40), primary_key=True)
content = Column(UnicodeText(), default=u'')
def __init__(self, title, content=None):
self.title = title
self.content = content
def __unicode__(self):
return self.title
__str__ = __unicode__
| Having some trouble creating my Model in Pylons | I've been reading the Pylons Book and, having got to the part about Models, realise it's out of date. So I then switched over to the official Pylons documentation for creating Models in Pylons 1.0 - http://pylonshq.com/docs/en/1.0/tutorials/quickwiki_tutorial/
I've followed what they've got and it's still failing.
./blog/model/init.py
"""The application's model objects"""
from sqlalchemy import orm, Column, Unicode, UnicodeText
from blog.model.meta import Session, Base
def init_model(engine):
"""Call me before using any of the tables or classes in the model"""
Session.configure(bind=engine)
class Page(Base):
__tablename__ = 'pages'
title = Column(Unicode(40), primary_key=True)
content = Column(UnicodeText(), default=u'')
class Page(object):
def __init__(self, title, content=None):
self.title = title
self.content = content
def __unicode__(self):
return self.title
__str__ = __unicode__
orm.mapper(Page, pages_table)
Having two classes with the same name kind of blows my mind... But nevertheless, it's what the tutorial says to do.
When I try to run my code, however, I get:
28, in <module>
orm.mapper(Page, pages_table)
NameError: name 'pages_table' is not defined
Sup with this? How can I get this to not fail? :/
| [
"First, you should not declare two classes with same name. How is that supposed to work at all?\nSecond, you probably would want to read official SQLA docs, not Pylons. Pylons docs are a bit messy after upgrade, and still have a lot of 0.9.7 references.\nDeclarative extension is described here: http://www.sqlalchem... | [
4
] | [] | [] | [
"model",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0003377013_model_pylons_python_sqlalchemy.txt |
Q:
method factories which take class attributes as parameters
I'm finding it useful to create "method factory functions" that wrap a parametrized object attribute in some logic.
For example:
"""Fishing for answers.
>>> one().number_fisher()
'one fish'
>>> one().colour_fisher()
'red fish'
>>> two().number_fisher()
'two fish'
>>> two().colour_fisher()
'blue fish'
"""
class one(object):
def number(self):
return 'one'
def colour(self):
return 'red'
def _make_fisher(sea):
def fisher(self):
return '{0} fish'.format(getattr(self, sea)())
return fisher
number_fisher = _make_fisher('number')
colour_fisher = _make_fisher('colour')
class two(one):
def number(self):
return 'two'
def colour(self):
return 'blue'
Is it necessary to pass the attribute to make_fisher as a string, or is there a better way to do this?
If I pass and use an actual attribute, this will break polymorphism, since instances of two will still be using that same reference to the attribute object.
I.E.
diff --git a/fishery.py b/fishery.py
index 840e85d..b98cf72 100644
--- a/fishery.py
+++ b/fishery.py
@@ -4,10 +4,12 @@
'one fish'
>>> one().colour_fisher()
'red fish'
+
+This version does not implement polymorphism, and so this happens:
>>> two().number_fisher()
-'two fish'
+'one fish'
>>> two().colour_fisher()
-'blue fish'
+'red fish'
"""
@@ -18,10 +20,10 @@ class one(object):
return 'red'
def _make_fisher(sea):
def fisher(self):
- return '{0} fish'.format(getattr(self, sea)())
+ return '{0} fish'.format(sea(self))
return fisher
- number_fisher = _make_fisher('number')
- colour_fisher = _make_fisher('colour')
+ number_fisher = _make_fisher(number)
+ colour_fisher = _make_fisher(colour)
class two(one):
def number(self):
It seems a bit weak to have to use a string to reference the attribute, but I'm not seeing another way to do this. Is there?
A:
"One more level of indirection" (sometimes proposed as programming's magic panacea;-) -- just like for typical decorators like property. E.g.:
def makefisher(fun):
def fisher(self):
return '{0} fish'.format(fun(self))
return fisher
class one(object):
def number(self): return self._number()
def _number(self): return 'one'
number_fisher = makefisher(number)
class two(one):
def _number(self): return 'two'
Basically, the function you wrap is the "organizing function" in a peculiarly simple variant of the Template Method DP, and the one you override is the "hook function" in that same DP. Or at least, that's one way to look at it, the other being the "extra level of indirection" one I started out with;-).
| method factories which take class attributes as parameters | I'm finding it useful to create "method factory functions" that wrap a parametrized object attribute in some logic.
For example:
"""Fishing for answers.
>>> one().number_fisher()
'one fish'
>>> one().colour_fisher()
'red fish'
>>> two().number_fisher()
'two fish'
>>> two().colour_fisher()
'blue fish'
"""
class one(object):
def number(self):
return 'one'
def colour(self):
return 'red'
def _make_fisher(sea):
def fisher(self):
return '{0} fish'.format(getattr(self, sea)())
return fisher
number_fisher = _make_fisher('number')
colour_fisher = _make_fisher('colour')
class two(one):
def number(self):
return 'two'
def colour(self):
return 'blue'
Is it necessary to pass the attribute to make_fisher as a string, or is there a better way to do this?
If I pass and use an actual attribute, this will break polymorphism, since instances of two will still be using that same reference to the attribute object.
I.E.
diff --git a/fishery.py b/fishery.py
index 840e85d..b98cf72 100644
--- a/fishery.py
+++ b/fishery.py
@@ -4,10 +4,12 @@
'one fish'
>>> one().colour_fisher()
'red fish'
+
+This version does not implement polymorphism, and so this happens:
>>> two().number_fisher()
-'two fish'
+'one fish'
>>> two().colour_fisher()
-'blue fish'
+'red fish'
"""
@@ -18,10 +20,10 @@ class one(object):
return 'red'
def _make_fisher(sea):
def fisher(self):
- return '{0} fish'.format(getattr(self, sea)())
+ return '{0} fish'.format(sea(self))
return fisher
- number_fisher = _make_fisher('number')
- colour_fisher = _make_fisher('colour')
+ number_fisher = _make_fisher(number)
+ colour_fisher = _make_fisher(colour)
class two(one):
def number(self):
It seems a bit weak to have to use a string to reference the attribute, but I'm not seeing another way to do this. Is there?
| [
"\"One more level of indirection\" (sometimes proposed as programming's magic panacea;-) -- just like for typical decorators like property. E.g.:\ndef makefisher(fun):\n def fisher(self):\n return '{0} fish'.format(fun(self))\n return fisher\n\nclass one(object):\n def number(self): return self._number()\n ... | [
2
] | [] | [] | [
"factory_method",
"polymorphism",
"python"
] | stackoverflow_0003377014_factory_method_polymorphism_python.txt |
Q:
How do I set up rpy2?
Hi I just download rpy2 and Python 2.6. When I try to run some of example code I found on the internet, I got this error. Can anyone explain why this is happening and how can I fix it? Thanks.
import rpy2.robjects as RO
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import rpy2.robjects as RO
File "C:\Python26\lib\site-packages\rpy2\robjects\__init__.py", line 12, in <module>
import rpy2.rinterface as rinterface
File "C:\Python26\lib\site-packages\rpy2\rinterface\__init__.py", line 22, in <module>
"This might be because R.exe is nowhere in your Path.")
RuntimeError: Unable to determine R version from the registery.Calling the command 'R RHOME' does not return anything.
This might be because R.exe is nowhere in your Path.
A:
This might be because R.exe is nowhere
in your Path
This sounds like a big clue. Check the value of %PATH% in your Windows environment. I'd expect this to contain the location of R.EXE (probably something like C:\Programs\R\R-2.8.0\bin).
| How do I set up rpy2? | Hi I just download rpy2 and Python 2.6. When I try to run some of example code I found on the internet, I got this error. Can anyone explain why this is happening and how can I fix it? Thanks.
import rpy2.robjects as RO
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import rpy2.robjects as RO
File "C:\Python26\lib\site-packages\rpy2\robjects\__init__.py", line 12, in <module>
import rpy2.rinterface as rinterface
File "C:\Python26\lib\site-packages\rpy2\rinterface\__init__.py", line 22, in <module>
"This might be because R.exe is nowhere in your Path.")
RuntimeError: Unable to determine R version from the registery.Calling the command 'R RHOME' does not return anything.
This might be because R.exe is nowhere in your Path.
| [
"\nThis might be because R.exe is nowhere\n in your Path\n\nThis sounds like a big clue. Check the value of %PATH% in your Windows environment. I'd expect this to contain the location of R.EXE (probably something like C:\\Programs\\R\\R-2.8.0\\bin).\n"
] | [
1
] | [] | [] | [
"python",
"r"
] | stackoverflow_0003376867_python_r.txt |
Q:
Solving AttributeErrors in nested attributes
I am writing a small mocking class to do some tests.
But this class needs to support the idea of having nested attributes.
This example should provide some insight to the problem:
class Foo(object):
def __init__(self):
self.x = True
From the above class, we can have:
f = Foo()
f.x
I know I can add attributes falling back to __getattr__ to avoid an AttributeError, but what if I need something like this to be valid:
f = Foo()
f.x
f.x.y
f.x.y.z()
I know what to return if the object gets called as f.x.y.z() but I just need to find a way to get to z() that makes sense.
A:
You can "mock anything" by returning, on each attribute access, another instance of the "mock anything" class (which must also be callable, if you want to have the .z() part work;-).
E.g.:
class MockAny(object):
# mock special methods by making them noops
def __init__(self, *a, **k): pass
# or returning fixed values
def __len__(self): return 0
# mock attributes:
def getattr(self, name):
return MockAny()
# make it callable, if you need to
def __call__(self, *a, **k):
return MockAny()
The alternative, of course, is to know what it is that you're mocking (by introspection, or by some form of "declarative description", or simply by coding mock for specific things;-) rather than take the catch-all approach; but, the latter is also feasible, as you see in the above (partial) example.
Personally, I'd recommend using an existing mocking framework such as pymox rather than reinventing this particular wheel (also, the source code for such frameworks can be more instructive than a reasonably terse response on SO, like this one;-).
A:
If you are calling something like f.x.y.z() in your unit tests, the chances are you're trying to test too much. Each of these nested attributes should be covered by the unit tests for their particular classes.
Take another look at your Foo class and see if you can test its own behaviour in your unit tests.
Perhaps not the answer you were looking for, but hopefully one that will help in the long run.
| Solving AttributeErrors in nested attributes | I am writing a small mocking class to do some tests.
But this class needs to support the idea of having nested attributes.
This example should provide some insight to the problem:
class Foo(object):
def __init__(self):
self.x = True
From the above class, we can have:
f = Foo()
f.x
I know I can add attributes falling back to __getattr__ to avoid an AttributeError, but what if I need something like this to be valid:
f = Foo()
f.x
f.x.y
f.x.y.z()
I know what to return if the object gets called as f.x.y.z() but I just need to find a way to get to z() that makes sense.
| [
"You can \"mock anything\" by returning, on each attribute access, another instance of the \"mock anything\" class (which must also be callable, if you want to have the .z() part work;-).\nE.g.:\nclass MockAny(object):\n\n # mock special methods by making them noops\n def __init__(self, *a, **k): pass\n\n # or r... | [
3,
1
] | [] | [] | [
"nested_attributes",
"python"
] | stackoverflow_0003376566_nested_attributes_python.txt |
Q:
tornado server not returning response with self.write
I have a simple tornado server running like this:
import json
import suds
from suds.client import Client
import tornado.httpserver
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
url = "http://xx.xxx.xx.xxx/Service.asmx?WSDL"
client = Client(url)
resultCount = client.service.MyMethod()
self.write(json.dumps({'result_count':resultCount}))
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(6969)
tornado.ioloop.IOLoop.instance().start()
Now, I have a jquery function that calls this tornado code like this:
$.get("http://localhost:6969",
function(data){
alert(data);
$('#article-counter').empty().append(data).show();
});
For the life of me, I don't understand why data (the response) is blank. Even firebug shows a blank response (the http status is 200 though). Anybody have a clue??
A:
I finally figured out what was wrong: my app wasn't following the 'same domain origin' policy. So when the ajax request was being sent, the referrer header was from a different port than my tornado server. Naturally the server didn't return a response!
| tornado server not returning response with self.write | I have a simple tornado server running like this:
import json
import suds
from suds.client import Client
import tornado.httpserver
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
url = "http://xx.xxx.xx.xxx/Service.asmx?WSDL"
client = Client(url)
resultCount = client.service.MyMethod()
self.write(json.dumps({'result_count':resultCount}))
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(6969)
tornado.ioloop.IOLoop.instance().start()
Now, I have a jquery function that calls this tornado code like this:
$.get("http://localhost:6969",
function(data){
alert(data);
$('#article-counter').empty().append(data).show();
});
For the life of me, I don't understand why data (the response) is blank. Even firebug shows a blank response (the http status is 200 though). Anybody have a clue??
| [
"I finally figured out what was wrong: my app wasn't following the 'same domain origin' policy. So when the ajax request was being sent, the referrer header was from a different port than my tornado server. Naturally the server didn't return a response!\n"
] | [
4
] | [] | [] | [
"jquery",
"python",
"tornado"
] | stackoverflow_0003367944_jquery_python_tornado.txt |
Q:
how to check the neighbouring states in python
The newPos gives me the position of pacman agent (like (3,5) ).
newPos = successorGameState.getPacmanPosition()
The oldfood gives me the remaining food available for pacman in the form of grid. We can access the grid via list like if we want to know if food is available at (3,4) then we do
oldFood = currentGameState.getFood()
if oldFood[x][y] == true....
newGhostStates = successorGameState.getGhostStates()
This will give me the list for the ghosts that are present.
I need to find the surrounding ghosts i.e the ghosts that are next to newPos. How would I do that ? I am not able to implement it. I got a soln on google but I dont want to use this method. Here , radius is used, i dont know why?
def surroundingGhosts(gList,(x,y), radius=1):
allGhosts = {}
sGhosts = []
for g in gList:
### map ghosts positions to ghost obj
allGhosts[g.getPosition()] = g
checkPos = []
for xx in range(x-radius,x+radius+1):
if xx == x:
for yy in range(y-radius, y+radius+1):
checkPos += [(xx,yy)]
else:
checkPos += [(xx,y)]
for p in checkPos:
if p[0] and p[1] >= 0:
if p in allGhosts:
sGhosts += [allGhosts[p]]
return sGhosts
basically , i need to find the surrrounding positions related to my current postion. Then I will check these postions with the gjost positions, if they match, then there is a ghost.
A:
Well, imagine this:
...
.P.
.G.
P is the pacman an G is a ghost. Checking with "radius = 1" is ghosts adjacent to the pacman. This check will find the ghost. But:
....
.P.G
....
....
But here a ghost won't be found with radius of 1, so radius of 2 is required.
| how to check the neighbouring states in python | The newPos gives me the position of pacman agent (like (3,5) ).
newPos = successorGameState.getPacmanPosition()
The oldfood gives me the remaining food available for pacman in the form of grid. We can access the grid via list like if we want to know if food is available at (3,4) then we do
oldFood = currentGameState.getFood()
if oldFood[x][y] == true....
newGhostStates = successorGameState.getGhostStates()
This will give me the list for the ghosts that are present.
I need to find the surrounding ghosts i.e the ghosts that are next to newPos. How would I do that ? I am not able to implement it. I got a soln on google but I dont want to use this method. Here , radius is used, i dont know why?
def surroundingGhosts(gList,(x,y), radius=1):
allGhosts = {}
sGhosts = []
for g in gList:
### map ghosts positions to ghost obj
allGhosts[g.getPosition()] = g
checkPos = []
for xx in range(x-radius,x+radius+1):
if xx == x:
for yy in range(y-radius, y+radius+1):
checkPos += [(xx,yy)]
else:
checkPos += [(xx,y)]
for p in checkPos:
if p[0] and p[1] >= 0:
if p in allGhosts:
sGhosts += [allGhosts[p]]
return sGhosts
basically , i need to find the surrrounding positions related to my current postion. Then I will check these postions with the gjost positions, if they match, then there is a ghost.
| [
"Well, imagine this:\n...\n.P.\n.G.\n\nP is the pacman an G is a ghost. Checking with \"radius = 1\" is ghosts adjacent to the pacman. This check will find the ghost. But:\n....\n.P.G\n....\n....\n\nBut here a ghost won't be found with radius of 1, so radius of 2 is required.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003377110_python.txt |
Q:
Memoization Handler
Is it "good practice" to create a class like the one below that can handle the memoization process for you? The benefits of memoization are so great (in some cases, like this one, where it drops from 501003 to 1507 function calls and from 1.409 to 0.006 seconds of CPU time on my computer) that it seems a class like this would be useful.
However, I've read only negative comments on the usage of eval(). Is this usage of it excusable, given the flexibility this approach offers?
This can save any returned value automatically at the cost of losing side effects. Thanks.
import cProfile
class Memoizer(object):
"""A handler for saving function results."""
def __init__(self):
self.memos = dict()
def memo(self, string):
if string in self.memos:
return self.memos[string]
else:
self.memos[string] = eval(string)
self.memo(string)
def factorial(n):
assert type(n) == int
if n == 1:
return 1
else:
return n * factorial(n-1)
# find the factorial of num
num = 500
# this many times
times = 1000
def factorialTwice():
factorial(num)
for x in xrange(0, times):
factorial(num)
return factorial(num)
def memoizedFactorial():
handler = Memoizer()
for x in xrange(0, times):
handler.memo("factorial(%d)" % num)
return handler.memo("factorial(%d)" % num)
cProfile.run('factorialTwice()')
cProfile.run('memoizedFactorial()')
A:
You can memoize without having to resort to eval.
A (very basic) memoizer:
def memoized(f):
cache={}
def ret(*args):
if args in cache:
return cache[args]
else:
answer=f(*args)
cache[args]=answer
return answer
return ret
@memoized
def fibonacci(n):
if n==0 or n==1:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)
print fibonacci(100)
A:
eval is often misspelt as evil primarily because the idea of executing "strings" at runtime is fraught with security considerations. Have you escaped the code sufficiently? Quotation marks? And a host of other annoying headaches. Your memoise handler works but it's really not the Python way of doing things. MAK's approach is much more Pythonic. Let's try a few experiments.
I edited up both the versions and made them run just once with 100 as the input. I also moved out the instantiation of Memoizer.
Here are the results.
>>> timeit.timeit(memoizedFactorial,number=1000)
0.08526921272277832h
>>> timeit.timeit(foo0.mfactorial,number=1000)
0.000804901123046875
In addition to this, your version necessitates a wrapper around the the function to be memoised which should be written in a string. That's ugly. MAK's solution is clean since the "process of memoisation" is encapsulated in a separate function which can be conveniently applied to any expensive function in an unobtrusive fashion. This is not very Pythonic. I have some details on writing such decorators in my Python tutorial at http://nibrahim.net.in/self-defence/ in case you're interested.
| Memoization Handler | Is it "good practice" to create a class like the one below that can handle the memoization process for you? The benefits of memoization are so great (in some cases, like this one, where it drops from 501003 to 1507 function calls and from 1.409 to 0.006 seconds of CPU time on my computer) that it seems a class like this would be useful.
However, I've read only negative comments on the usage of eval(). Is this usage of it excusable, given the flexibility this approach offers?
This can save any returned value automatically at the cost of losing side effects. Thanks.
import cProfile
class Memoizer(object):
"""A handler for saving function results."""
def __init__(self):
self.memos = dict()
def memo(self, string):
if string in self.memos:
return self.memos[string]
else:
self.memos[string] = eval(string)
self.memo(string)
def factorial(n):
assert type(n) == int
if n == 1:
return 1
else:
return n * factorial(n-1)
# find the factorial of num
num = 500
# this many times
times = 1000
def factorialTwice():
factorial(num)
for x in xrange(0, times):
factorial(num)
return factorial(num)
def memoizedFactorial():
handler = Memoizer()
for x in xrange(0, times):
handler.memo("factorial(%d)" % num)
return handler.memo("factorial(%d)" % num)
cProfile.run('factorialTwice()')
cProfile.run('memoizedFactorial()')
| [
"You can memoize without having to resort to eval.\nA (very basic) memoizer:\ndef memoized(f):\n cache={}\n def ret(*args):\n if args in cache:\n return cache[args]\n else:\n answer=f(*args)\n cache[args]=answer\n return answer\n return ret\n\n@memo... | [
14,
5
] | [] | [] | [
"dynamic_programming",
"memoization",
"python"
] | stackoverflow_0003377258_dynamic_programming_memoization_python.txt |
Q:
Mac ports Mysql install
I completed my install on Leopard with Mac Ports. I also installed Mysqld via Mac Ports for use with python. I set the password for mysql on mysql start. Everything seemed to be fine except when I invoke mysql-start from the command line now I get this: mysql-start
*****Password:
Starting MySQL
. SUCCESS!
demetrius-fords-macbook-pro-17:~ demet8$
I also get a system que stating:Do you want mysqld to accepting incoming notifications.....
So I kinda think I am activating mysqld, not the actual mysql command interpreter. I can use mysql-stop with no problem to shut the server down. Lastly in the Python interpreter when I run: import MySQLdb I get this:
/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQLdb/__init__.py:34: DeprecationWarning: the sets module is deprecated
from sets import ImmutableSet
I don't think this affects mysqld @ all. I don't have the mysql default socket in my path via bash_login. Do I need to do that? thank you....
A:
The command for the client is normally mysql (see MySql docs) However in macports they have appended the major version number so try mysql5
The python error is only a depreciation so can be ignored
| Mac ports Mysql install | I completed my install on Leopard with Mac Ports. I also installed Mysqld via Mac Ports for use with python. I set the password for mysql on mysql start. Everything seemed to be fine except when I invoke mysql-start from the command line now I get this: mysql-start
*****Password:
Starting MySQL
. SUCCESS!
demetrius-fords-macbook-pro-17:~ demet8$
I also get a system que stating:Do you want mysqld to accepting incoming notifications.....
So I kinda think I am activating mysqld, not the actual mysql command interpreter. I can use mysql-stop with no problem to shut the server down. Lastly in the Python interpreter when I run: import MySQLdb I get this:
/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQLdb/__init__.py:34: DeprecationWarning: the sets module is deprecated
from sets import ImmutableSet
I don't think this affects mysqld @ all. I don't have the mysql default socket in my path via bash_login. Do I need to do that? thank you....
| [
"The command for the client is normally mysql (see MySql docs) However in macports they have appended the major version number so try mysql5 \nThe python error is only a depreciation so can be ignored \n"
] | [
0
] | [] | [] | [
"django",
"macports",
"mysql",
"python"
] | stackoverflow_0003376565_django_macports_mysql_python.txt |
Q:
Relating generically created Django objects with users
I'm new to Python & Django. I want to allow users to create new objects, and for each object to be related to the currently logged in user. So, I thought I'd use the generic create_object method - only I can't work out how best to do this so it's simple and secure.
Here's my model:
class Book(models.Model):
user = models.ForeignKey(User, related_name='owner',
editable=False)
title = models.CharField(max_length=200,
help_text='A title for this entry')
author = models.CharField(max_length=200)
This is a really simple model - users can enter a book title and author, and the 'user' field is set as non-editable. When the object is created I want the user field to have the value of the currently logged in user.
Can I do this with the generic create_object method? What's the best approach here? I don't want to use a hidden field in the form since it's obviously not safe.
Thanks
A:
I think it's not possible with generic view (I could think of some way to accomplish that, but that would be much more complicated than it's worth - using signals, globals and middleware). You should write your own view that will handle Book object creation using ModelForm. Read about it here and here (Django docs).
Also, I think you misunderstood what related_name parameter does - now, given some User instance you'll have to write:
books = user.owner.all()
to get list of this user's books. It would be better to either leave related_name unchanged (the default is relatedmodelname_set, in this case: user.book_set.all()) or change it to something more meaningful, like "books", which will let you write:
books = user.books.all()
and get what you want.
| Relating generically created Django objects with users | I'm new to Python & Django. I want to allow users to create new objects, and for each object to be related to the currently logged in user. So, I thought I'd use the generic create_object method - only I can't work out how best to do this so it's simple and secure.
Here's my model:
class Book(models.Model):
user = models.ForeignKey(User, related_name='owner',
editable=False)
title = models.CharField(max_length=200,
help_text='A title for this entry')
author = models.CharField(max_length=200)
This is a really simple model - users can enter a book title and author, and the 'user' field is set as non-editable. When the object is created I want the user field to have the value of the currently logged in user.
Can I do this with the generic create_object method? What's the best approach here? I don't want to use a hidden field in the form since it's obviously not safe.
Thanks
| [
"I think it's not possible with generic view (I could think of some way to accomplish that, but that would be much more complicated than it's worth - using signals, globals and middleware). You should write your own view that will handle Book object creation using ModelForm. Read about it here and here (Django docs... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003377421_django_python.txt |
Q:
Using a tuple as function arguments
For this function I can use tuple elements as arguments:
light_blue = .6, .8, .9
gradient.add_color_rgb(0, *light_blue)
What if i have to add another argument after the tuple?
light_blue = .6, .8, .9
alpha = .5
gradient.add_color_rgba(0, *light_blue, alpha)
does not work. What does work is
gradient.add_color_rgba(0, *list(light_blue)+[alpha])
which does not really look better than
gradient.add_color_rgba(0, light_blue[0], light_blue[1], light_blue[2], alpha)
Is there a better way to do this?
A:
You could call it like gradient.add_color_rgba(0, *light_blue, alpha=alpha) if you know parameter name for the alpha.
A:
You can simplify the expression slightly by making a tuple instead of a list containing light_blue and alpha e.g.
gradient.add_color_rgba(0, *(light_blue + (alpha,)))
| Using a tuple as function arguments | For this function I can use tuple elements as arguments:
light_blue = .6, .8, .9
gradient.add_color_rgb(0, *light_blue)
What if i have to add another argument after the tuple?
light_blue = .6, .8, .9
alpha = .5
gradient.add_color_rgba(0, *light_blue, alpha)
does not work. What does work is
gradient.add_color_rgba(0, *list(light_blue)+[alpha])
which does not really look better than
gradient.add_color_rgba(0, light_blue[0], light_blue[1], light_blue[2], alpha)
Is there a better way to do this?
| [
"You could call it like gradient.add_color_rgba(0, *light_blue, alpha=alpha) if you know parameter name for the alpha.\n",
"You can simplify the expression slightly by making a tuple instead of a list containing light_blue and alpha e.g.\ngradient.add_color_rgba(0, *(light_blue + (alpha,)))\n\n"
] | [
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0003377681_python.txt |
Q:
How do I efficiently fill a file with null data from python?
I need to create files of arbitrary size that contain no data. The are potentially quite large. While I could just loop through and write a single null character until I've reached the file size, that seems ugly.
with open(filename,'wb') as f:
# what goes here?
What is the efficient, pythonic way to do this?
A:
You can seek to a specific position and write a byte, and the OS will magically make the rest of the file appear.
with open(filename, "wb") as f:
f.seek(999999)
f.write("\0")
You need to write at least one byte for this to work.
A:
with open('zero', 'w') as f:
f.seek(999999999)
f.write('\0')
Will create a sparse file if the OS supports it. The magic is that files created this way do not take any space (until you copy it elsewhere with a program that does not preserve holes)
| How do I efficiently fill a file with null data from python? | I need to create files of arbitrary size that contain no data. The are potentially quite large. While I could just loop through and write a single null character until I've reached the file size, that seems ugly.
with open(filename,'wb') as f:
# what goes here?
What is the efficient, pythonic way to do this?
| [
"You can seek to a specific position and write a byte, and the OS will magically make the rest of the file appear.\nwith open(filename, \"wb\") as f:\n f.seek(999999)\n f.write(\"\\0\")\n\nYou need to write at least one byte for this to work.\n",
"with open('zero', 'w') as f:\n f.seek(999999999)\n f.w... | [
18,
8
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003377891_file_python.txt |
Q:
find the neighbouring states around the agent
I need to find the states that are next to my pacman agent. The current state is Tuple(3,5) which is given by numPos.
I need to check the position that are around the pacman agent. I want to find the neighbouring states so that i can check it with the ghosts states and if they matches, that means , a ghost is present in the neighbouring side. But I am not able to find the neighbouring states. Like , I need to check (x, y+1), (x,y-1) , (y,x+1), (y, x-1). How do i implement it.I cannot use the range function here.
A:
What is the problem? Your question (and the previous) one are quite unclear.
What's wrong with this.
x,y = numPos
positions_to_search = [ (x-1, y),
(x-1, y-1),
(x, y-1),
(x+1, y-1),
(x+1, y),
(x+1, y+1),
(x, y+1),
(x-1, y+1)]
What have you tried?
A:
for dx,dy in ((1,0),(0,1),(-1,0),(0,-1)):
search_position(x+dx, y+dy)
A:
If you want to get fancy you can make neighbour tuples ready for whole grid so that the movement out of grid and to the walls is impossible also runtime action is fast as it need only lookup from ready neighbour dictionary:
neighbourghosts = [(nx,ny)
for nx,ny in neighbours_of[numPos]
if (nx,ny) in ghostplaces]
| find the neighbouring states around the agent | I need to find the states that are next to my pacman agent. The current state is Tuple(3,5) which is given by numPos.
I need to check the position that are around the pacman agent. I want to find the neighbouring states so that i can check it with the ghosts states and if they matches, that means , a ghost is present in the neighbouring side. But I am not able to find the neighbouring states. Like , I need to check (x, y+1), (x,y-1) , (y,x+1), (y, x-1). How do i implement it.I cannot use the range function here.
| [
"What is the problem? Your question (and the previous) one are quite unclear. \nWhat's wrong with this. \nx,y = numPos\npositions_to_search = [ (x-1, y),\n (x-1, y-1),\n (x, y-1),\n (x+1, y-1),\n (x+1, y),\n ... | [
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003377303_python.txt |
Q:
passing C++ classes instances to python with boost::python
I have a library which creates objects (instances of class A) and pass them to a python program which should be able to call their methods.
Basically I have C++ class instances and I want to use them from python. Occasionally that object should be passed back to C++ for some manipulations.
I created the following wrapper file (let's assume that the New function is called somewhere in the C++ code):
#include <boost/python.hpp>
#include <iostream>
#include <boost/smart_ptr.hpp>
using namespace boost;
using namespace boost::python;
int calls = 0;
struct A
{
int f() { return calls++; }
~A() { std::cout << "destroyed\n"; }
};
shared_ptr<A> existing_instance;
void New() { existing_instance = shared_ptr<A>( new A() ); }
int Count( shared_ptr<A> a ) { return a.use_count(); }
BOOST_PYTHON_MODULE(libp)
{
class_<A>("A")
.def("f", &A::f)
;
def("Count", &Count);
register_ptr_to_python< shared_ptr<A> >();
}
The code lacks the part where the python gets the existing_instance. I didn't paste that, but let's just say I use a callback mechanism for that purpose.
This code works but I have a few questions:
In the Count function (and in all other C++ manipulation functions) is it fine to pass a like that or it's better to do something like const shared_ptr<A>&? In the code snippets I found in the python boost documentation the reference is often used but I don't understand the difference (apart from having a higher reference counter, of course).
Is this code "safe"? When I pass the existing_instance to python, its counter will be incremented (just once, even if in python I make more copies of the object, of course) so there is no way that the C++ code could destroy the object as far as python holds at least a "copy". Am I correct? I tried to play with pointers and it seems I'm correct, I'm asking just to be sure.
I'd like to prevent python from creating instances of A. They should only be passed from C++ code. How could I achieve that? EDIT: found, I just need to use no_init and noncopyable: class_<A, boost::noncopyable>("A", no_init)
A:
boost::python knows all about boost::shared_ptr, but you need to tell it that boost::shared_ptr<A> holds an instance of A, you do this by adding boost::shared_ptr<A> in the template argument list to class_, more information on this 'Held Type' is here in the boost documentation.
To prevent instances being created from python, you add boost::python::no_init to the class_ constructor, so you end up with:
boost::python::class_< A, boost::shared_ptr<A> >("A", boost::python::no_init)
//... .def, etc
;
In general you should not pass around shared pointers by reference, since if the reference to the shared pointer is invalidated, then the reference to which the shared pointer is pointing to is also invalidated (since taking a reference of the shared pointer didn't increment the reference counter to the pointed to object).
It is perfectly safe to pass boost::shared_ptr objects around to and from python, reference counts (python and shared_ptr) will be correctly managed provided you don't change the return_value_policy. If you change the policy of a method exposed in python so that it returns a reference to a shared pointer then you can cause problems, just as passing shared pointers around by c++ references can cause problems.
(Also, you should use make_shared<A>(...) in preference to shared_ptr<A>(new A(...)).)
A:
In this situation my code would look like this (for your example):
...
BOOST_PYTHON_MODULE(libp)
{
class_<A, boost::shared_ptr<A>, boost::noncopyable >("A")
.def("f", &A::f)
.def("Count", &Count)
;
}
It is important to forbid boost::python to copy things, but if your are using
shared_ptr chances are that you only need copying in a few controlled situations.
| passing C++ classes instances to python with boost::python | I have a library which creates objects (instances of class A) and pass them to a python program which should be able to call their methods.
Basically I have C++ class instances and I want to use them from python. Occasionally that object should be passed back to C++ for some manipulations.
I created the following wrapper file (let's assume that the New function is called somewhere in the C++ code):
#include <boost/python.hpp>
#include <iostream>
#include <boost/smart_ptr.hpp>
using namespace boost;
using namespace boost::python;
int calls = 0;
struct A
{
int f() { return calls++; }
~A() { std::cout << "destroyed\n"; }
};
shared_ptr<A> existing_instance;
void New() { existing_instance = shared_ptr<A>( new A() ); }
int Count( shared_ptr<A> a ) { return a.use_count(); }
BOOST_PYTHON_MODULE(libp)
{
class_<A>("A")
.def("f", &A::f)
;
def("Count", &Count);
register_ptr_to_python< shared_ptr<A> >();
}
The code lacks the part where the python gets the existing_instance. I didn't paste that, but let's just say I use a callback mechanism for that purpose.
This code works but I have a few questions:
In the Count function (and in all other C++ manipulation functions) is it fine to pass a like that or it's better to do something like const shared_ptr<A>&? In the code snippets I found in the python boost documentation the reference is often used but I don't understand the difference (apart from having a higher reference counter, of course).
Is this code "safe"? When I pass the existing_instance to python, its counter will be incremented (just once, even if in python I make more copies of the object, of course) so there is no way that the C++ code could destroy the object as far as python holds at least a "copy". Am I correct? I tried to play with pointers and it seems I'm correct, I'm asking just to be sure.
I'd like to prevent python from creating instances of A. They should only be passed from C++ code. How could I achieve that? EDIT: found, I just need to use no_init and noncopyable: class_<A, boost::noncopyable>("A", no_init)
| [
"boost::python knows all about boost::shared_ptr, but you need to tell it that boost::shared_ptr<A> holds an instance of A, you do this by adding boost::shared_ptr<A> in the template argument list to class_, more information on this 'Held Type' is here in the boost documentation.\nTo prevent instances being created... | [
14,
1
] | [] | [] | [
"boost",
"boost_python",
"c++",
"python"
] | stackoverflow_0003342216_boost_boost_python_c++_python.txt |
Q:
Using boost.python to import a method with opencv calls but failing due to symbols not being found after compilation
So I don't have the code right now, as I am not home... but i used the boost library for python in C++ to allow python to access a function called something like loadImageIntoMainWindow(string filepath)
in the C++ source code the method calls opencv methods that are imported at the top of the file, I included opencv in my Jamroot file, and also found a way to compile and link manually on the command line... in either case when I run my python file it complains that the symbols aren't found for the first function call to an opencv method...
I will update as soon as I get home with the C++, the command line compilation lines, the Jamroot, and the python files
here is the Jamroot:
# Copyright David Abrahams 2006. Distributed under the Boost
# Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
using python ;
lib libboost_python : : <name>boost_python-mt-py26 ;
# Specify the path to the Boost project. If you move this project,
# adjust this path to refer to the Boost root directory.
use-project boost
: ./ ;
# Set up the project-wide requirements that everything uses the
# boost_python library from the project whose global ID is
# /boost/python.
project
: requirements
<search>/usr
<library>libboost_python
<include>/usr/include/opencv ;
# Declare the three extension modules. You can specify multiple
# source files after the colon separated by spaces.
python-extension uTrackSpheresForPyInterface : uTrackSpheresForPyInterface.cpp ;
# A little "rule" (function) to clean up the syntax of declaring tests
# of these extension modules.
local rule run-test ( test-name : sources + )
{
import testing ;
testing.make-test run-pyd : $(sources) : : $(test-name) ;
}
# Declare test targets
after I run bjam --preserve-test-targets
or
g++ -c -g -Wall -fPIC -pipe -DBOOST_PYTHON_MAX_ARITY=20 -I. -I/usr/include/opencv/ - /usr/include/python2.6 `pkg-config --libs opencv` uTrackSpheresForPyInterface.cpp
g++ -shared -o uTrackSpheresForPyInterface.so uTrackSpheresForPyInterface.o -L/usr/lib - python2.6 -lboost_python-mt-py26
I get this:
nathan@innovation:~/Research RIT/openCv$ python uTrackSpheres.py
Traceback (most recent call last):
File "uTrackSpheres.py", line 18, in <module>
import uTrackSpheresForPyInterface
ImportError: /home/nathan/Research RIT/openCv/uTrackSpheresForPyInterface.so: undefined symbol: cvCvtColor
nathan@innovation:~/Research RIT/openCv$
and in the cpp file I'm doing a litte more than this:
#include <iostream>
using namespace std;
#ifdef _CH_
#pragma package <opencv>
#endif
#ifndef _EiC
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#endif
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
int loadImageIntoMainWindow(string imgPath) {
if( (imgLoaded = cvLoadImage(imgPath.c_str(),1)) == 0 )
return 0;
imgMain = cvCreateImage( cvSize(imgLoaded->width, imgLoaded->height), 8, 1 );
cvCvtColor( imgLoaded, imgMain, CV_BGR2GRAY );
cvNamedWindow( charCurrentFilename,CV_WINDOW_AUTOSIZE);
cvSetMouseCallback(charCurrentFilename, on_mouse_imgMain, 0 );
cvShowImage(charCurrentFilename, imgMain);
return 1;
}
BOOST_PYTHON_MODULE(uTrackSpheresForPyInterface)
{
using namespace boost::python;
def("loadImageIntoMainWindow", loadImageIntoMainWindow);
}
A:
Add the lines (editing /your/lib/path as appropriate...):
lib cvlib : : <name>cv <search>/your/lib/path/lib ;
lib cxcorelib : : <name>cxcore <search>/your/lib/path/lib ;
to your Jamfile, and edit
python-extension uTrackSpheresForPyInterface : uTrackSpheresForPyInterface.cpp ;
so that it reads:
python-extension uTrackSpheresForPyInterface :
uTrackSpheresForPyInterface.cpp
cvlib
cxcorelib ;
| Using boost.python to import a method with opencv calls but failing due to symbols not being found after compilation | So I don't have the code right now, as I am not home... but i used the boost library for python in C++ to allow python to access a function called something like loadImageIntoMainWindow(string filepath)
in the C++ source code the method calls opencv methods that are imported at the top of the file, I included opencv in my Jamroot file, and also found a way to compile and link manually on the command line... in either case when I run my python file it complains that the symbols aren't found for the first function call to an opencv method...
I will update as soon as I get home with the C++, the command line compilation lines, the Jamroot, and the python files
here is the Jamroot:
# Copyright David Abrahams 2006. Distributed under the Boost
# Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
using python ;
lib libboost_python : : <name>boost_python-mt-py26 ;
# Specify the path to the Boost project. If you move this project,
# adjust this path to refer to the Boost root directory.
use-project boost
: ./ ;
# Set up the project-wide requirements that everything uses the
# boost_python library from the project whose global ID is
# /boost/python.
project
: requirements
<search>/usr
<library>libboost_python
<include>/usr/include/opencv ;
# Declare the three extension modules. You can specify multiple
# source files after the colon separated by spaces.
python-extension uTrackSpheresForPyInterface : uTrackSpheresForPyInterface.cpp ;
# A little "rule" (function) to clean up the syntax of declaring tests
# of these extension modules.
local rule run-test ( test-name : sources + )
{
import testing ;
testing.make-test run-pyd : $(sources) : : $(test-name) ;
}
# Declare test targets
after I run bjam --preserve-test-targets
or
g++ -c -g -Wall -fPIC -pipe -DBOOST_PYTHON_MAX_ARITY=20 -I. -I/usr/include/opencv/ - /usr/include/python2.6 `pkg-config --libs opencv` uTrackSpheresForPyInterface.cpp
g++ -shared -o uTrackSpheresForPyInterface.so uTrackSpheresForPyInterface.o -L/usr/lib - python2.6 -lboost_python-mt-py26
I get this:
nathan@innovation:~/Research RIT/openCv$ python uTrackSpheres.py
Traceback (most recent call last):
File "uTrackSpheres.py", line 18, in <module>
import uTrackSpheresForPyInterface
ImportError: /home/nathan/Research RIT/openCv/uTrackSpheresForPyInterface.so: undefined symbol: cvCvtColor
nathan@innovation:~/Research RIT/openCv$
and in the cpp file I'm doing a litte more than this:
#include <iostream>
using namespace std;
#ifdef _CH_
#pragma package <opencv>
#endif
#ifndef _EiC
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#endif
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
int loadImageIntoMainWindow(string imgPath) {
if( (imgLoaded = cvLoadImage(imgPath.c_str(),1)) == 0 )
return 0;
imgMain = cvCreateImage( cvSize(imgLoaded->width, imgLoaded->height), 8, 1 );
cvCvtColor( imgLoaded, imgMain, CV_BGR2GRAY );
cvNamedWindow( charCurrentFilename,CV_WINDOW_AUTOSIZE);
cvSetMouseCallback(charCurrentFilename, on_mouse_imgMain, 0 );
cvShowImage(charCurrentFilename, imgMain);
return 1;
}
BOOST_PYTHON_MODULE(uTrackSpheresForPyInterface)
{
using namespace boost::python;
def("loadImageIntoMainWindow", loadImageIntoMainWindow);
}
| [
"Add the lines (editing /your/lib/path as appropriate...):\nlib cvlib : : <name>cv <search>/your/lib/path/lib ;\nlib cxcorelib : : <name>cxcore <search>/your/lib/path/lib ;\n\nto your Jamfile, and edit\npython-extension uTrackSpheresForPyInterface : uTrackSpheresForPyInterface.cpp ;\n\nso that it reads:\npython-ext... | [
0
] | [] | [] | [
"boost_python",
"c++",
"missing_symbols",
"opencv",
"python"
] | stackoverflow_0002502921_boost_python_c++_missing_symbols_opencv_python.txt |
Q:
Problem extracting text out of html file using python regex
I'm working on a project that requires me to write some code to pull out some text from a html file in python.
<tr>
<td>Target binary file name:</td>
<td class="right">Doc1.docx</td>
</tr>
^Small portion of the html file that I'm interested in.
#! /usr/bin/python
import os
import re
if __name__ == '__main__':
f = open('./results/sample_result.html')
soup = f.read()
p = re.compile("binary")
for line in soup:
m = p.search(line)
if m:
print "finally"
break
^Sample code I wrote to test if I could extract data out.
I've written several programs similar to this to extract text from txt files almost exactly the same and they have worked just fine. Is there something I'm missing out with regards to regex and html?
A:
Is there something I'm missing out with regards to regex and html?
Yes. You're missing the fact that some HTML cannot be parsed with a simple regex.
A:
HTML as understood by browsers is waaaay too flexible for reg expressions. Attributes can pop up in any tag, and in any order, and in upper or lower case, and with or without quotation marks about the value. Special emphasis tags can show up anywhere. Whitespace is significant in regex, but not so much in HTML, so your regex has to be littered with \s*'s everywhere. There is no requirement that opening tags be matched with closing tags. Some opening tags include a trailing '/', meaning that they are empty tags (no body, no closing tag). Lastly, HTML is often nested, which is pretty much off the chart as far as regex is concerned.
A:
Is this actually what you're trying to do, or just a simple example for a more complicated regex later? If the latter, listen to everyone else. If the former:
for line in file:
if "binary" in line:
# do stuff
If that doesn't work, are you sure "binary" is in the file? Not, I don't know, "<i>b</i>inary"?
| Problem extracting text out of html file using python regex | I'm working on a project that requires me to write some code to pull out some text from a html file in python.
<tr>
<td>Target binary file name:</td>
<td class="right">Doc1.docx</td>
</tr>
^Small portion of the html file that I'm interested in.
#! /usr/bin/python
import os
import re
if __name__ == '__main__':
f = open('./results/sample_result.html')
soup = f.read()
p = re.compile("binary")
for line in soup:
m = p.search(line)
if m:
print "finally"
break
^Sample code I wrote to test if I could extract data out.
I've written several programs similar to this to extract text from txt files almost exactly the same and they have worked just fine. Is there something I'm missing out with regards to regex and html?
| [
"\nIs there something I'm missing out with regards to regex and html?\n\nYes. You're missing the fact that some HTML cannot be parsed with a simple regex.\n",
"HTML as understood by browsers is waaaay too flexible for reg expressions. Attributes can pop up in any tag, and in any order, and in upper or lower cas... | [
4,
0,
0
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0003378194_html_python_regex.txt |
Q:
name and value lookup collection, loaded from a dropdown list using beautifulsoup
On my html page I have a dropdown list:
<select name="somelist">
<option value="234234234239393">Some Text</option>
</select>
So do get this list I am doing:
ddl = soup.findAll('select', name="somelist")
if(ddl):
???
Now I need help with this collection/dictionary, I want to be able to lookup by both 'Some Text' and 234234234239393.
Is this possible?
A:
Try the following to get started:
str = r'''
<select name="somelist">
<option value="234234234239393">Some Text</option>
<option value="42">Other text</option>
</select>
'''
soup = BeautifulSoup(str)
select_node = soup.findAll('select', attrs={'name': 'somelist'})
if select_node:
for option in select_node[0].findAll('option'):
print option
It prints out the option nodes:
<option value="234234234239393">Some Text</option>
<option value="42">Other text</option>
Now, for each option, option['value'] is the value attribute, and option.text is the text inside the tag ("Some Text")
A:
Here's one way ..
ddl_list = soup.findAll('select', attrs={'name': 'somelist'})
if ddl_list:
ddl = ddl_list[0]
# find the optino by value=234234234239393
opt = ddl.findChild('option', attrs={'value': '234234234239393'})
if opt:
# do something
# this list will hold all "option" elements matching 'Some Text'
opt_list = [opt for opt in ddl.findChildren('option') if opt.string == u'Some Text']
if opt_list:
opt2 = opt_list[0]
# do something
A:
And again, just to show how one could do this with pyparsing:
html = r'''
<select name="somelist">
<option value="234234234239393">Some Text</option>
<option value="42">Other text</option>
</select>
'''
from pyparsing import makeHTMLTags, Group, SkipTo, withAttribute, OneOrMore
select,selectEnd = makeHTMLTags("SELECT")
option,optionEnd = makeHTMLTags("OPTION")
optionEntry = Group(option("option") +
SkipTo(optionEnd)("menutext") +
optionEnd)
somelistSelect = (select.setParseAction(withAttribute(name="somelist")) +
OneOrMore(optionEntry)("options") +
selectEnd)
t,_,_ = somelistSelect.scanString(html).next()
for op in t.options:
print op.menutext, '->', op.option.value
prints:
Some Text -> 234234234239393
Other text -> 42
| name and value lookup collection, loaded from a dropdown list using beautifulsoup | On my html page I have a dropdown list:
<select name="somelist">
<option value="234234234239393">Some Text</option>
</select>
So do get this list I am doing:
ddl = soup.findAll('select', name="somelist")
if(ddl):
???
Now I need help with this collection/dictionary, I want to be able to lookup by both 'Some Text' and 234234234239393.
Is this possible?
| [
"Try the following to get started:\nstr = r'''\n<select name=\"somelist\">\n <option value=\"234234234239393\">Some Text</option>\n <option value=\"42\">Other text</option>\n</select>\n'''\n\nsoup = BeautifulSoup(str)\nselect_node = soup.findAll('select', attrs={'name': 'somelist'})\n\nif select_node:\n for ... | [
5,
1,
0
] | [] | [] | [
"beautifulsoup",
"dictionary",
"python"
] | stackoverflow_0003376817_beautifulsoup_dictionary_python.txt |
Q:
Python: what does "...".encode("utf8") fix?
I wanted to url encode a python string and got exceptions with hebrew strings.
I couldn't fix it and started doing some guess oriented programming.
Finally, doing mystr = mystr.encode("utf8") before sending it to the url encoder saved the day.
Can somebody explain what happened? What does .encode("utf8") do? My original string was a unicode string anyways (i.e. prefixed by a u).
A:
My original string was a unicode string anyways (i.e. prefixed by a u)
...which is the problem. It wasn't a "string", as such, but a "Unicode object". It contains a sequence of Unicode code points. These code points must, of course, have some internal representation that Python knows about, but whatever that is is abstracted away and they're shown as those \uXXXX entities when you print repr(my_u_str).
To get a sequence of bytes that another program can understand, you need to take that sequence of Unicode code points and encode it. You need to decide on the encoding, because there are plenty to choose from. UTF8 and UTF16 are common choices. ASCII could be too, if it fits. u"abc".encode('ascii') works just fine.
Do my_u_str = u"\u2119ython" and then type(my_u_str) and type(my_u_str.encode('utf8')) to see the difference in types: The first is <type 'unicode'> and the second is <type 'str'>. (Under Python 2.5 and 2.6, anyway).
Things are different in Python 3, but since I rarely use it I'd be talking out of my hat if I tried to say anything authoritative about it.
A:
You original string was a unicode object containing raw Unicode code points, after encoding it as UTF-8 it is a normal byte string that contains UTF-8 encoded data.
The URL encoder seems to expect a byte string, so that it can URL-encode one byte after another and doesn't have to deal with Unicode code points. When you give it a unicode object, it tries to convert it to a byte string using some default encoding, probably ASCII. For Hebrew characters that cannot be represented as ASCII, this will lead to errors.
A:
What does .encode("utf8") do?
It depends on which version of Python you're using:
In Python 3.x, it converts a str object (encoded in UTF-16 or UTF-32) into a bytes object containing the UTF-8 representation of the string.
In Python 2.x, it converts a unicode object into a str object encoded in UTF-8. But str has an encode method too, and writing '...'.encode('UTF-8') is equivalent to writing '...'.decode('ascii').encode('UTF-8').
Since you mentioned the "u" prefix, you must be using 2.x. If you don't require any 2.x-only libraries, I'd recommend switching to 3.x, which has a nice clear distinction between text and binary data.
Dive into Python 3 has a good explanation of the issue.
Can somebody explain what happened?
It would help if you told us what the error message was.
The urllib.quote function expects a str object. It also happens to work with unicode objects that contain only ASCII characters, but not when they contain Hebrew letters.
In Python 3.x, urllib.parse.quote accepts both str (=Python 2.x unicode) and bytes objects. Strings are automatically encoded in UTF-8.
A:
"...".encode("utf-8") transforms the in-memory representation of the string into an UTF-8 -encoded string.
url encoder likely expected a bytestring, that is, string representation where each character is represented with a single byte.
A:
It returns a UTF-8 encoded version of the Unicode string, mystr. It is important to realize that UTF-8 is simply 1 way of encoding Unicode. Python can work with many other encodings (eg. mystr.encode("utf32") or even mystr.encode("ascii")).
A:
The link that balpha posted explains it all. In short:
The fact that your string was prefixed with "u" just means it's composed of Unicode characters (or code points). UTF-8 is an encoding of this string into a sequence of bytes.
| Python: what does "...".encode("utf8") fix? | I wanted to url encode a python string and got exceptions with hebrew strings.
I couldn't fix it and started doing some guess oriented programming.
Finally, doing mystr = mystr.encode("utf8") before sending it to the url encoder saved the day.
Can somebody explain what happened? What does .encode("utf8") do? My original string was a unicode string anyways (i.e. prefixed by a u).
| [
"\nMy original string was a unicode string anyways (i.e. prefixed by a u)\n\n...which is the problem. It wasn't a \"string\", as such, but a \"Unicode object\". It contains a sequence of Unicode code points. These code points must, of course, have some internal representation that Python knows about, but whatever t... | [
13,
9,
4,
1,
0,
0
] | [] | [] | [
"internationalization",
"python",
"unicode",
"urlencode",
"utf_8"
] | stackoverflow_0003291123_internationalization_python_unicode_urlencode_utf_8.txt |
Q:
How would you group up articles by context? - Natural Language
I have lists of articles made of:
title, subtitle and body.
Now I need to parse all these articles and group them up under different context categories or sub categories based on their possible keywords.
e.g. if the article is likely to be related to sports cars then the article would be associated with the car or/and vehicle context
Now I understand that this is a vast ocean, but this is also why I have put up this question. Because the ocean of solutions might be too big for me, and I would most likely get lost and adopt some bad thought solution.
There are probably some popular and standardized ways of doing this that I do not know, and it would be very useful if someone pointed me in the right direction.
Help would be great. =)
A:
The Natural Lanugage Toolkit but don't expect that there is a magic bullet in there which will keep you having to learn a fair bit about linguistics, as the problem you describe cannot be solved wholly mechanically.
| How would you group up articles by context? - Natural Language | I have lists of articles made of:
title, subtitle and body.
Now I need to parse all these articles and group them up under different context categories or sub categories based on their possible keywords.
e.g. if the article is likely to be related to sports cars then the article would be associated with the car or/and vehicle context
Now I understand that this is a vast ocean, but this is also why I have put up this question. Because the ocean of solutions might be too big for me, and I would most likely get lost and adopt some bad thought solution.
There are probably some popular and standardized ways of doing this that I do not know, and it would be very useful if someone pointed me in the right direction.
Help would be great. =)
| [
"The Natural Lanugage Toolkit but don't expect that there is a magic bullet in there which will keep you having to learn a fair bit about linguistics, as the problem you describe cannot be solved wholly mechanically.\n"
] | [
1
] | [] | [] | [
"data_mining",
"nlp",
"python"
] | stackoverflow_0003378908_data_mining_nlp_python.txt |
Q:
How to capture Python interpreter's and/or CMD.EXE's output from a Python script?
Is it possible to capture Python interpreter's output from a Python script?
Is it possible to capture Windows CMD's output from a Python script?
If so, which librar(y|ies) should I look into?
A:
If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:
python script_a.py | python script_b.py
This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on standard streams on Wikipedia.
If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):
import subprocess
# Of course you can open things other than python here :)
process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
x = process.stderr.readline()
y = process.stdout.readline()
process.wait()
See the Python subprocess module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard file objects.
For use with pipes, reading from standard input as lassevk suggested you'd do something like this:
import sys
x = sys.stderr.readline()
y = sys.stdin.readline()
sys.stdin and sys.stdout are standard file objects as noted above, defined in the sys module. You might also want to take a look at the pipes module.
Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into polling which unfortunately does not work in windows, but I'm sure there's some alternative out there.
A:
I think I can point you to a good answer for the first part of your question.
1. Is it possible to capture Python interpreter's output from a Python
script?
The answer is "yes", and personally I like the following lifted from the examples in the PEP 343 -- The "with" Statement document.
from contextlib import contextmanager
import sys
@contextmanager
def stdout_redirected(new_stdout):
saved_stdout = sys.stdout
sys.stdout = new_stdout
try:
yield None
finally:
sys.stdout.close()
sys.stdout = saved_stdout
And used like this:
with stdout_redirected(open("filename.txt", "w")):
print "Hello world"
A nice aspect of it is that it can be applied selectively around just a portion of a script's execution, rather than its entire extent, and stays in effect even when unhandled exceptions are raised within its context. If you re-open the file in append-mode after its first use, you can accumulate the results into a single file:
with stdout_redirected(open("filename.txt", "w")):
print "Hello world"
print "screen only output again"
with stdout_redirected(open("filename.txt", "a")):
print "Hello world2"
Of course, the above could also be extended to also redirect sys.stderr to the same or another file. Also see this answer to a related question.
A:
Actually, you definitely can, and it's beautiful, ugly, and crazy at the same time!
You can replace sys.stdout and sys.stderr with StringIO objects that collect the output.
Here's an example, save it as evil.py:
import sys
import StringIO
s = StringIO.StringIO()
sys.stdout = s
print "hey, this isn't going to stdout at all!"
print "where is it ?"
sys.stderr.write('It actually went to a StringIO object, I will show you now:\n')
sys.stderr.write(s.getvalue())
When you run this program, you will see that:
nothing went to stdout (where print usually prints to)
the first string that gets written to stderr is the one starting with 'It'
the next two lines are the ones that were collected in the StringIO object
Replacing sys.stdout/err like this is an application of what's called monkeypatching. Opinions may vary whether or not this is 'supported', and it is definitely an ugly hack, but it has saved my bacon when trying to wrap around external stuff once or twice.
Tested on Linux, not on Windows, but it should work just as well. Let me know if it works on Windows!
A:
You want subprocess. Look specifically at Popen in 17.1.1 and communicate in 17.1.2.
A:
In which context are you asking?
Are you trying to capture the output from a program you start on the command line?
if so, then this is how to execute it:
somescript.py | your-capture-program-here
and to read the output, just read from standard input.
If, on the other hand, you're executing that script or cmd.exe or similar from within your program, and want to wait until the script/program has finished, and capture all its output, then you need to look at the library calls you use to start that external program, most likely there is a way to ask it to give you some way to read the output and wait for completion.
| How to capture Python interpreter's and/or CMD.EXE's output from a Python script? |
Is it possible to capture Python interpreter's output from a Python script?
Is it possible to capture Windows CMD's output from a Python script?
If so, which librar(y|ies) should I look into?
| [
"If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and s... | [
10,
6,
3,
1,
0
] | [] | [] | [
"cmd",
"python",
"windows"
] | stackoverflow_0000024931_cmd_python_windows.txt |
Q:
Deploying python app to Mac and Windows users
I've written an app in python that depends on wxPython and some other python libraries. I know about pyexe for making python scripts executable on Windows, but what would be the easiest way to share this with my Mac using friends who wouldn't know how to install the required dependencies? One option would be to bundle my dependencies in the same package, but that seems kind of clunky. How do people usually deploy such apps? For once I miss Java...
A:
You could check out py2app, which is similar to py2exe
A:
How do people usually deploy such apps?
2 choices.
With instructions.
All bundled up.
You write simple instructions like this. Folks can follow these pretty reliably, unless they don't have enough privileges. Sometimes they need to sudo in linux environments.
Download easy_install (or pip)
easy_install this, easy_install that (or pip this, pip that)
easy_install whatever package you wrote.
It works really well. If you download some Python packages you'll see this in action.
Sphinx requires docutils. Django requires docutils and PIL. It works out really well to simply document the dependencies. Other folks seem to do it without serious problems. Follow their lead.
Bundling things up means you have to
(a) provide the entire original distribution (as required by most open source licenses)
(b) provide a compatible open source license with the licenses of the things you bundled. This can be easy if you depend on things that all of the same license. Otherwise, you basically can't redistribute them and have to resort to installation instructions.
| Deploying python app to Mac and Windows users | I've written an app in python that depends on wxPython and some other python libraries. I know about pyexe for making python scripts executable on Windows, but what would be the easiest way to share this with my Mac using friends who wouldn't know how to install the required dependencies? One option would be to bundle my dependencies in the same package, but that seems kind of clunky. How do people usually deploy such apps? For once I miss Java...
| [
"You could check out py2app, which is similar to py2exe\n",
"\nHow do people usually deploy such apps?\n\n2 choices.\n\nWith instructions.\nAll bundled up.\n\nYou write simple instructions like this. Folks can follow these pretty reliably, unless they don't have enough privileges. Sometimes they need to sudo in... | [
2,
0
] | [] | [] | [
"deployment",
"python"
] | stackoverflow_0003379032_deployment_python.txt |
Q:
call external python script in same window
Im trying to call an external python script, and so far i was able to do so successfully using:
os.system("START fileNameHere")
However right now im running in the console, and i want the contents of the other python file to be shown in the same console. ATM it shows it in a separate console.
Thanks in Advance.
A:
This outta do it.
import subprocess
p = subprocess.Popen('command', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print line,
retval = p.wait()
| call external python script in same window | Im trying to call an external python script, and so far i was able to do so successfully using:
os.system("START fileNameHere")
However right now im running in the console, and i want the contents of the other python file to be shown in the same console. ATM it shows it in a separate console.
Thanks in Advance.
| [
"This outta do it.\nimport subprocess\n\np = subprocess.Popen('command', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n for line in p.stdout.readlines():\n print line,\nretval = p.wait()\n\n"
] | [
1
] | [] | [] | [
"console",
"external",
"python"
] | stackoverflow_0003379151_console_external_python.txt |
Q:
Asynchronous api for obtaining GPS position in python for S60
I'm using positioning.position(). but this function is blocking.
I want to be able to run another function while the GPS is being measured.
thanks
A:
I'm not familiar with the S60, but if it supports threading here's an example of doing two functions at once:
import threading
import time
def doit1():
for i in range(10):
time.sleep(.1)
print 'doit1(%d)' % i
def doit2():
for i in range(10):
time.sleep(.2)
print 'doit2(%d)' % i
t = threading.Thread(target=doit2)
t.start()
doit1()
t.join()
print 'All done.'
Hope this helps.
| Asynchronous api for obtaining GPS position in python for S60 | I'm using positioning.position(). but this function is blocking.
I want to be able to run another function while the GPS is being measured.
thanks
| [
"I'm not familiar with the S60, but if it supports threading here's an example of doing two functions at once:\nimport threading\nimport time\n\ndef doit1():\n for i in range(10):\n time.sleep(.1)\n print 'doit1(%d)' % i\n\ndef doit2():\n for i in range(10):\n time.sleep(.2)\n prin... | [
2
] | [] | [] | [
"position",
"pys60",
"python"
] | stackoverflow_0003378922_position_pys60_python.txt |
Q:
Which is the most preferred language to start with dynamic languages
After working for on JAVA for a long time now i feel like also learn some other language just for a change. This time i want to spend some time learning and reading one of the dynamic languages.
Which is the most appropriate one that covers most of the features offered by dynamic languages and the syntax which probably is fun and also one that is closer to the syntax used by most of the dynamic languages.
BR,
Keshav
A:
Python is always fun.Go for it.
A:
Javascript is by far the most useful of dynamic languages for real-world practical work - not only is it irreplaceable for "client-side" work on the user's browser, but Node.js is rapidly making it very interesting for server-side work, too. Sure, it has many issues, but a book such as Crockford's Javascript: the good parts will help you avoid many of them.
JS's syntax of course is quite different from that of dynamic languages such as Python or Ruby, which try to avoid braces and semicolons (which you'd better not avoid in JS: it tries to guess on your behalf but too often it guesses wrong!-). There is really no "syntax used by most of the dynamic languages" given these huge syntax differences (which grow if you throw into the mix Scheme, Erlang, Perl, PHP, Tcl, ...), so that part of your specs is moot.
Second most useful today is probably Python -- as Allison Randall (program chair of OSCON and a well-known Perl guru) put it, Python has surprisingly become something of a "default language" in many fields. For example, the SEC is considering a regulation to mandate publication of algorithms used in stock trading, and their initially proposed language for such a publication is "of course" Python. As this post explains,
Why Python? The SEC actually asks for
comments on whether they should
mandate Perl, Java or something else
instead. I use Perl quite extensively,
but the idea that Perl is a suitable
language for implementing a
transparency requirement is laughable.
Perl is a model of powerful but
unreadable and cryptic code. As for
Java and C-Sharp, there is little
point in having open source code if
the interpreter is not also open
source. I do not use Python myself,
but it appears to be a good choice for
the task at hand.
This is what Allison meant by "default language", I think: not necessarily the one you'll choose to implement a given task (e.g. the above post's author would prefer using Perl), but a language everybody's supposed to be able to read in order to understand an algorithm that is published or otherwise presented -- as Bruce Eckel (deservedly-best-selling author of books on C++ and Java) puts it here,
Python is executable pseudocode.
You can look at the "executable" part as a bonus (it does guarantee lack of ambiguity, which non-executable pseudocode might lack;-) even though large systems such as reddit and youtube have been implemented in it.
At the other extreme, if you're not necessarily looking for immediately useful knowledge, but for mind-broadening, Scheme or Erlang might suit you best (but the syntax in each case is quite different from most other languages, be warned;-).
However, in that case, I'd suggest Mozart, to go with the masterpiece that is Van Roy's and Haridi's Concepts, Techniques, and Models of Computer Programming (that book is plenty motivation to learn Mozart, just like SICP is to learn Scheme -- indeed, I've described CTMCP as "SICP for the 21st century"!-).
A:
Learn [one of] these:
Ruby
Python
Clojure (a modern Lisp)
JavaScript (yes, this is a great dynamic language!)
Don't transition via a semi-dynamic, semi-Java language. Just jump in and try a dynamic language. In order to really understand what else is going on, you have to get out of the Java world by jumping in, not by sticking your toes into the water.
Yes, I know Clojure is on the JVM and that Ruby and Python have implementations on the JVM as well. But the runtime implementation of a language does not define the language. Learn the language, and you can pick a favorite runtime.
A:
Since you have a Java background, Groovy might be worth a shot.
It's a lot of fun :)
A:
You may want to start with Groovy (http://groovy.codehaus.org/), as that is a language that is close to Java, so you can use what you know, but then start to gain experience to using functions as first-class objects, for example.
Then, once you understand Groovy then you can start to experiment with Ruby and Python.
A:
Ahah, nice troll :) (with ruby and python tags).
In my humble opinion, after trying many languages, my favorite is Ruby with Ruby on Rails.
A:
Try Jython, if you like Java, this way you can both ;-)
| Which is the most preferred language to start with dynamic languages | After working for on JAVA for a long time now i feel like also learn some other language just for a change. This time i want to spend some time learning and reading one of the dynamic languages.
Which is the most appropriate one that covers most of the features offered by dynamic languages and the syntax which probably is fun and also one that is closer to the syntax used by most of the dynamic languages.
BR,
Keshav
| [
"Python is always fun.Go for it.\n",
"Javascript is by far the most useful of dynamic languages for real-world practical work - not only is it irreplaceable for \"client-side\" work on the user's browser, but Node.js is rapidly making it very interesting for server-side work, too. Sure, it has many issues, but a... | [
7,
4,
3,
2,
2,
2,
0
] | [] | [] | [
"dynamic_languages",
"python",
"ruby"
] | stackoverflow_0003379174_dynamic_languages_python_ruby.txt |
Q:
Why doesn't mydict.items().sort() work?
When I try and sort my dictionary, I get an error: ''nonetype' object is not iterable.
I am doing:
for k,v in mydict.items().sort():
A:
The sort method returns None (it has sorted the temporary list given by items(), but that's gone now). Use:
for k, v in sorted(mydict.iteritems()):
Using .items() in lieu of .iteritems() is also OK (and needed if you're in Python 3) but, in Python 2 (where .items() makes and returns a list while .iteritems() doesn't, just returns an iterator), avoiding the making of an extra list is advantageous -- sorted will make its own list to return, anyway, without altering the argument passed to it.
| Why doesn't mydict.items().sort() work? | When I try and sort my dictionary, I get an error: ''nonetype' object is not iterable.
I am doing:
for k,v in mydict.items().sort():
| [
"The sort method returns None (it has sorted the temporary list given by items(), but that's gone now). Use:\nfor k, v in sorted(mydict.iteritems()):\n\nUsing .items() in lieu of .iteritems() is also OK (and needed if you're in Python 3) but, in Python 2 (where .items() makes and returns a list while .iteritems() ... | [
12
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003379282_dictionary_python.txt |
Q:
ModelForm and error_css_class
my problem is simple. Where the right place for a custom error_css_class value is when using ModelForm?
I tried this:
class ToolForm(ModelForm):
error_css_class = 'wrong_list'
class Meta:
model = Tool
widgets = {
'name' : TextInput(attrs={'class': 'small_input corners'}),
'description' : Textarea(attrs={'cols': 20, 'rows': 5, 'class': 'text corners'}),
'stocks' : TextInput(attrs={'class': 'small_input corners'}),
'state' : Textarea(attrs={'cols': 25, 'rows': 6, 'class': 'text corners'}),
}
Also, I tried as a class Meta value. Doesn't work either.
By now I just changed my css to 'errorlist' (u know, the default one), buuut this kind of doubts make me unhappy :P.
Any help is appreciated.
A:
You can define your own error list class by inherting from django's ErrorList. See the docs for details:
Customizing the error list format
Note that you'll have to override the method to output the full HTML and can't just replace CSS class. You could call the base method and do a string replace on "class=\"errolist\"" and return the output.
| ModelForm and error_css_class | my problem is simple. Where the right place for a custom error_css_class value is when using ModelForm?
I tried this:
class ToolForm(ModelForm):
error_css_class = 'wrong_list'
class Meta:
model = Tool
widgets = {
'name' : TextInput(attrs={'class': 'small_input corners'}),
'description' : Textarea(attrs={'cols': 20, 'rows': 5, 'class': 'text corners'}),
'stocks' : TextInput(attrs={'class': 'small_input corners'}),
'state' : Textarea(attrs={'cols': 25, 'rows': 6, 'class': 'text corners'}),
}
Also, I tried as a class Meta value. Doesn't work either.
By now I just changed my css to 'errorlist' (u know, the default one), buuut this kind of doubts make me unhappy :P.
Any help is appreciated.
| [
"You can define your own error list class by inherting from django's ErrorList. See the docs for details:\n\nCustomizing the error list format\n\nNote that you'll have to override the method to output the full HTML and can't just replace CSS class. You could call the base method and do a string replace on \"class... | [
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003379302_django_django_forms_python.txt |
Q:
ImageKit in Django
I am implementing ImageKit in a Django app and I have everything set up properly to my knowledge. When I run the command
$python manage.py ikflush main
the command seems to run fine but nothing appears to happen. None of the images get resized or stored and cannot be accessed.
main.models.py:
class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.CharField(max_length=255, null=True, blank=True)
original = models.ImageField(upload_to='uploads/product-images/zoom/')
class IKOptions:
spec_module = 'main.specs'
cache_dir = 'uploads/cache'
image_field = 'original'
main.specs.py:
from imagekit.specs import ImageSpec
from imagekit import processors
class ResizeSmall(processors.Resize):
width = 230
height = 289
crop = False
class SmallImage(ImageSpec):
access_as = 'small_image'
pre_cache = True
processors = [ResizeSmall]
in template: (prints nothing)
{% for image in images %}
{{ image.small_image }}<br />
{% endfor %}
Does anyone have any ideas on how to debug this? I really want to use ImageKit for this but I have never implemented it before. Thanks in advance!
A:
This may just be a formatting mistake in the question and not in your code. But IKOptions should be nested in your model class:
class ProductImage(models.Model):
# fields, etc...
class IKOptions:
# ...
Also, before you run ikflush, did you add ImageKit to INSTALLED_APPS in your settings file?
A:
Your ProductImage model needs to inherit from imagekit.models.ImageModel in instead of models.Model.
| ImageKit in Django | I am implementing ImageKit in a Django app and I have everything set up properly to my knowledge. When I run the command
$python manage.py ikflush main
the command seems to run fine but nothing appears to happen. None of the images get resized or stored and cannot be accessed.
main.models.py:
class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.CharField(max_length=255, null=True, blank=True)
original = models.ImageField(upload_to='uploads/product-images/zoom/')
class IKOptions:
spec_module = 'main.specs'
cache_dir = 'uploads/cache'
image_field = 'original'
main.specs.py:
from imagekit.specs import ImageSpec
from imagekit import processors
class ResizeSmall(processors.Resize):
width = 230
height = 289
crop = False
class SmallImage(ImageSpec):
access_as = 'small_image'
pre_cache = True
processors = [ResizeSmall]
in template: (prints nothing)
{% for image in images %}
{{ image.small_image }}<br />
{% endfor %}
Does anyone have any ideas on how to debug this? I really want to use ImageKit for this but I have never implemented it before. Thanks in advance!
| [
"This may just be a formatting mistake in the question and not in your code. But IKOptions should be nested in your model class:\nclass ProductImage(models.Model):\n # fields, etc...\n class IKOptions:\n # ...\n\nAlso, before you run ikflush, did you add ImageKit to INSTALLED_APPS in your settings fil... | [
1,
1
] | [] | [] | [
"django",
"django_imagekit",
"imagekit",
"python"
] | stackoverflow_0003366952_django_django_imagekit_imagekit_python.txt |
Q:
Django Fixtures Error: Unknown application
I have a project w/ multiple apps. I am attempting to use the dumpdata command to create a fixture for each app. Calling dumpdata on a given app seems to work well.
This prints the data to the console:
python manage.py dumpdata myapp
However, when I attempt to create a json file containing the dumped data:
python manage.py dumpdata apps/myapp/fixtures/initial_data.json
This error is thrown:
Error: Unknown application: apps/myapp/fixtures/initial_data
The fixtures dir already exists and I've tried multiple variations of the path to the json file. There is another coder on the project and we are working with the same source code. He does not appear to be running into the same issue though.
We are using Django 1.2.
A:
You give the correct syntax in your first snippet. The argument after dumpdata is an application, not a file.
If you want to save that output to a file, you use standard redirection:
python manage.py dumpdata myapp > apps/myapp/fixtures/initial_data.json
| Django Fixtures Error: Unknown application | I have a project w/ multiple apps. I am attempting to use the dumpdata command to create a fixture for each app. Calling dumpdata on a given app seems to work well.
This prints the data to the console:
python manage.py dumpdata myapp
However, when I attempt to create a json file containing the dumped data:
python manage.py dumpdata apps/myapp/fixtures/initial_data.json
This error is thrown:
Error: Unknown application: apps/myapp/fixtures/initial_data
The fixtures dir already exists and I've tried multiple variations of the path to the json file. There is another coder on the project and we are working with the same source code. He does not appear to be running into the same issue though.
We are using Django 1.2.
| [
"You give the correct syntax in your first snippet. The argument after dumpdata is an application, not a file.\nIf you want to save that output to a file, you use standard redirection: \npython manage.py dumpdata myapp > apps/myapp/fixtures/initial_data.json\n\n"
] | [
2
] | [] | [] | [
"django",
"fixtures",
"python"
] | stackoverflow_0003379500_django_fixtures_python.txt |
Q:
min max algorithm in python
In the minmax algorithm,How to determine when your function reaches the end of the tree and break the recursive calls.
I have made a max function in which I am calling the min function. In the min function , what shud I do?? For max function, I am just returning the bestscore.
def maxAgent(gameState, depth):
if (gameState.isWin()):
return gameState.getScore()
actions = gameState.getLegalActions(0);
bestScore = -99999
bestAction = Directions.STOP
for action in actions:
if (action != Directions.STOP):
score = minAgent(gameState.generateSuccessor(0, action), depth, 1)
if (score > bestScore):
bestScore = score
bestAction = action
return bestScore
def minvalue(gameState,depth,agentIndex):
if (gameState.isLose()):
return gameState.getScore()
else:
finalstage = False
number = gameState.getNumAgents()
if (agentIndex == number-1):
finalstage = True
bestScore = 9999
for action in gameState.getLegalActions(agentIndex):
if(action != Directions.STOP
I could not understand how to proceed now?I not allowed to set the limit of depth of tree. it has to be arbitrary.
A:
Usually you want to search until a certain recursion depth (e.g. n moves in advance, when playing chess). Therefore, you should pass the current recursion depth as a parameter. You may abort earlier when your results do not improve, if you can determine that with little effort.
A:
In the minmax algorithm,How to
determine when your function reaches
the end of the tree and break the
recursive calls.
Basically, you're asking when you've reached a leaf node.
A leaf node occurs when you've reached the maximum depth for the search, or a terminal node (i.e. a position that ends the game).
A:
I completely agree with relet. But you might want to consider this also:
There are times when you might also think that the current branch that you are exploring is worth exploring a little deeper. This will call for some further heuristics to be applied. I don't know how advanced the solution for your problem is required to be. This is because I don't know where the problem is coming from.
As suggested by Amber, try posting some code so we know how complex you want the solution to be. Further, if you explained how much you know/can_do, then we might be able to suggest more useful options - things that you might be able to realistically implement, rather than just amazing ideas that you may not know how to or have the time to implement
A:
This site has post of minimax, even though it is based on IronPython:
http://blogs.microsoft.co.il/blogs/dhelper/archive/2009/07/13/getting-started-with-ironpython-part-4-minimax-algorithm.aspx
It says:
The Minimax algorithm is recursive by nature, and as such it requires a stop condition, in our case either the game has ended (no more moves) or the desired depth has been reached (lines 3-8).
You can avoid having two different functions by using Negamax http://en.wikipedia.org/wiki/Negamax
| min max algorithm in python | In the minmax algorithm,How to determine when your function reaches the end of the tree and break the recursive calls.
I have made a max function in which I am calling the min function. In the min function , what shud I do?? For max function, I am just returning the bestscore.
def maxAgent(gameState, depth):
if (gameState.isWin()):
return gameState.getScore()
actions = gameState.getLegalActions(0);
bestScore = -99999
bestAction = Directions.STOP
for action in actions:
if (action != Directions.STOP):
score = minAgent(gameState.generateSuccessor(0, action), depth, 1)
if (score > bestScore):
bestScore = score
bestAction = action
return bestScore
def minvalue(gameState,depth,agentIndex):
if (gameState.isLose()):
return gameState.getScore()
else:
finalstage = False
number = gameState.getNumAgents()
if (agentIndex == number-1):
finalstage = True
bestScore = 9999
for action in gameState.getLegalActions(agentIndex):
if(action != Directions.STOP
I could not understand how to proceed now?I not allowed to set the limit of depth of tree. it has to be arbitrary.
| [
"Usually you want to search until a certain recursion depth (e.g. n moves in advance, when playing chess). Therefore, you should pass the current recursion depth as a parameter. You may abort earlier when your results do not improve, if you can determine that with little effort.\n",
"\nIn the minmax algorithm,How... | [
3,
1,
1,
0
] | [] | [] | [
"algorithm",
"artificial_intelligence",
"python"
] | stackoverflow_0003379616_algorithm_artificial_intelligence_python.txt |
Q:
Splitting a module with 8+ classes into a package with each class in its own file
I have a module (tools.py) containing many classes. I'd like to extract these out into its own "whyteboard.tools" package, each class being inside its own file.
However, I previously moved from having all my classes in one base directory to being in a package below the root of my project, and had issues with loading in pickled files that had been saved in the old format. (see: https://stackoverflow.com/questions/2121874). I had to monkey patch the sys.modules dict while loading the file and then delete it afterwards. nasty...
What's the best way to do this move?
Is it best to also import each of my classes in the package's __init__ otherwise I'd have to
from whyteboard.tools.pen import Pen
instead of
from whyteboard.tools import Pen
A:
I've typically seen the init.py in modules do something like:
from whyteboard.tools.pen import *
This way you can always import from whyteboard.tools and reference any of the classes inside this module without knowing where they are located. You simply need to just know of the classes provided by the whyteboard.tools package.
A:
What's the best way to do this move?
First. Don't. Class per file isn't going to improve anything, so why bother?
had issues with loading in pickled files that had been saved in the old format
Correct. You must have issues loading files pickled in the old format because the class names have changed.
Why change them if it causes problems?
If you absolutely must change them, you can try something like this to convert. Saves monkey patching. Moves forward to your new architecture.
import this.that.module
import pickle
import os
legacy_obj= pickle.load( someFile )
os.rename( someFile, someFile+".bak")
import this.that.module.class
new_obj= this.that.module.class( legacy_obj )
pickle.save( someFile )
There's a middle ground between 1900 lines in one file and 8+ files with 200+ lines each. A single class of 200+ lines indicates that you may have other design problems. You might want to tackle those first before creating 8 files of "1 class each".
Consider that a 200-line class may already be doing too much. You might want to decompose your classes to have more fine-grained responsibilities. Having done that you may find that you have a few modules -- each with a few classes.
You might want to decompose collections of related classes into reusable modules. A simplistic "class-per-file" approach may be a poor way to restructure this.
| Splitting a module with 8+ classes into a package with each class in its own file | I have a module (tools.py) containing many classes. I'd like to extract these out into its own "whyteboard.tools" package, each class being inside its own file.
However, I previously moved from having all my classes in one base directory to being in a package below the root of my project, and had issues with loading in pickled files that had been saved in the old format. (see: https://stackoverflow.com/questions/2121874). I had to monkey patch the sys.modules dict while loading the file and then delete it afterwards. nasty...
What's the best way to do this move?
Is it best to also import each of my classes in the package's __init__ otherwise I'd have to
from whyteboard.tools.pen import Pen
instead of
from whyteboard.tools import Pen
| [
"I've typically seen the init.py in modules do something like:\nfrom whyteboard.tools.pen import *\n\nThis way you can always import from whyteboard.tools and reference any of the classes inside this module without knowing where they are located. You simply need to just know of the classes provided by the whyteboar... | [
2,
1
] | [] | [] | [
"extract",
"package",
"python"
] | stackoverflow_0003379662_extract_package_python.txt |
Q:
Can Python be good alternative for web app that would otherwise be done in Java EE?
Can Python be a good alternative to a web app that would otherwise be developed with Java EE? If so, which Python web app framework(s) may be a good choice? Please see details about the app below. I've asked a few people individually about this, who have worked for a good amount of time on either or both of Java EE and Python web apps, and got a few answers that indicated Python might not such a good choice, mainly due to ease of scaling, which is one of the needs. The other reason given was relative lack of Python developers in the part of the world where the app is being developed. We might be able to overcome the second one, but not sure about the first.
The app in question is a financial domain B2B one, with a few different types of users (as in: "actors" having different real-life roles - e.g. buyers, sellers), some admin users, will use an RDBMS, will have CRUD (Create/Read/Update/Delete) plus search functionality for master tables, some types of transactions involving both master and transaction tables, (with fairly straightforward, not very complex logic), and some reports to PDF for most / all of the search screens (queries). Around 80 or so features, where the features mostly map to screens in the app; not all, though. It will have a few types of batch jobs too, for which the plan is to run them at times when the users are not permitted to use the app. Will have JavaScript and AJAX on the front end. Will have the feature of sending emails to users, not just for signup or resetting passwords, but for transaction-related info as well. No programmatic reading of incoming emails though.
The aim is for it to eventually to get a medium level of scale in terms of numbers of (paying) users and transactions, not very high, but not too small a number - say in the range of 10,000 users, of which 2000 may be concurrently accessing the app in a time frame of 15 to 20 minutes. It will be a SaaS (Software as a Service) app.
I know the question is very general and open ended and I expect some answers on the lines of "It depends" :) but still want to get some views from people who have worked on such things.
Feel free to ask more questions if needed to answer. I'll answer them except for anything that is confidential.
Thanks.
Edit 1:
Really appreciate all the answers. I will take a little time to think about them, and then get back with further questions (original, or in response to answers) or comments, if any.
A:
It's a very good alternative indeed. Your project sounds to me like it'll need quite a lot of custom programming, which in the Python world would point to basing your web app from Pylons ( http://pylonshq.com/ ). Pylons is mostly a glue layer, and you'll pick a template engine and ORM (try SQLAlchemy ( http://www.sqlalchemy.org/ ) for maximum power or SQLObject ( http://www.sqlobject.org/ ) for a somewhat simpler approach) layer of your choice. You will probably want to generate the PDF's using ReporLab ( http://www.reportlab.com/ ). For the email part, you'll get a long way with Pythons built-in email functionality (see docs at Python's own website).
Edit 1: you have almost certainly already thought of this, but..: success of course depends a lot on the competencies of the developers you have access to, i.e. if the know Python already, or are eager and quick to learn. I'd say Python is a very good beginners language, but it takes a little time to become really 'Pythonic' (roughly translatable as being proficient with Python's characteristics, e.g. using features like generators, list comprehensions, getattr and setattr etc fluently).
Edit 2: also, take a look at PyPI, the Python package index, http://pypi.python.org/pypi to 'window shop' for modules that'll provide additional functionality for you. There's a lot of them.
A:
Any language/framework is a good choice, if it is used properly by competent developers. Sometimes the best choice is the one with which your team is most familiar.
Given your client space though, if you want to move to a "higher productivity" framework, I suggest Grails. Its implemented in Groovy, which Java developers can pick up naturally, and has various tools for generating wars, which can be deployed in your favorite servlet container. It takes a lot of the pain out of tradition J2EE development, as long as you follow the conventions. It has a ton of robust plugins for things like authentication/authorization. It will save you a ton of time.
A:
I think Python would be eminently suitable for your requirements, and you are likely to get the development done much more quickly than with a Java based solution.
There are several mature Python web application frameworks. Django is the most popular and will probably do much of what you want out of the box.
performance is unlikely to be an issue for the figures you give - any bottleneck is likely to be in the database access, so the speed of the language you use is largely irrelevant. Python is fast enough to run YouTube, and they have orders of magnitude more users than you will. (If you don't have time to watch the linked presentation, the lead scalability engineer at YouTube says that 99.999% of their application code is written in Python).
A:
Scaling is largely independent of your choice of language, but yes, python can scale just fine for what you describe. Plenty of large sites use Python, including reddit and youtube (here's a brief writeup on why reddit uses python).
Framework: Django is the a very popular framework, comes with nice admin capabilities built in, includes an ORM that speaks with the major databases, includes plenty of functionality, and has a vibrant community that churns out new apps and extensions constantly. We use it and like it.
For your AJAX/CRUD/Rest needs take a look at django-piston, a clean way to create rest based APIs.
| Can Python be good alternative for web app that would otherwise be done in Java EE? | Can Python be a good alternative to a web app that would otherwise be developed with Java EE? If so, which Python web app framework(s) may be a good choice? Please see details about the app below. I've asked a few people individually about this, who have worked for a good amount of time on either or both of Java EE and Python web apps, and got a few answers that indicated Python might not such a good choice, mainly due to ease of scaling, which is one of the needs. The other reason given was relative lack of Python developers in the part of the world where the app is being developed. We might be able to overcome the second one, but not sure about the first.
The app in question is a financial domain B2B one, with a few different types of users (as in: "actors" having different real-life roles - e.g. buyers, sellers), some admin users, will use an RDBMS, will have CRUD (Create/Read/Update/Delete) plus search functionality for master tables, some types of transactions involving both master and transaction tables, (with fairly straightforward, not very complex logic), and some reports to PDF for most / all of the search screens (queries). Around 80 or so features, where the features mostly map to screens in the app; not all, though. It will have a few types of batch jobs too, for which the plan is to run them at times when the users are not permitted to use the app. Will have JavaScript and AJAX on the front end. Will have the feature of sending emails to users, not just for signup or resetting passwords, but for transaction-related info as well. No programmatic reading of incoming emails though.
The aim is for it to eventually to get a medium level of scale in terms of numbers of (paying) users and transactions, not very high, but not too small a number - say in the range of 10,000 users, of which 2000 may be concurrently accessing the app in a time frame of 15 to 20 minutes. It will be a SaaS (Software as a Service) app.
I know the question is very general and open ended and I expect some answers on the lines of "It depends" :) but still want to get some views from people who have worked on such things.
Feel free to ask more questions if needed to answer. I'll answer them except for anything that is confidential.
Thanks.
Edit 1:
Really appreciate all the answers. I will take a little time to think about them, and then get back with further questions (original, or in response to answers) or comments, if any.
| [
"It's a very good alternative indeed. Your project sounds to me like it'll need quite a lot of custom programming, which in the Python world would point to basing your web app from Pylons ( http://pylonshq.com/ ). Pylons is mostly a glue layer, and you'll pick a template engine and ORM (try SQLAlchemy ( http://www.... | [
5,
3,
3,
2
] | [] | [] | [
"jakarta_ee",
"java",
"python"
] | stackoverflow_0003379440_jakarta_ee_java_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.