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:
How to convert an accented character in an unicode string to its unicode character code using Python?
Just wonder how to convert a unicode string like u'é' to its unicode character code u'\xe9'?
A:
You can use Python's repr() function:
>>> unicode_char = u'é'
>>> repr(unicode_char)
"u'\\xe9'"
A:
ord will give you the numeric value, but you'll have to convert it into hex:
>>> ord(u'é')
233
A:
u'é' and u'\xe9' are exactly the same, they are just different representations:
>>> u'é' == u'\xe9'
True
| How to convert an accented character in an unicode string to its unicode character code using Python? | Just wonder how to convert a unicode string like u'é' to its unicode character code u'\xe9'?
| [
"You can use Python's repr() function:\n>>> unicode_char = u'é'\n>>> repr(unicode_char)\n\"u'\\\\xe9'\"\n\n",
"ord will give you the numeric value, but you'll have to convert it into hex:\n>>> ord(u'é')\n233\n\n",
"u'é' and u'\\xe9' are exactly the same, they are just different representations:\n>>> u'é' == u'\... | [
3,
1,
1
] | [] | [] | [
"character",
"codepoint",
"diacritics",
"python",
"unicode"
] | stackoverflow_0003499087_character_codepoint_diacritics_python_unicode.txt |
Q:
Trouble installing Django
I'm having trouble installing Django, even if I follow the instructions here: http://www.djangobook.com/en/2.0/chapter02/
Could someone please provide baby steps to installing Django. I'm talking baby steps that really break it down, so that a retarded person could do it.
I've installed Django and unzipped the file, but I'm unsure where to go from there.
I on Windows 7, and I've downloaded Python 2.7 and Django 1.2.1.
A:
OK. If you have Python installed, you can then proceed to execute setup.py given with Django. Head over to the directory where you unzipped Django.
cd C:\path\to\Django\
You can now execute
python setup.py install
This step requires your python executable to be present in the system's PATH environment variable. If it isn't you will have to append your Python installation directory to your PATH.
Update
You can verify that the installation has gone well with the following command. Run python and execute the command import django. If no import errors are thrown everything is OK. Thanks to cji for the tip.
| Trouble installing Django | I'm having trouble installing Django, even if I follow the instructions here: http://www.djangobook.com/en/2.0/chapter02/
Could someone please provide baby steps to installing Django. I'm talking baby steps that really break it down, so that a retarded person could do it.
I've installed Django and unzipped the file, but I'm unsure where to go from there.
I on Windows 7, and I've downloaded Python 2.7 and Django 1.2.1.
| [
"OK. If you have Python installed, you can then proceed to execute setup.py given with Django. Head over to the directory where you unzipped Django.\ncd C:\\path\\to\\Django\\\n\nYou can now execute \npython setup.py install\n\nThis step requires your python executable to be present in the system's PATH environment... | [
3
] | [] | [] | [
"django",
"installation",
"python"
] | stackoverflow_0003500371_django_installation_python.txt |
Q:
Way to get value of this hex number
import binascii
f = open('file.ext', 'rb')
print binascii.hexlify(f.read(4))
f.close()
This prints:
84010100
I know that I must retrieve the hex number 184 out of this data.
How can it be done in python? I've used the struct module before, but I don't know if its little endian, big..whatever.. how can I get 184 from this number using struct?
A:
>>> x = b'\x84\x01\x01\x00'
>>> import struct
>>> struct.unpack_from('<h', x)
(388,)
>>> map(hex, struct.unpack_from('<h', x))
['0x184']
< means little endian, h means read a 16-bit integer ("short"). Detail is in the package doc.
| Way to get value of this hex number | import binascii
f = open('file.ext', 'rb')
print binascii.hexlify(f.read(4))
f.close()
This prints:
84010100
I know that I must retrieve the hex number 184 out of this data.
How can it be done in python? I've used the struct module before, but I don't know if its little endian, big..whatever.. how can I get 184 from this number using struct?
| [
">>> x = b'\\x84\\x01\\x01\\x00'\n>>> import struct\n>>> struct.unpack_from('<h', x)\n(388,)\n>>> map(hex, struct.unpack_from('<h', x))\n['0x184']\n\n< means little endian, h means read a 16-bit integer (\"short\"). Detail is in the package doc.\n"
] | [
2
] | [] | [] | [
"binary",
"python"
] | stackoverflow_0003500493_binary_python.txt |
Q:
Interacting with SVN from appengine
I've got a couple of projects where it would be useful to be able to interact with an SVN server from Google App Engine.
Pull specific files from the SVN (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate)
Commit changes to the SVN (this is the really hard/important part)
Possibly run an SVN server (from an App Engine app, I'm guessing this isn't possible)
I would prefer a python solution, but I can survive with Java if I must.
A:
you can try using SVNKit with the java runtime
A:
DryDrop (http://drydrop.binaryage.com/) is a Git based solution you may want to look at for comparison of what you're trying to do.
A:
You can talk to a svn server(if setup with apache running mod_dav_svn) using the webdav protocol. See apache's implementation details Problem is that google appengine's urlfetch system doesn't allow for HTTP request methods other then GET, POST, HEAD, PUT and DELETE. (webdav uses custom request methods like PROPFIND, PROPPATCH, etc..) So at this time you are restricted to just viewing the contents of the svn server.
You can however use google appengine to implement a webdav provider. Have a look at the gae-webdav project for more information.
| Interacting with SVN from appengine | I've got a couple of projects where it would be useful to be able to interact with an SVN server from Google App Engine.
Pull specific files from the SVN (fairly easy, since there is a web interface which I can grab the data off automatically, but how do I authenticate)
Commit changes to the SVN (this is the really hard/important part)
Possibly run an SVN server (from an App Engine app, I'm guessing this isn't possible)
I would prefer a python solution, but I can survive with Java if I must.
| [
"you can try using SVNKit with the java runtime\n",
"DryDrop (http://drydrop.binaryage.com/) is a Git based solution you may want to look at for comparison of what you're trying to do.\n",
"You can talk to a svn server(if setup with apache running mod_dav_svn) using the webdav protocol. See apache's implementat... | [
4,
3,
1
] | [] | [] | [
"google_app_engine",
"java",
"python",
"svn"
] | stackoverflow_0001604220_google_app_engine_java_python_svn.txt |
Q:
Python Console Name Customization
Usually the Python console looks like this:
>>> command
Is there a way to make it look like:
SomeText>>> command
A:
sys.ps1 == ">>>"
sys.ps2 == "..."
You can also change this in the PYTHONSTARTUP environment variable.
For example (this is not secure), put the following in a script somewhere and set PYTHONSTARTUP to point at that script.
import sys
import getpass
sys.ps1 = getpass.getuser( ) + ">>> "
Of course, you could change the last line above to anything you want.
A:
You could try
import sys
import os
sys.ps1 = os.getenv("USER") + sys.ps1
(or getpass.getuser() as suggested by the other answer)
In the corrected version, it's even easier, of course:
import sys
sys.ps1 = "SomeText" + sys.ps1
A:
IPython provides convenient way of setting sophisticated prompts as described here.
| Python Console Name Customization | Usually the Python console looks like this:
>>> command
Is there a way to make it look like:
SomeText>>> command
| [
"sys.ps1 == \">>>\"\nsys.ps2 == \"...\"\n\nYou can also change this in the PYTHONSTARTUP environment variable.\nFor example (this is not secure), put the following in a script somewhere and set PYTHONSTARTUP to point at that script.\nimport sys\nimport getpass\nsys.ps1 = getpass.getuser( ) + \">>> \"\n\nOf course,... | [
6,
2,
0
] | [] | [] | [
"command_line_interface",
"console",
"customization",
"python"
] | stackoverflow_0003500799_command_line_interface_console_customization_python.txt |
Q:
Your typical sheep counting regular expression in python question
at night, after saying my prayers, i typically count sheep to help me fall asleep.
i want a regular expression to help me with the correct count.
i want the following strings to match
0
1sheep
2sheepsheep
3sheepsheepsheep
and so on.
what is the regular expression for this?
something like '(\d+)(sheep){\1}' if {\1} would do what i want it to do
what if i count my sheep in pairs (1sheepsheep and 2sheepsheepsheepsheep), what would the regular expression be then?
A:
Python's regular expression engine does not support parsing a matched subexpression to a repetition count, and I don't think this should be done with RegExp either.
The best bet is to combine RegExp matching and checking with code:
rx = re.compile(r'^(\d+)((?:sheep)*)$')
m = rx.match(theString)
if m and len(m.group(2)) == 5 * int(m.group(1)):
print ("Matched")
A:
This is not something you should do with regex alone; you should first match the number at the start of the string and then dynamically generate a regex to match the rest. See the other answers for code examples.
I believe this is doable using Perl regexes (search for (?PARNO)). This is probably why I don't like Perl.
A:
You can extract the digits using a regex, and then compile a second regex using that number on the repetition operator:
import re
theString = '2sheepsheep'
rx = re.compile(r'^(\d+)(sheep)*$')
m = rx.match(theString)
rx = re.compile(r'^(\d+)(sheep){' + m.group(1) + '}$')
# If you count in pairs, you can just change that to:
rx = re.compile(r'^(\d+)(sheepsheep){' + m.group(1) + '}$')
| Your typical sheep counting regular expression in python question | at night, after saying my prayers, i typically count sheep to help me fall asleep.
i want a regular expression to help me with the correct count.
i want the following strings to match
0
1sheep
2sheepsheep
3sheepsheepsheep
and so on.
what is the regular expression for this?
something like '(\d+)(sheep){\1}' if {\1} would do what i want it to do
what if i count my sheep in pairs (1sheepsheep and 2sheepsheepsheepsheep), what would the regular expression be then?
| [
"Python's regular expression engine does not support parsing a matched subexpression to a repetition count, and I don't think this should be done with RegExp either. \nThe best bet is to combine RegExp matching and checking with code:\nrx = re.compile(r'^(\\d+)((?:sheep)*)$')\nm = rx.match(theString)\nif m and len(... | [
3,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003500753_python_regex.txt |
Q:
suitable replacement for python expression
I want to replace the next expression with something simpler but i'm not sure what my changes impli?
if not (self.permission_index_link == 0) \
or not (self.permission_index_link == 8):
with
if not self.permission_index_link == (0,8):
A:
if self.permission_index_link not in (0,8):
# code
Is this what you are looking for? code will run if self.permission_index_link is not 0 or 8.
A:
Are you sure your initial expression is correct? It will always be true. Didn't you mean to use and rather than or?
Use the not in operator:
if self.permission_index_link not in (0,8):
A:
if self.permission_index.link not in (0,8):
| suitable replacement for python expression | I want to replace the next expression with something simpler but i'm not sure what my changes impli?
if not (self.permission_index_link == 0) \
or not (self.permission_index_link == 8):
with
if not self.permission_index_link == (0,8):
| [
"if self.permission_index_link not in (0,8):\n # code\n\nIs this what you are looking for? code will run if self.permission_index_link is not 0 or 8. \n",
"Are you sure your initial expression is correct? It will always be true. Didn't you mean to use and rather than or?\nUse the not in operator:\nif self.perm... | [
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003501007_python.txt |
Q:
Question about bdist directory hierarchy
I just made a small app and then wrote a setup.py file for it. Everything seems to be working, except I can't figure out a small thing.
When passing the bdist option to setup.py, it creates the archive gzipped tar file. When I open that file, I notice that the directory structure is:
> usr
> lib
> python2.6
> site-packages
> Folder 1
> Folder 2
What is the reason for this? Typically, I had expect that Folder 1 and Folder 2 would be in the root directory. Why does bdist add the top level directories? Is there any way I can get rid of them (more importantly, should I get rid of them?)
A:
I think that you want an sdist output .... so try python setup.py sdist
Quote of Python documentation
As a simple example, if I run the following command in the Distutils source tree:
python setup.py bdist
then the Distutils builds my module distribution (the Distutils itself in this case), does a “fake”
installation (also in the build directory), and creates the default type of built distribution for my platform. The default format for built distributions is a “dumb” tar file on Unix, and a simple executable installer on Windows. (That tar file is considered “dumb” because it has to be unpacked in a specific location to work.)
See Python Documentation
| Question about bdist directory hierarchy | I just made a small app and then wrote a setup.py file for it. Everything seems to be working, except I can't figure out a small thing.
When passing the bdist option to setup.py, it creates the archive gzipped tar file. When I open that file, I notice that the directory structure is:
> usr
> lib
> python2.6
> site-packages
> Folder 1
> Folder 2
What is the reason for this? Typically, I had expect that Folder 1 and Folder 2 would be in the root directory. Why does bdist add the top level directories? Is there any way I can get rid of them (more importantly, should I get rid of them?)
| [
"I think that you want an sdist output .... so try python setup.py sdist\nQuote of Python documentation\n\nAs a simple example, if I run the following command in the Distutils source tree:\n\npython setup.py bdist\n\n\nthen the Distutils builds my module distribution (the Distutils itself in this case), does a “fak... | [
2
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0003483243_distutils_python.txt |
Q:
Finding a function's parameters in Python
I want to be able to ask a class's __init__ method what it's parameters are. The straightforward approach is the following:
cls.__init__.__func__.__code__.co_varnames[:code.co_argcount]
However, that won't work if the class has any decorators. It will give the parameter list for the function returned by the decorator. I want to get down to the original __init__ method and get those original parameters. In the case of a decorator, the decorator function is going to be found in the closure of the function returned by the decorator:
cls.__init__.__func__.__closure__[0]
However, it is more complicated if there are other things in the closure, which decorators may do from time to time:
def Something(test):
def decorator(func):
def newfunc(self):
stuff = test
return func(self)
return newfunc
return decorator
def test():
class Test(object):
@Something(4)
def something(self):
print Test
return Test
test().something.__func__.__closure__
(<cell at 0xb7ce7584: int object at 0x81b208c>, <cell at 0xb7ce7614: function object at 0xb7ce6994>)
And then I have to decide if I want to the parameters from decorator or the parameters from the original function. The function returned by the decorator could have *args and **kwargs for its parameters. What if there are multiple decorators and I have to decide which is the one I care about?
So what is the best way to find a function's parameters even when the function may be decorated? Also, what is the best way to go down a chain of decorators back to the decorated function?
Update:
Here is effectively how I am doing this right now (names have been changed to protect the identity of the accused):
import abc
import collections
IGNORED_PARAMS = ("self",)
DEFAULT_PARAM_MAPPING = {}
DEFAULT_DEFAULT_PARAMS = {}
class DICT_MAPPING_Placeholder(object):
def __get__(self, obj, type):
DICT_MAPPING = {}
for key in type.PARAMS:
DICT_MAPPING[key] = None
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.DICT_MAPPING = DICT_MAPPING
break
return DICT_MAPPING
class PARAM_MAPPING_Placeholder(object):
def __get__(self, obj, type):
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.PARAM_MAPPING = DEFAULT_PARAM_MAPPING
break
return DEFAULT_PARAM_MAPPING
class DEFAULT_PARAMS_Placeholder(object):
def __get__(self, obj, type):
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.DEFAULT_PARAMS = DEFAULT_DEFAULT_PARAMS
break
return DEFAULT_DEFAULT_PARAMS
class PARAMS_Placeholder(object):
def __get__(self, obj, type):
func = type.__init__.__func__
# unwrap decorators here
code = func.__code__
keys = list(code.co_varnames[:code.co_argcount])
for name in IGNORED_PARAMS:
try: keys.remove(name)
except ValueError: pass
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.PARAMS = tuple(keys)
break
return tuple(keys)
class BaseMeta(abc.ABCMeta):
def __init__(self, name, bases, dict):
super(BaseMeta, self).__init__(name, bases, dict)
if "__init__" not in dict:
return
if "PARAMS" not in dict:
self.PARAMS = PARAMS_Placeholder()
if "DEFAULT_PARAMS" not in dict:
self.DEFAULT_PARAMS = DEFAULT_PARAMS_Placeholder()
if "PARAM_MAPPING" not in dict:
self.PARAM_MAPPING = PARAM_MAPPING_Placeholder()
if "DICT_MAPPING" not in dict:
self.DICT_MAPPING = DICT_MAPPING_Placeholder()
class Base(collections.Mapping):
__metaclass__ = BaseMeta
"""
Dict-like class that uses its __init__ params for default keys.
Override PARAMS, DEFAULT_PARAMS, PARAM_MAPPING, and DICT_MAPPING
in the subclass definition to give non-default behavior.
"""
def __init__(self):
pass
def __nonzero__(self):
"""Handle bool casting instead of __len__."""
return True
def __getitem__(self, key):
action = self.DICT_MAPPING[key]
if action is None:
return getattr(self, key)
try:
return action(self)
except AttributeError:
return getattr(self, action)
def __iter__(self):
return iter(self.DICT_MAPPING)
def __len__(self):
return len(self.DICT_MAPPING)
print Base.PARAMS
# ()
print dict(Base())
# {}
At this point Base reports uninteresting values for the four contants and the dict version of instances is empty. However, if you subclass you can override any of the four, or you can include other parameters to the __init__:
class Sub1(Base):
def __init__(self, one, two):
super(Sub1, self).__init__()
self.one = one
self.two = two
Sub1.PARAMS
# ("one", "two")
dict(Sub1(1,2))
# {"one": 1, "two": 2}
class Sub2(Base):
PARAMS = ("first", "second")
def __init__(self, one, two):
super(Sub2, self).__init__()
self.first = one
self.second = two
Sub2.PARAMS
# ("first", "second")
dict(Sub2(1,2))
# {"first": 1, "second": 2}
A:
Consider this decorator:
def rickroll(old_function):
return lambda junk, junk1, junk2: "Never Going To Give You Up"
class Foo(object):
@rickroll
def bar(self, p1, p2):
return p1 * p2
print Foo().bar(1, 2)
In it, the rickroll decorator takes the bar method, discards it, replaces it with a new function that ignores its differently-named (and possibly numbered!) parameters and instead returns a line from a classic song.
There are no further references to the original function, and the garbage collector can come and remove it any time it likes.
In such a case, I cannot see how you could find the parameter names p1 and p2. In my understanding, even the Python interpreter itself has no idea what they used to be called.
| Finding a function's parameters in Python | I want to be able to ask a class's __init__ method what it's parameters are. The straightforward approach is the following:
cls.__init__.__func__.__code__.co_varnames[:code.co_argcount]
However, that won't work if the class has any decorators. It will give the parameter list for the function returned by the decorator. I want to get down to the original __init__ method and get those original parameters. In the case of a decorator, the decorator function is going to be found in the closure of the function returned by the decorator:
cls.__init__.__func__.__closure__[0]
However, it is more complicated if there are other things in the closure, which decorators may do from time to time:
def Something(test):
def decorator(func):
def newfunc(self):
stuff = test
return func(self)
return newfunc
return decorator
def test():
class Test(object):
@Something(4)
def something(self):
print Test
return Test
test().something.__func__.__closure__
(<cell at 0xb7ce7584: int object at 0x81b208c>, <cell at 0xb7ce7614: function object at 0xb7ce6994>)
And then I have to decide if I want to the parameters from decorator or the parameters from the original function. The function returned by the decorator could have *args and **kwargs for its parameters. What if there are multiple decorators and I have to decide which is the one I care about?
So what is the best way to find a function's parameters even when the function may be decorated? Also, what is the best way to go down a chain of decorators back to the decorated function?
Update:
Here is effectively how I am doing this right now (names have been changed to protect the identity of the accused):
import abc
import collections
IGNORED_PARAMS = ("self",)
DEFAULT_PARAM_MAPPING = {}
DEFAULT_DEFAULT_PARAMS = {}
class DICT_MAPPING_Placeholder(object):
def __get__(self, obj, type):
DICT_MAPPING = {}
for key in type.PARAMS:
DICT_MAPPING[key] = None
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.DICT_MAPPING = DICT_MAPPING
break
return DICT_MAPPING
class PARAM_MAPPING_Placeholder(object):
def __get__(self, obj, type):
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.PARAM_MAPPING = DEFAULT_PARAM_MAPPING
break
return DEFAULT_PARAM_MAPPING
class DEFAULT_PARAMS_Placeholder(object):
def __get__(self, obj, type):
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.DEFAULT_PARAMS = DEFAULT_DEFAULT_PARAMS
break
return DEFAULT_DEFAULT_PARAMS
class PARAMS_Placeholder(object):
def __get__(self, obj, type):
func = type.__init__.__func__
# unwrap decorators here
code = func.__code__
keys = list(code.co_varnames[:code.co_argcount])
for name in IGNORED_PARAMS:
try: keys.remove(name)
except ValueError: pass
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.PARAMS = tuple(keys)
break
return tuple(keys)
class BaseMeta(abc.ABCMeta):
def __init__(self, name, bases, dict):
super(BaseMeta, self).__init__(name, bases, dict)
if "__init__" not in dict:
return
if "PARAMS" not in dict:
self.PARAMS = PARAMS_Placeholder()
if "DEFAULT_PARAMS" not in dict:
self.DEFAULT_PARAMS = DEFAULT_PARAMS_Placeholder()
if "PARAM_MAPPING" not in dict:
self.PARAM_MAPPING = PARAM_MAPPING_Placeholder()
if "DICT_MAPPING" not in dict:
self.DICT_MAPPING = DICT_MAPPING_Placeholder()
class Base(collections.Mapping):
__metaclass__ = BaseMeta
"""
Dict-like class that uses its __init__ params for default keys.
Override PARAMS, DEFAULT_PARAMS, PARAM_MAPPING, and DICT_MAPPING
in the subclass definition to give non-default behavior.
"""
def __init__(self):
pass
def __nonzero__(self):
"""Handle bool casting instead of __len__."""
return True
def __getitem__(self, key):
action = self.DICT_MAPPING[key]
if action is None:
return getattr(self, key)
try:
return action(self)
except AttributeError:
return getattr(self, action)
def __iter__(self):
return iter(self.DICT_MAPPING)
def __len__(self):
return len(self.DICT_MAPPING)
print Base.PARAMS
# ()
print dict(Base())
# {}
At this point Base reports uninteresting values for the four contants and the dict version of instances is empty. However, if you subclass you can override any of the four, or you can include other parameters to the __init__:
class Sub1(Base):
def __init__(self, one, two):
super(Sub1, self).__init__()
self.one = one
self.two = two
Sub1.PARAMS
# ("one", "two")
dict(Sub1(1,2))
# {"one": 1, "two": 2}
class Sub2(Base):
PARAMS = ("first", "second")
def __init__(self, one, two):
super(Sub2, self).__init__()
self.first = one
self.second = two
Sub2.PARAMS
# ("first", "second")
dict(Sub2(1,2))
# {"first": 1, "second": 2}
| [
"Consider this decorator:\ndef rickroll(old_function):\n return lambda junk, junk1, junk2: \"Never Going To Give You Up\"\n\nclass Foo(object):\n @rickroll\n def bar(self, p1, p2):\n return p1 * p2\n\nprint Foo().bar(1, 2)\n\nIn it, the rickroll decorator takes the bar method, discards it, replaces ... | [
3
] | [] | [] | [
"closures",
"decorator",
"function",
"python"
] | stackoverflow_0003375573_closures_decorator_function_python.txt |
Q:
Fill a Form on the same page with different classes - write to DB and display values
I have a model with 5 entities and intend to create a form (on the same page) but do not know how to integrate more than one form.
In my main, i can play very well with the forms and write to database, but I need to put more fields on the page.
These fields are of different models.
**
My models:
Teacher, Account(ReferenceProperty), Experience (ReferenceProperty), ServiceDistribution(ReferenceProperty), Experience(ReferenceProperty)
My forms:
class TeacherForm(djangoforms.ModelForm):
class Meta:
model =models.Teacher
exclude = ['user']
and the same for other models
My Main:
class CreateCvHandler(webapp.RequestHandler):
def post(self):
if self.request.get('EscTeacher'):
id = int(self.request.get('EscTeacher'))
teacher=models.teacher.get(db.Key.from_path('Teacher', id))
else:
teacher= models.teacher()
data = forms.TeacherForm(data = self.request.POST)
if data.is_valid():
userList= models.Account.all()
userList.filter('user =', users.get_current_user())
for user in userList:
teacher.user=user.key()
teacher.unity=self.request.get('unity')
teacher.category=self.request.get('category')
teacher.regime=self.request.get('regime')
teacher.put()
self.redirect('/academy')
else:
self.redirect('/createCv')**
Help Please...
A:
If I understood you correctly what you can do is create forms for each model and display them in the template having a single save button. Now when submitted, in your view you can validate each form and add or update the db as required.
Here is a link to an answer to a question similar to what you have asked..
Django: multiple models in one template using forms
| Fill a Form on the same page with different classes - write to DB and display values | I have a model with 5 entities and intend to create a form (on the same page) but do not know how to integrate more than one form.
In my main, i can play very well with the forms and write to database, but I need to put more fields on the page.
These fields are of different models.
**
My models:
Teacher, Account(ReferenceProperty), Experience (ReferenceProperty), ServiceDistribution(ReferenceProperty), Experience(ReferenceProperty)
My forms:
class TeacherForm(djangoforms.ModelForm):
class Meta:
model =models.Teacher
exclude = ['user']
and the same for other models
My Main:
class CreateCvHandler(webapp.RequestHandler):
def post(self):
if self.request.get('EscTeacher'):
id = int(self.request.get('EscTeacher'))
teacher=models.teacher.get(db.Key.from_path('Teacher', id))
else:
teacher= models.teacher()
data = forms.TeacherForm(data = self.request.POST)
if data.is_valid():
userList= models.Account.all()
userList.filter('user =', users.get_current_user())
for user in userList:
teacher.user=user.key()
teacher.unity=self.request.get('unity')
teacher.category=self.request.get('category')
teacher.regime=self.request.get('regime')
teacher.put()
self.redirect('/academy')
else:
self.redirect('/createCv')**
Help Please...
| [
"If I understood you correctly what you can do is create forms for each model and display them in the template having a single save button. Now when submitted, in your view you can validate each form and add or update the db as required.\nHere is a link to an answer to a question similar to what you have asked..\nD... | [
1
] | [] | [] | [
"djangoappengine",
"google_app_engine",
"python"
] | stackoverflow_0003488658_djangoappengine_google_app_engine_python.txt |
Q:
AttributeError: 'file' object has no attribute 'open' in Django while assigning a local file to the FileField
Possible Duplicate:
How to assign a local file to the FileField in Django?
I was trying to assign a file from my disk to the FileField, but I have this error:
AttributeError: 'file' object has no attribute 'open'
My python code:
pdfImage = FileSaver()
myPdfFile = open('mytest.pdf')
pdfImage.myfile.save('new', myPdfFile)
and my models.py
class FileSaver(models.Model):
myfile = models.FileField(upload_to="files/")
class Meta:
managed=False
Thank you in advance for your help
A:
See http://www.nitinh.com/2009/02/django-example-filefield-and-imagefield/. You need to pass save a Django request.
| AttributeError: 'file' object has no attribute 'open' in Django while assigning a local file to the FileField |
Possible Duplicate:
How to assign a local file to the FileField in Django?
I was trying to assign a file from my disk to the FileField, but I have this error:
AttributeError: 'file' object has no attribute 'open'
My python code:
pdfImage = FileSaver()
myPdfFile = open('mytest.pdf')
pdfImage.myfile.save('new', myPdfFile)
and my models.py
class FileSaver(models.Model):
myfile = models.FileField(upload_to="files/")
class Meta:
managed=False
Thank you in advance for your help
| [
"See http://www.nitinh.com/2009/02/django-example-filefield-and-imagefield/. You need to pass save a Django request.\n"
] | [
0
] | [] | [] | [
"django",
"file",
"filefield",
"python"
] | stackoverflow_0003502128_django_file_filefield_python.txt |
Q:
Webservice with Python client
I have a application wrote in Python. Now I must run many instances of this application, but it is one problem. Many instances have one device and access to this device must be synchronised.
I think that the best way to synchronise these instances is to build webservice.
In which language you suggest to write webservice. Python/Django or .NET? How my client can edit data in webservice? I have only found tutorials with read data - not write.
Thanks for responses!
A:
In which language you suggest to write webservice.
Python/Django
How my client can edit data in webservice?
Read about REST. A POST request instead of a GET request is an update.
Use Piston with Django.
| Webservice with Python client | I have a application wrote in Python. Now I must run many instances of this application, but it is one problem. Many instances have one device and access to this device must be synchronised.
I think that the best way to synchronise these instances is to build webservice.
In which language you suggest to write webservice. Python/Django or .NET? How my client can edit data in webservice? I have only found tutorials with read data - not write.
Thanks for responses!
| [
"\nIn which language you suggest to write webservice. \n\nPython/Django\n\nHow my client can edit data in webservice? \n\nRead about REST. A POST request instead of a GET request is an update.\nUse Piston with Django.\n"
] | [
0
] | [] | [] | [
"python",
"webservice_client"
] | stackoverflow_0003501257_python_webservice_client.txt |
Q:
Weird idea: C# - declare a method insinde another method
Okay, in python one can do this:
def foo(monkeys):
def bar(monkey):
#process and return new monkey
processed_monkeys = list()
for monkey in monkeys:
processed_monkeys += bar(monkey)
return processed_monkeys
(This is just a stupid example)
I sometimes miss this functionality of declaring a method inside another method in c#. But today I had the following idea for accomplishing this:
List<Monkey> foo(List<Monkey> monkeys)
{
Func<Monkey, Monkey> bar = delegate(Monkey monkey)
{
//process and return new monkey
}
List<Monkey> processed_monkeys = new List<Monkey>(monkeys.Count);
foreach(Monkey monkey in monkeys)
processed_monkeys.Append(bar(monkey));
return processed_monkeys;
}
Obviously the workaround does not provide exactly the same functionality as the original as the Func or Action Delegates are limited to 4 parameters, but more than 4 parameters are rarely needed...
What are your opinions on this?
Is this evil and should be avoided for all but very special situations?
How is the performance of this? Will a new bar function be created each time the function is called, or will the compiler optimize this somehow?
A:
...as the Func or
Action Delegates are limited to 4
parameters...
Starting with .NET 4.0, these delegate types are defined for up to something like 17 parameters. You can also define your own quite simply for any arbitrary number of parameters; for example, below I define a delegate that takes 5 parameters:
public delegate void Action<T1, T2, T3, T4, T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
What are your opinions on this?
It's totally fine. Believe or not, .NET developers do this all the time.
Is this evil and should be avoided for
all but very special situations?
Nope, it's pretty benign. There's really no harm in it.
How is the performance of this? Will a
new bar function be created each time
the function is called, or will the
compiler optimize this somehow?
The performance is pretty good. The compiler will define an actual full-blown CLR type to provide the anonymous method, just like it defines full-blown CLR types for anonymous types and for methods using the yield keyword. Don't worry; anonymous methods do not incur dynamic compilation on every invocation! Really, that would be pretty absurd, if you think about it.
This isn't even really what I'd call "optimization"; it's simply the way that anonymous methods are implemented by the compiler.
A:
You could use lambda expressions syntax, so the code will be a bit shorter and you won't be limited to 4 arguments.
var bar = (monkey) => { return new Monkey(); }
Imho, it's not evil. The delegate will be definitely compiled once, so the difference in performance between delegate and static method will not be significant.
Of course, just as always, this technique should not be overused to avoid creating unreadable/unmaintanable code.
A:
It's evil when it makes your code harder to read, good when it makes it easier to read, neutral otherwise.
A:
I have used this 'pattern' quite a lot in C# after learning Scheme.
It is very handy to create closures that capture values that can be used as a continuation function (especially when used asynchronously).
A:
I'de consider it good only if the particular sub function will be used only in this function. Otherwise you'll have to repeat it and it becomes evil to me.
| Weird idea: C# - declare a method insinde another method | Okay, in python one can do this:
def foo(monkeys):
def bar(monkey):
#process and return new monkey
processed_monkeys = list()
for monkey in monkeys:
processed_monkeys += bar(monkey)
return processed_monkeys
(This is just a stupid example)
I sometimes miss this functionality of declaring a method inside another method in c#. But today I had the following idea for accomplishing this:
List<Monkey> foo(List<Monkey> monkeys)
{
Func<Monkey, Monkey> bar = delegate(Monkey monkey)
{
//process and return new monkey
}
List<Monkey> processed_monkeys = new List<Monkey>(monkeys.Count);
foreach(Monkey monkey in monkeys)
processed_monkeys.Append(bar(monkey));
return processed_monkeys;
}
Obviously the workaround does not provide exactly the same functionality as the original as the Func or Action Delegates are limited to 4 parameters, but more than 4 parameters are rarely needed...
What are your opinions on this?
Is this evil and should be avoided for all but very special situations?
How is the performance of this? Will a new bar function be created each time the function is called, or will the compiler optimize this somehow?
| [
"\n...as the Func or\n Action Delegates are limited to 4\n parameters...\n\nStarting with .NET 4.0, these delegate types are defined for up to something like 17 parameters. You can also define your own quite simply for any arbitrary number of parameters; for example, below I define a delegate that takes 5 paramet... | [
5,
2,
2,
0,
0
] | [] | [] | [
"anonymous_methods",
"c#",
"methods",
"python"
] | stackoverflow_0003502457_anonymous_methods_c#_methods_python.txt |
Q:
Is it good design to create a module-wide logger in python?
When coding python, I use the logging module a lot.
After some bad experiences and reading articles like this one, I try to prevent import-time executed code wherever possible.
However, for the sake of simplicity, I tend to get my logging object right at the beginning of the module file:
# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger('product.plugin.foo.bar')
This way, my logger is globally accessible and I can just write "logger.error()" anywhere. The alternative is to create it class-wide:
class Bar(object):
logger = logging.getLogger('product.plugin.foo.bar')
However, now I have to type the Class name everytime. To prevent typing the class name, I am tempted to use "self" instead, which will fail in static methods.
def my_method(self):
Bar.logger.error('foo')
def my_method_2(self):
self.logger.error('foo') # ok...
@staticmethod
def my_method_2():
self.logger.error('foo') # boom!
So, at first, it looks like creating the logger object module-wide seems like the right thing to do - still it feels like I could end up in import-related trouble when doing it like this...
A:
It's fine. I even use the same variable name logger. Any logging is better than no logging, but I find it's nice practise to only expose the logger variable, keep the module hidden away so your code only references the logger, and hence the namespace you've designated for the module.
If you later need to refine the namespaces for code within the module, you can use self.logger within those classes, or shadow the global logger where necessary.
Update0
__all__ = [anything but logger]
import logging
logger = logging.getLogger("why.is.this.method.still.java.camel.case")
del logging
Taking note of S.Lott's contribution below. Also note that generally you don't want from x import * anyway.
A:
Damn - I realized it the second after I posted that question, that my "alternative" actually is not any different: the logger is created at import-time as well ;)
Still, I'm interested in your opinions on the best way to handle this issue. Another advantage of the first solution: We have some situations where we have to check on the availability of modules using import statements in try/except blocks. By creating the logger right at the beginning of the file, you can already use it to log this kind of events.
A:
I would create the logger object at the beginning of the module and I would probably even use it in submodules if appropriate.
Anyway, I might still create an additional logging object inside a big class which uses logging a lot if I think it's a good idea - for example when i think it might be useful to configure the logging verbosity or the logging handlers separately for this important class (e.g. an class for ordering processes or for database queries might be such a case).
And you shouldn't worry about that your logging object is accessible outside the module. In fact, Python doesn't support private members at all. I think Guido van Rossum once wrote something like "We are all adults, aren't we?".
| Is it good design to create a module-wide logger in python? | When coding python, I use the logging module a lot.
After some bad experiences and reading articles like this one, I try to prevent import-time executed code wherever possible.
However, for the sake of simplicity, I tend to get my logging object right at the beginning of the module file:
# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger('product.plugin.foo.bar')
This way, my logger is globally accessible and I can just write "logger.error()" anywhere. The alternative is to create it class-wide:
class Bar(object):
logger = logging.getLogger('product.plugin.foo.bar')
However, now I have to type the Class name everytime. To prevent typing the class name, I am tempted to use "self" instead, which will fail in static methods.
def my_method(self):
Bar.logger.error('foo')
def my_method_2(self):
self.logger.error('foo') # ok...
@staticmethod
def my_method_2():
self.logger.error('foo') # boom!
So, at first, it looks like creating the logger object module-wide seems like the right thing to do - still it feels like I could end up in import-related trouble when doing it like this...
| [
"It's fine. I even use the same variable name logger. Any logging is better than no logging, but I find it's nice practise to only expose the logger variable, keep the module hidden away so your code only references the logger, and hence the namespace you've designated for the module.\nIf you later need to refine t... | [
8,
1,
0
] | [] | [] | [
"coding_style",
"import",
"logging",
"python"
] | stackoverflow_0003502558_coding_style_import_logging_python.txt |
Q:
python datetime help
I have a big search field, where users could type in any peice of text and it would search for it.
Now I have a requirement to add in dob to my search. I am not adding a new textbox with a dob picker. I just want users to be able to input a dob in a range of formats and it would figure it out.
IE users can search using any combination of these:
25/08/1970
25-08-1970
1970/08/25
1970-08-25
My program must figure out the dmy for each.
Is there a better way?
def parse(dob):
for d in dob.split(" "):
# find the dob
if len(d) == 10:
# its a dob
if d[0:4].isdigit() # this is the year
year = d[0:4]
month = d[5:7]
day = d[8:10]
elif d[6:10].isdigit() # this is the year
day = d[0:2]
month = d[3:5]
year= d[6:10]
A:
Python-dateutil should make your life much easier.
from dateutil.parser import parse as dparse
for each in ('25/08/1970', '25-08-1970', '1970/08/25', '1970-08-25'):
dparse(each)
dparse(each) will return a datetime.datetime instance. You can pick up the date, month and year from the datetime instance.
Update
As mp0int pointed out, do remember to localize.
A:
Dateutil.parser.parse is a nasty function and must be used carefully, such as
In [16]: parse('2010-05-01')
Out[16]: datetime.datetime(2010, 5, 1, 0, 0)
In [17]: parse('01-05-2010')
Out[17]: datetime.datetime(2010, 1, 5, 0, 0)
Localization is an important matter in date time format.
a = parse('01-05-2010')
a.astimezone(dateutil.tx.tzutc()) # not sure about dateutil.tx.tzutc()
probably this will resolve your problem, but i have not use it and i am not sure witch dateutil.tx function is what you need.
| python datetime help | I have a big search field, where users could type in any peice of text and it would search for it.
Now I have a requirement to add in dob to my search. I am not adding a new textbox with a dob picker. I just want users to be able to input a dob in a range of formats and it would figure it out.
IE users can search using any combination of these:
25/08/1970
25-08-1970
1970/08/25
1970-08-25
My program must figure out the dmy for each.
Is there a better way?
def parse(dob):
for d in dob.split(" "):
# find the dob
if len(d) == 10:
# its a dob
if d[0:4].isdigit() # this is the year
year = d[0:4]
month = d[5:7]
day = d[8:10]
elif d[6:10].isdigit() # this is the year
day = d[0:2]
month = d[3:5]
year= d[6:10]
| [
"Python-dateutil should make your life much easier. \nfrom dateutil.parser import parse as dparse\nfor each in ('25/08/1970', '25-08-1970', '1970/08/25', '1970-08-25'):\n dparse(each)\n\ndparse(each) will return a datetime.datetime instance. You can pick up the date, month and year from the datetime instance.\nU... | [
2,
1
] | [] | [] | [
"date_formatting",
"datetime",
"python"
] | stackoverflow_0003502784_date_formatting_datetime_python.txt |
Q:
Programmatically working with color gradients
I have a python app that uses GIMP gradients to color images. Other than letting the user choose which GIMP gradient to use, the user doesn't have much more control over the coloring. I'm thinking of how to make it easier to let users edit or create color gradients. Are there preexisting tools for working with creating/editing color gradients (preferably using Python)?
A:
You can get some information about creating gradients from Here and it also provides some example code of how to use it.
| Programmatically working with color gradients | I have a python app that uses GIMP gradients to color images. Other than letting the user choose which GIMP gradient to use, the user doesn't have much more control over the coloring. I'm thinking of how to make it easier to let users edit or create color gradients. Are there preexisting tools for working with creating/editing color gradients (preferably using Python)?
| [
"You can get some information about creating gradients from Here and it also provides some example code of how to use it.\n"
] | [
3
] | [] | [] | [
"colors",
"gimp",
"gradient",
"python"
] | stackoverflow_0003503158_colors_gimp_gradient_python.txt |
Q:
how to send EOS message to the bus
ok, I have something like this:
self.pipeline = gst.Pipeline()
self.tee = gst.element_factory_make
self.source = gst.element_factory_make('subdevsrc')
self.source.set_property('viewfinder-mode', 1)
self.source.set_property('camera-device', 1)
self.capsfilter = gst.element_factory_make('capsfilter')
caps = 'video/x-raw-yuv, width=640, height=480'
self.capsfilter.set_property('caps', gst.caps_from_string(caps))
self.tee = gst.element_factory_make('tee')
self.queue1 = gst.element_factory_make('queue')
self.queue2 = gst.element_factory_make('queue')
self.encoder = gst.element_factory_make('dsphdmp4venc')
self.muxer = gst.element_factory_make('mp4mux')
self.imagesink = gst.element_factory_make('xvimagesink')
self.filesink = gst.element_factory_make('filesink')
self.filesink.set_property('location', '/dev/null')
self.pipeline.add(self.source, self.capsfilter, self.tee, self.queue1, self.queue2, self.encoder, self.muxer, self.imagesink, self.filesink)
gst.element_link_many(self.source, self.capsfilter, self.tee, self.queue1, self.imagesink)
gst.element_link_many(self.tee, self.queue2, self.encoder, self.muxer, self.filesink)
self.bus = self.pipeline.get_bus()
I want to stop (EOS) the stream in ready state, change the location and so..
help?
self.bus.emit('eos')
gives me TypeError: : unknown signal name: eos
A:
well I solved it somehow:
I added
self.bus = self.pipeline.get_bus()
self.bus.connect('message::eos', self.on_eos)
self.loop = gobject.MainLoop()
and three methods:
def location(self, filename):
self.ready()
gst.element_unlink_many(self.muxer, self.filesink)
self.filesink.set_state(gst.STATE_NULL)
self.filesink.set_property('location', filename)
self.filesink.set_state(gst.STATE_READY)
gst.element_link_many(self.muxer, self.filesink)
self.run()
if self.pipeline.get_state()[1] != gst.STATE_PLAYING:
self.stop()
def eos(self):
self.bus.add_signal_watch()
self.pipeline.send_event(gst.event_new_eos())
try:
self.loop.run()
except KeyboardInterrupt:
self.on_eos(None,None)
def on_eos(self, bus, msg):
self.loop.quit()
self.bus.remove_signal_watch()
self.location('/dev/null')
| how to send EOS message to the bus | ok, I have something like this:
self.pipeline = gst.Pipeline()
self.tee = gst.element_factory_make
self.source = gst.element_factory_make('subdevsrc')
self.source.set_property('viewfinder-mode', 1)
self.source.set_property('camera-device', 1)
self.capsfilter = gst.element_factory_make('capsfilter')
caps = 'video/x-raw-yuv, width=640, height=480'
self.capsfilter.set_property('caps', gst.caps_from_string(caps))
self.tee = gst.element_factory_make('tee')
self.queue1 = gst.element_factory_make('queue')
self.queue2 = gst.element_factory_make('queue')
self.encoder = gst.element_factory_make('dsphdmp4venc')
self.muxer = gst.element_factory_make('mp4mux')
self.imagesink = gst.element_factory_make('xvimagesink')
self.filesink = gst.element_factory_make('filesink')
self.filesink.set_property('location', '/dev/null')
self.pipeline.add(self.source, self.capsfilter, self.tee, self.queue1, self.queue2, self.encoder, self.muxer, self.imagesink, self.filesink)
gst.element_link_many(self.source, self.capsfilter, self.tee, self.queue1, self.imagesink)
gst.element_link_many(self.tee, self.queue2, self.encoder, self.muxer, self.filesink)
self.bus = self.pipeline.get_bus()
I want to stop (EOS) the stream in ready state, change the location and so..
help?
self.bus.emit('eos')
gives me TypeError: : unknown signal name: eos
| [
"\nwell I solved it somehow:\nI added\nself.bus = self.pipeline.get_bus()\nself.bus.connect('message::eos', self.on_eos)\nself.loop = gobject.MainLoop()\n\nand three methods:\ndef location(self, filename):\n self.ready()\n gst.element_unlink_many(self.muxer, self.filesink)\n self.filesink.set_state(gst.STA... | [
0
] | [] | [] | [
"gstreamer",
"python"
] | stackoverflow_0003495005_gstreamer_python.txt |
Q:
Using Mechanize to submit a form for web-automation - returning an error
for control in form.controls:
if control.type == 'text':
if 'user' in control.name:
control.value = 'blah'
if 'mail' in control.name:
control.value = 'blah'
if control.type == 'password':
if 'pass' in control.name:
control.value = 'blah'
if control.type == 'checkbox':
if 'agree' in control.name:
control.selected = True
if control.type == 'submit':
if 'Submit' in control.name:
control.readonly = False
I fill the form out this way. Then I go to selected the "Agree" checkbox, after doing that I try to use br.submit() to submit the form and send the data. The error I get it:
AttributeError: SubmitControl instance has no attribute 'click'
This is the HTML source of the submit and agree controls:
<input type="submit" name="regSubmit" value="Register" />
<label for="regagree"><input type="checkbox" name="regagree" onclick="checkAgree();" id="regagree" class="check" /> <b>I Agree</b></label>
The HTML source of this particular website has this JavaScript:
function verifyAgree()
{
if (document.forms.creator.passwrd1.value != document.forms.creator.passwrd2.value)
{
alert("The two passwords you entered are not the same!");
return false;
}
if (!document.forms.creator.regagree.checked)
{
alert("Please read and accept the agreement before registering.");
return false;
}
return true;
}
function checkAgree()
{
document.forms.creator.regSubmit.disabled = isEmptyText(document.forms.creator.user) || isEmptyText(document.forms.creator.email) || isEmptyText(document.forms.creator.passwrd1) || !document.forms.creator.regagree.checked;
setTimeout("checkAgree();", 1000);
}
setTimeout("checkAgree();", 1000);
When I type print forms into IDLE, the form is returned as filled and all the proper controls are selected. I can't for the life of me figure out WHY this isn't working. I've been at it for two days.
Help is greatly appreciated.
A:
Why not just submit the form as it is shown in the documentation sample:
br.select_form(name="whatever")
response = br.submit()
Clicking on the submit button is just one way to submit the form; using JavaScript is another. So you don't need to go through the trouble of finding the submit control.
| Using Mechanize to submit a form for web-automation - returning an error | for control in form.controls:
if control.type == 'text':
if 'user' in control.name:
control.value = 'blah'
if 'mail' in control.name:
control.value = 'blah'
if control.type == 'password':
if 'pass' in control.name:
control.value = 'blah'
if control.type == 'checkbox':
if 'agree' in control.name:
control.selected = True
if control.type == 'submit':
if 'Submit' in control.name:
control.readonly = False
I fill the form out this way. Then I go to selected the "Agree" checkbox, after doing that I try to use br.submit() to submit the form and send the data. The error I get it:
AttributeError: SubmitControl instance has no attribute 'click'
This is the HTML source of the submit and agree controls:
<input type="submit" name="regSubmit" value="Register" />
<label for="regagree"><input type="checkbox" name="regagree" onclick="checkAgree();" id="regagree" class="check" /> <b>I Agree</b></label>
The HTML source of this particular website has this JavaScript:
function verifyAgree()
{
if (document.forms.creator.passwrd1.value != document.forms.creator.passwrd2.value)
{
alert("The two passwords you entered are not the same!");
return false;
}
if (!document.forms.creator.regagree.checked)
{
alert("Please read and accept the agreement before registering.");
return false;
}
return true;
}
function checkAgree()
{
document.forms.creator.regSubmit.disabled = isEmptyText(document.forms.creator.user) || isEmptyText(document.forms.creator.email) || isEmptyText(document.forms.creator.passwrd1) || !document.forms.creator.regagree.checked;
setTimeout("checkAgree();", 1000);
}
setTimeout("checkAgree();", 1000);
When I type print forms into IDLE, the form is returned as filled and all the proper controls are selected. I can't for the life of me figure out WHY this isn't working. I've been at it for two days.
Help is greatly appreciated.
| [
"Why not just submit the form as it is shown in the documentation sample:\nbr.select_form(name=\"whatever\")\nresponse = br.submit()\n\nClicking on the submit button is just one way to submit the form; using JavaScript is another. So you don't need to go through the trouble of finding the submit control.\n"
] | [
0
] | [] | [] | [
"form_submit",
"mechanize",
"python"
] | stackoverflow_0003502933_form_submit_mechanize_python.txt |
Q:
What is the difference in Python between a class call and a method call?
Being probably one of the worst OOP programmers on the planet, I've been reading through a lot of example code to help 'get' what a class can be used for. Recently I found this example:
class NextClass: # define class
def printer(self, text): # define method
self.message = text # change instance
print self.message # access instance
x = NextClass() # make instance
x.printer('instance call') # call its method
print x.message # instance changed
NextClass.printer(x, 'class call') # direct class call
print x.message # instance changed again
It doesn't appear there is any difference between what the direct class call does and the instance call does; but it goes against the Zen to include features like that without some use to them. So if there is a difference, what is it? Performance? Overhead reduction? Maybe readability?
A:
There is no difference. instance.method(...) is class.method(instance, ...). But this doesn't go against the Zen, since it says (emphasis mine):
There should be one-- and preferably only one --obvious way to do it.
The second way is possible, and everyone with good knowledge of Python should know that (and why), but it's a nonobvious way of doing that, nobody does it in real code.
So why is it that way? It's just how methods work in any language - a method is some code that operates on an object/instance (and possibly more arguments). Except that usually, the instance is supplied implicitly (e.g. this in C++/Java/D) - but since the Zen says "explicit is better than implicit", self is explicitly a parameter of every method, which inevitable allows this. Explicitly prohibiting it would be pointless.
And apart from that, the fact that methods are not forced to (implicitly) take an instance allows class methods and static methods to be defined without special treatment of the language - the first is just a method that expects a class instead of an instance, and the latter is just a method that doesn't expect an instance at all.
A:
In this situation, there is no difference. In both calls, you are supplying an instance of that class:
x.printer('instance call') # you supplied x and then called its printer method
NextClass.printer(x, 'class call') # you supplied x as a parameter this time
Normally, though, I wouldn't write the second method very often. I usually think of any method that operates on an instance as an instance method. Things like:
car.drive('place')
car.refuel
car.impound
And, I use class methods to operate more generally (I'm struggling to describe this):
Car.numberintheworld # returns the number of cars in the world (or your program)
Here's some more help, for your reading.
A:
This might give you a better clarification.
When an instance attribute is
referenced that isn’t a data
attribute, its class is searched. If
the name denotes a valid class
attribute that is a function object, a
method object is created by packing
(pointers to) the instance object and
the function object just found
together in an abstract object (i.e. this
method object). When the method
object is called with an argument
list, a new argument list is
constructed from the instance object
and the argument list, and the
function object is called with this
new argument list.
| What is the difference in Python between a class call and a method call? | Being probably one of the worst OOP programmers on the planet, I've been reading through a lot of example code to help 'get' what a class can be used for. Recently I found this example:
class NextClass: # define class
def printer(self, text): # define method
self.message = text # change instance
print self.message # access instance
x = NextClass() # make instance
x.printer('instance call') # call its method
print x.message # instance changed
NextClass.printer(x, 'class call') # direct class call
print x.message # instance changed again
It doesn't appear there is any difference between what the direct class call does and the instance call does; but it goes against the Zen to include features like that without some use to them. So if there is a difference, what is it? Performance? Overhead reduction? Maybe readability?
| [
"There is no difference. instance.method(...) is class.method(instance, ...). But this doesn't go against the Zen, since it says (emphasis mine):\n\nThere should be one-- and preferably only one --obvious way to do it.\n\nThe second way is possible, and everyone with good knowledge of Python should know that (and w... | [
2,
1,
0
] | [] | [] | [
"call",
"class",
"instance",
"methods",
"python"
] | stackoverflow_0003503179_call_class_instance_methods_python.txt |
Q:
python html extract tags
How would it be possible to do the following:
Scan through an html page (preferably through a whole domain (www.python.org) and extract all
h1 h2 ...hn Tags
and write all Headings to a file. In the correct order:
Start with h1
Than h2
until we reach the next h1
A:
Use BeautifulSoup or PyQuery.
A:
Given the requirement to scan a whole website, you might want to look into pycurl to grab the files to scrape. Be careful not to hit the site with the equivalent of a DoS attack though.
| python html extract tags | How would it be possible to do the following:
Scan through an html page (preferably through a whole domain (www.python.org) and extract all
h1 h2 ...hn Tags
and write all Headings to a file. In the correct order:
Start with h1
Than h2
until we reach the next h1
| [
"Use BeautifulSoup or PyQuery.\n",
"Given the requirement to scan a whole website, you might want to look into pycurl to grab the files to scrape. Be careful not to hit the site with the equivalent of a DoS attack though.\n"
] | [
2,
1
] | [] | [] | [
"html",
"python"
] | stackoverflow_0003503329_html_python.txt |
Q:
Pipe between current process and other process
I want to make pipe or queue in Python between one process (current) and other existing in system. how can I make it? I know current and other process ID.
I work on Windows 32bit.
A:
Like this.
python one_process.py | python the_other_process.py
Make the OS do the work for you.
In one_process.py, you write to sys.stdout.
In the_other_process.py, you read from sys.stdin.
That's it.
| Pipe between current process and other process | I want to make pipe or queue in Python between one process (current) and other existing in system. how can I make it? I know current and other process ID.
I work on Windows 32bit.
| [
"Like this.\npython one_process.py | python the_other_process.py\n\nMake the OS do the work for you.\nIn one_process.py, you write to sys.stdout.\nIn the_other_process.py, you read from sys.stdin.\nThat's it.\n"
] | [
3
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0003503236_multiprocessing_python.txt |
Q:
Elegant way to extract values from a string parsed with a template
I have a template like this:
foo_tmplte = Template("fieldname_${ln}_${type} = $value")
and a lot of strings parsed with this template like this:
foo_str1 = "fieldname_ru_ln = journal"
foo_str2 = "fieldname_zh_TW_ln = journal"
foo_str3 = "fieldname_uk_ln = номер запису"
Now i want to extract back the variables from the template, for example with str1 the result must be:
ln = ru
type = ln
value = journal
I try some approaches but I can't find any elegant and reusable function to extract the variables.
Any idea?
Thanks in advance
A:
Why don't you use regexps? They have named groups and you can extract them in a dictionary.
Tue Aug 17 14:33:58 $ python
Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
[GCC 4.3.4 20090804 (release) 1] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> foo_template = re.compile(r"^fieldname_(?P<ln>\w+?)_(?P<type>\w+) = (?P<value>.*)$")
>>> m = foo_template.match("fieldname_zh_TW_ln = journal")
>>> m
<_sre.SRE_Match object at 0x7ff34840>
>>> m.groupdict()
{'ln': 'zh', 'type': 'TW_ln', 'value': 'journal'}
>>>
A:
You could use Jinja2, a general-purpose templating library. You'd have to change the string format, though:
"fieldname_{{ ln }}"
| Elegant way to extract values from a string parsed with a template | I have a template like this:
foo_tmplte = Template("fieldname_${ln}_${type} = $value")
and a lot of strings parsed with this template like this:
foo_str1 = "fieldname_ru_ln = journal"
foo_str2 = "fieldname_zh_TW_ln = journal"
foo_str3 = "fieldname_uk_ln = номер запису"
Now i want to extract back the variables from the template, for example with str1 the result must be:
ln = ru
type = ln
value = journal
I try some approaches but I can't find any elegant and reusable function to extract the variables.
Any idea?
Thanks in advance
| [
"Why don't you use regexps? They have named groups and you can extract them in a dictionary.\nTue Aug 17 14:33:58 $ python\nPython 2.6.5 (r265:79063, Jun 12 2010, 17:07:01) \n[GCC 4.3.4 20090804 (release) 1] on cygwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import re \n>... | [
2,
0
] | [] | [] | [
"python",
"templates"
] | stackoverflow_0003502388_python_templates.txt |
Q:
I change Python code, but can't see results
Sorry for totally stupid question, but the situation is that I have to make some changes to the Django website, and I have about zero knowleges in python.
I've been reading Django docs and found out where to make changes, but there is very strange situation. When I change view, template, config or anything on web site - nothing happens.
It looks like code is cached. When I completely delete the site's folder - everithing works fine except css stops working.
The only file that is vital and lays outside the site's folder is starter.py whith code
#!/usr/local/bin/pthon2.3
import sys, os
.... importing some pathes and other conf stuff
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Please can anybody tell my what am I doing wrong?
A:
Python web applications typically differ from PHP ones in that the software is not automatically reloaded once you change the source code. This makes sense because initialization, firing up the interpreter etc., doesn't have to be performed at each instance. It's not that the code is "cached"; it's only loaded once. (Python does cache its bytecode, but this it transparently detects changes, so you needn't worry about that.) So you need to find a means to restart the WSGI program. How this is done in your particular webhosting environment is for you to find out, with the help of the web host or system administrator.
In addition to this, Django does cache its views (if that feature is turned on). You'll need to invalidate the caches in that case.
| I change Python code, but can't see results | Sorry for totally stupid question, but the situation is that I have to make some changes to the Django website, and I have about zero knowleges in python.
I've been reading Django docs and found out where to make changes, but there is very strange situation. When I change view, template, config or anything on web site - nothing happens.
It looks like code is cached. When I completely delete the site's folder - everithing works fine except css stops working.
The only file that is vital and lays outside the site's folder is starter.py whith code
#!/usr/local/bin/pthon2.3
import sys, os
.... importing some pathes and other conf stuff
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Please can anybody tell my what am I doing wrong?
| [
"Python web applications typically differ from PHP ones in that the software is not automatically reloaded once you change the source code. This makes sense because initialization, firing up the interpreter etc., doesn't have to be performed at each instance. It's not that the code is \"cached\"; it's only loaded o... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003503484_django_python.txt |
Q:
Python, With ... as ... AST/Symbol access
Disclaimer: Sensible semantics do dictate that the LHS of as behaving differently depending on the RHS lexeme is ludicrous. But I am curious nontheless.
Hi guys,
Simple question, but one that somone may be able to answer better than my hack. I'm currently messing with metaclasses etc and working out a comfortable syntax for some things.
Given the Python with ... as ...: statement, can I access in the context manager what name(s) are given on the right of as:
with foo('fido') as Dog:
...
Can foo.__enter__() find out the lexeme where Dog is?
Super bonus credit: Keep it implementation agnostic, supporting Python 3.x too.
A:
No, just like (say) in Dog = foo('fido') there is no "serious" way in which foo can know its result is about to be bound to name Dog in the caller. (By "serious" I'm excluding rummaging in the stack to find out the calling bytecode and disassembling it, &c -- basically the stuff that you know you'd never do if you knew your code was going to be maintained by a well-muscled maintainer who knows where you live;-).
| Python, With ... as ... AST/Symbol access |
Disclaimer: Sensible semantics do dictate that the LHS of as behaving differently depending on the RHS lexeme is ludicrous. But I am curious nontheless.
Hi guys,
Simple question, but one that somone may be able to answer better than my hack. I'm currently messing with metaclasses etc and working out a comfortable syntax for some things.
Given the Python with ... as ...: statement, can I access in the context manager what name(s) are given on the right of as:
with foo('fido') as Dog:
...
Can foo.__enter__() find out the lexeme where Dog is?
Super bonus credit: Keep it implementation agnostic, supporting Python 3.x too.
| [
"No, just like (say) in Dog = foo('fido') there is no \"serious\" way in which foo can know its result is about to be bound to name Dog in the caller. (By \"serious\" I'm excluding rummaging in the stack to find out the calling bytecode and disassembling it, &c -- basically the stuff that you know you'd never do i... | [
1
] | [] | [] | [
"python",
"python_2.6",
"python_3.x"
] | stackoverflow_0003503753_python_python_2.6_python_3.x.txt |
Q:
Getting started with Pylons
I am just starting to use a web framework. I have decided I really like python and started looking at web frameworks. I don't really like django for a few reasons, but from what I have tried so far I found I really like pylons.
The problem I have is that I can't find that many articles/tutorials about pylons, especially 1.0 articles. Does anybody know any good getting started tutorials and articles about pylons?
Also, I am gonna need to implement users in my applications with a secure log in and have the users "own" a model. Any good advice/articles/tutorials about how I would do this?
When I was looking at some tutorial they mention virtual python environments. I don't really know what that is, why you would use them and how do you use them. Any help?
Finally, I can't find any good tutorials/articles about how to deploy pylons to a production environment. I own a VPS and am gonna deploy there. Any help with that?
Is there anything else I should know about pylons or python. I know the basics of python already.
A:
The book suggested by meder (http://pylonsbook.com/en/1.1/) is a very good start. I upvoted his anwser because that's where I learned Pylons.
However, the book is written for Pylons 0.9.7 (the latest version before 0.10 and 1.0).
Pylons is the agglomeration of several high quality libraries. Learning Pylons is all about learning those libraries. Most of the book is about exploring those libraries. When you learn to develop web app in Pylons, what you really learn is to develop app in Python.
Right now, I think the book and the official website (http://pylonshq.com/docs/en/1.0/) are the two most valuable resources to learn Pylons.
Most of the changes that happenned between 0.9.7 and 1.0 are in the app start-up (which you probably won't really try to modify at the begining). Other than that, the libraries have been updated (sqlalchemy is now 0.6, etc.). Also, one change that may affect you: the url_to and redirect_to functions have been replaced by url and redirect. That's about it.
A:
There is an entire book published free which covers Pylons 1.0:
http://pylonsbook.com/en/1.1/
A:
You will definitely need to learn SQLAlchemy to master Pylons.
Official docs are pretty good start at it, http://www.sqlalchemy.org/docs/, and you may want to try Elixir extension, which provides a bit better declarative syntax.
You also should read docs on Routes module, http://routes.groovie.org/contents.html, especially on submappers and RESTful services, http://routes.groovie.org/restful.html
And you need to learn w/e templating system you choose. Mako, for example, have some non-obvious caveats, like much better performance of <%namespace/> vs <%include/>.
A:
For authentication the homegrown decorator based approach works well also: http://wiki.pylonshq.com/display/pylonscookbook/Another+approach+for+authorization+in+pylons+%28decorator+based%2C+repoze.what+like%29
| Getting started with Pylons | I am just starting to use a web framework. I have decided I really like python and started looking at web frameworks. I don't really like django for a few reasons, but from what I have tried so far I found I really like pylons.
The problem I have is that I can't find that many articles/tutorials about pylons, especially 1.0 articles. Does anybody know any good getting started tutorials and articles about pylons?
Also, I am gonna need to implement users in my applications with a secure log in and have the users "own" a model. Any good advice/articles/tutorials about how I would do this?
When I was looking at some tutorial they mention virtual python environments. I don't really know what that is, why you would use them and how do you use them. Any help?
Finally, I can't find any good tutorials/articles about how to deploy pylons to a production environment. I own a VPS and am gonna deploy there. Any help with that?
Is there anything else I should know about pylons or python. I know the basics of python already.
| [
"The book suggested by meder (http://pylonsbook.com/en/1.1/) is a very good start. I upvoted his anwser because that's where I learned Pylons.\nHowever, the book is written for Pylons 0.9.7 (the latest version before 0.10 and 1.0).\nPylons is the agglomeration of several high quality libraries. Learning Pylons is a... | [
10,
6,
2,
1
] | [] | [] | [
"authentication",
"pylons",
"python"
] | stackoverflow_0003428795_authentication_pylons_python.txt |
Q:
Importing python variables of a program after its execution
I've written two python scripts script1.py and script2.py. I want to run script1.py from script2.py and get the content of the variables of script1 created during the execution of script1. Script1 has several functions in which the variables are created including in the main.
Thank you for all your answers. I've examined your answers and it doesn't seem to work.
Here are the guilty scripts I'm talking about :
script1.py
def main(argv):
"""Main of script 1
Due to the internal structure of the script this
main function must always be called with the flag -d
and a corresponding argument.
"""
global now
now = datetime.datetime.now()
global vroot_directory
vroot_directory = commands.getoutput("pwd")
global testcase_list_file
testcase_list_file = 'no_argument'
try:
opts, args = getopt.getopt(argv, "d:t:",
["directory_path=", "testcase_list="])
except getopt.GetoptError, err:
print command_syntax
sys.exit()
for opt, arg in opts:
if opt in ("-d", "--directory"):
vroot_directory = arg
if opt in ("-t", "--testcase"):
testcase_list_file = arg
def function1():
pass
def function2():
if testcase_list_file == 'no_argument':
function1()
else:
function2()
if __name__ == "__main__":
main(sys.argv[1:])
script2.py
from Tkinter import *
class Application:
def __init__(self):
""" main window constructor """
self.root = Tk()
# I'd like to import here the variables of script1.py
self.root.title(script1.vroot_directory) ?
self.root.mainloop()
# Main program
f = Application()
Sorry for my mistakes and thank you for your pertinent remarks. I've got the following error message :
" AttributeError: 'module' object has no attribute 'vroot_directory' "
To be more specific I'd like to have something similar to the following :
from Tkinter import *
import script1
class Application:
def __init__(self):
""" main window constructor """
self.root = Tk()
script1.main(-d directory -t testcase_list_file) # to launch script1
self.root.title(script1.vroot_directory) # and after use its variables and functions
self.root.mainloop()
# Main program
f = Application()
A:
From script2 do
import script1
This will run any code inside script1; any global variables will be available as e.g. script1.result_of_calculation. You can set global variables as below.
script1:
from time import sleep
def main( ):
global result
sleep( 1 ) # Big calculation here
result = 3
script2:
import script1
script1.main( ) # ...
script1.result # 3
Note that it would be nicer to make main() in script1 return result, so that you could do
import script1
result = script1.main( )
This better encapsulates the flow of data, and is generally more Pythonic. It also avoids global variables, which are generally a Bad Thing.
A:
There are two possibilities: First, merge them into a single script. This could look something like (in script2.py)
import script1
...
script1.dostuff()
importantvar = script1.importantvar
doScript2Stuff(importantvar)
Without knowing your application, however, I'd advise encapsulating whatever script1 does into a function such that you can simply call
(var1, var2, var3) = script1.dostuffAndReturnVariables()
since it's always good to avoid global variables. Also, it may turn out handy later on if the stuff in script1 isn't executed in the moment you import it (as it is done if you write all the commands directly on the main level), but when you want it, by calling a function. Otherwise things may get messy once you get more modules and you may find yourself rearranging import commands because they do so much stuff.
Second possibility, if, for some reason, they need to be run separately, would be to use pickle.
Write
output = open(picklefile, "w")
pickle.dump(vars, output)
output.close()
in script1.py
and then
inputfile = open(picklefile, "r")
vars = pickle.load(inputfile)
input.close()
in script2.py. This way, you save the contents of your var in a file and can revive them from there when needed.
However, I'd prefer the first approach unless there's a really good reason for the two not to be run together, as it improves the structure of your code.
A:
Python is an interpreted language, so when you simply import a script within another script (e.g. by writing import script1 inside script2) then the interpreter will load the second script and execute it step by step. Each function definition will result in a callable function object and so on, and each expression will be simply executed.
After that, you can access everything from the module with script1.globalvar1 and so on.
A:
I think what you are looking for is some form of object persistence. I personally use the shelve module for this:
Script 1:
import shelve
def main(argv):
"""Main of script 1
Due to the internal structure of the script this
main function must always be called with the flag -d
and a corresponding argument.
"""
settings = shelve.open('mySettings')
global now
now = datetime.datetime.now()
settings['vroot_directory'] = commands.getoutput("pwd")
settings['testcase_list_file'] = 'no_argument'
try:
opts, args = getopt.getopt(argv, "d:t:",
["directory_path=", "testcase_list="])
except getopt.GetoptError, err:
print command_syntax
sys.exit()
for opt, arg in opts:
if opt in ("-d", "--directory"):
settings['vroot_directory'] = arg
if opt in ("-t", "--testcase"):
settings['testcase_list_file'] = arg
def function1():
pass
def function2():
if testcase_list_file == 'no_argument':
function1()
else:
function2()
if __name__ == "__main__":
main(sys.argv[1:])
Script 2:
from Tkinter import *
import shelve
class Application:
def __init__(self):
settings = shelve.open('mySettings')
""" main window constructor """
self.root = Tk()
# I'd like to import here the variables of script1.py
self.root.title(settings['vroot_directory']) ?
self.root.mainloop()
# Main program
f = Application()
The shelve module uses the pickle module in its implementation, so you could also look at pickle module for another approach.
| Importing python variables of a program after its execution | I've written two python scripts script1.py and script2.py. I want to run script1.py from script2.py and get the content of the variables of script1 created during the execution of script1. Script1 has several functions in which the variables are created including in the main.
Thank you for all your answers. I've examined your answers and it doesn't seem to work.
Here are the guilty scripts I'm talking about :
script1.py
def main(argv):
"""Main of script 1
Due to the internal structure of the script this
main function must always be called with the flag -d
and a corresponding argument.
"""
global now
now = datetime.datetime.now()
global vroot_directory
vroot_directory = commands.getoutput("pwd")
global testcase_list_file
testcase_list_file = 'no_argument'
try:
opts, args = getopt.getopt(argv, "d:t:",
["directory_path=", "testcase_list="])
except getopt.GetoptError, err:
print command_syntax
sys.exit()
for opt, arg in opts:
if opt in ("-d", "--directory"):
vroot_directory = arg
if opt in ("-t", "--testcase"):
testcase_list_file = arg
def function1():
pass
def function2():
if testcase_list_file == 'no_argument':
function1()
else:
function2()
if __name__ == "__main__":
main(sys.argv[1:])
script2.py
from Tkinter import *
class Application:
def __init__(self):
""" main window constructor """
self.root = Tk()
# I'd like to import here the variables of script1.py
self.root.title(script1.vroot_directory) ?
self.root.mainloop()
# Main program
f = Application()
Sorry for my mistakes and thank you for your pertinent remarks. I've got the following error message :
" AttributeError: 'module' object has no attribute 'vroot_directory' "
To be more specific I'd like to have something similar to the following :
from Tkinter import *
import script1
class Application:
def __init__(self):
""" main window constructor """
self.root = Tk()
script1.main(-d directory -t testcase_list_file) # to launch script1
self.root.title(script1.vroot_directory) # and after use its variables and functions
self.root.mainloop()
# Main program
f = Application()
| [
"From script2 do\nimport script1\n\nThis will run any code inside script1; any global variables will be available as e.g. script1.result_of_calculation. You can set global variables as below.\n\nscript1:\nfrom time import sleep\ndef main( ):\n global result\n sleep( 1 ) # Big calculation here\n result = 3\... | [
4,
0,
0,
0
] | [
"Depending on how many variables you want to pass to script2.py you could pass them via arguments and pick them up as an argv array. You could run script1.py then from this script run os.system('script2.py arg0 arg1 arg2 arg3') to call script2.py.\nThen you can pick up your variables in you script2.py by doing this... | [
-2
] | [
"import",
"program_entry_point",
"python",
"variables"
] | stackoverflow_0003500957_import_program_entry_point_python_variables.txt |
Q:
SQLCLR & IronPython
Im feeling crazy and I've decided I would really like to write a User-Defined Function in Python that would run in SQL Server 2008. I am interested in doing this as I have a few thousand lines of PL/Python functions written for PostgreSQL and I am interested to know if I can get the project running on SQL Server instead.
I am looking at IronPython for the first time trying to work out if I can convert something like this C#...
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Function1()
{
// Put your code here
return new SqlString("Hello");
}
};
... into Python.
Has anyone got any ideas on this one? Is it possible?
The bit I am particularly perplexed by is the annotation:
[Microsoft.SqlServer.Server.SqlFunction]
How do I write that in Python? Looks a bit like a decorator :)
All suggestions welcome.
Cheers,
Tom
A:
According to this article you're wasting your time trying. Apparently you simply can't use dynamic languages in SQL CLR even in UNSAFE assemblies.
| SQLCLR & IronPython | Im feeling crazy and I've decided I would really like to write a User-Defined Function in Python that would run in SQL Server 2008. I am interested in doing this as I have a few thousand lines of PL/Python functions written for PostgreSQL and I am interested to know if I can get the project running on SQL Server instead.
I am looking at IronPython for the first time trying to work out if I can convert something like this C#...
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Function1()
{
// Put your code here
return new SqlString("Hello");
}
};
... into Python.
Has anyone got any ideas on this one? Is it possible?
The bit I am particularly perplexed by is the annotation:
[Microsoft.SqlServer.Server.SqlFunction]
How do I write that in Python? Looks a bit like a decorator :)
All suggestions welcome.
Cheers,
Tom
| [
"According to this article you're wasting your time trying. Apparently you simply can't use dynamic languages in SQL CLR even in UNSAFE assemblies.\n"
] | [
2
] | [] | [] | [
"ironpython",
"python",
"sql_server",
"sqlclr"
] | stackoverflow_0003503996_ironpython_python_sql_server_sqlclr.txt |
Q:
When java program is started using Python's subprocess.Popen() exits, why database connection opened by the subprocess is not closed?
We use Robot Framework for test automation, and our jython test code spawns a java subprocess using subprocess.Popen():
cmd = "java -jar program.jar"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
process.wait()
Java code utilizes a JDBC connection to Oracle database, and the same program needs to be executed several times successively.
Our issue is, that after the java program exits the database connection to Oracle is not closed - and after several executions the tests start to fail because Oracle won't accept more connections.
netstat shows, that the stale TCP connections to Oracle are owned by jython's PID (=parent process).
Why aren't the connections closed when the java program (=subprocess) exits?
A:
I'm not sure but it's possible that because you're using Jython, the interpreter is given ownership of the connections (and hence they survive until that process dies). Have you tried using process.terminate() after the process.wait()?
A:
Consider using os.kill (which is used by process.terminate in >= 2.6).
If that doesn't work, given your unusual setup - JVMs invoking JVMs, not usually necessary - you may want to use something like execnet (http://codespeak.net/execnet/) to start a CPython process to control this. CPython has more functionality for accessing host operating system services than what we have provided in Jython. Using execnet is a good way to combine these strengths together.
| When java program is started using Python's subprocess.Popen() exits, why database connection opened by the subprocess is not closed? | We use Robot Framework for test automation, and our jython test code spawns a java subprocess using subprocess.Popen():
cmd = "java -jar program.jar"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
process.wait()
Java code utilizes a JDBC connection to Oracle database, and the same program needs to be executed several times successively.
Our issue is, that after the java program exits the database connection to Oracle is not closed - and after several executions the tests start to fail because Oracle won't accept more connections.
netstat shows, that the stale TCP connections to Oracle are owned by jython's PID (=parent process).
Why aren't the connections closed when the java program (=subprocess) exits?
| [
"I'm not sure but it's possible that because you're using Jython, the interpreter is given ownership of the connections (and hence they survive until that process dies). Have you tried using process.terminate() after the process.wait()?\n",
"Consider using os.kill (which is used by process.terminate in >= 2.6).\n... | [
2,
1
] | [] | [] | [
"java",
"jython",
"python"
] | stackoverflow_0003477440_java_jython_python.txt |
Q:
Help On Python program that can use to compile python coding into a standalone .exe file
I am currently working on a python program with the use of wxpython to make out a gui application. However, i wish to compile my application to be like a standalone application where people can just get the .exe file and run it without installing python and wxpython. I am not sure if it is possible, thus i hope that someone can give me some guidance on this. Also, if it is possible, please tell me what program should i use to accomplish that.
Thanks
A:
You need to create a frozen binary. You can use py2exe for this purpose.
For what it's worth, if you ever need to make executables on a unix system, you can use Freeze, a utility that comes with Python.
A:
For a nice cross-platform solution, I always recommend pyinstaller (actually, I find it better than py2exe even just for making a Windows-only executable -- it can do code signing, can seamlessly incorporate "big, hairy" libraries such as PyQt, etc;-).
| Help On Python program that can use to compile python coding into a standalone .exe file | I am currently working on a python program with the use of wxpython to make out a gui application. However, i wish to compile my application to be like a standalone application where people can just get the .exe file and run it without installing python and wxpython. I am not sure if it is possible, thus i hope that someone can give me some guidance on this. Also, if it is possible, please tell me what program should i use to accomplish that.
Thanks
| [
"You need to create a frozen binary. You can use py2exe for this purpose.\nFor what it's worth, if you ever need to make executables on a unix system, you can use Freeze, a utility that comes with Python.\n",
"For a nice cross-platform solution, I always recommend pyinstaller (actually, I find it better than py2e... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003503988_python.txt |
Q:
Problem with inheritance and "self" reference
This is my first post, so first of all I want to say a giant "Thank you!" to the community of stackoverflow for all the time an answer did the trick for me :)
I have a problem while dealing with python's inheritance.
I have a parent class which contains the following code:
def start(self):
pid = os.fork()
if (pid==0):
self.__do_in_forked_process()
elif(pid > 0):
self.__do_in_parent_process()
else:
print ("Error while forking...")
sys.exit(1)
The __do_in_forked_process() method contains a method self.__manage_request() which is defined in the parent class and overridden in the child class.
In the child class, when I use use the method self.start() the problem arise: the self.__manage_request() method executed is the one defined in the parent class instead of the method define in the child class (even if, I suppose, when I do self.start() the start method and all the things inside it should refer to the child object instead of to the parent object).
Thanks in advance!
turkishweb
A:
Don't use TWO leading underscores in your method and other attribute names: they're specifically intended to isolate parent classes from subclasses, which is most definitely what you do not want here! Rename the method in question to _manage_request (single leading underscore) throughout, and live happily ever after. And in the future use double leading underscores only when you're absolutely certain you never want any override (or acess from subclass methods) of that attribute (method being just a special case of attribute).
In C++ terminology, single leading underscore means protected: subclasses are allowed and welcome to access and override. Double leading underscores mean private: meant to be hands-off even for subclasses (and with some compiler name mangling to help it be so). Rarely have I seem double leading underscores used with clear purpose and understanding of this.
| Problem with inheritance and "self" reference | This is my first post, so first of all I want to say a giant "Thank you!" to the community of stackoverflow for all the time an answer did the trick for me :)
I have a problem while dealing with python's inheritance.
I have a parent class which contains the following code:
def start(self):
pid = os.fork()
if (pid==0):
self.__do_in_forked_process()
elif(pid > 0):
self.__do_in_parent_process()
else:
print ("Error while forking...")
sys.exit(1)
The __do_in_forked_process() method contains a method self.__manage_request() which is defined in the parent class and overridden in the child class.
In the child class, when I use use the method self.start() the problem arise: the self.__manage_request() method executed is the one defined in the parent class instead of the method define in the child class (even if, I suppose, when I do self.start() the start method and all the things inside it should refer to the child object instead of to the parent object).
Thanks in advance!
turkishweb
| [
"Don't use TWO leading underscores in your method and other attribute names: they're specifically intended to isolate parent classes from subclasses, which is most definitely what you do not want here! Rename the method in question to _manage_request (single leading underscore) throughout, and live happily ever af... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0003504136_python.txt |
Q:
How to best organize the rules component of a Django system?
I'm designing (and ultimately writing) a system in Django that consists of two major components:
A Game Manager: this is essentially a data-entry piece. Trusted (non-public) users will enter information on a gaming system, such as options that a player may have. The interface for this is solely the Django admin console, and it doesn't "do" anything except hold the information.
A Character Manager: this is the consumer of the above data. Public users will create characters in the role-playing systems defined above, pulling from the options entered by those trusted users. This is a separate app in the project from Django's standpoint.
There's one piece I'm not sure where to put, however, and that is the "rules" that are associated with each game. Essentially, for each game put into the first app, there are a sets of prerequisites, limitations, and other business logic specific to that game. (There's also similarly-structured logic that will be common to all games.) The logic is going to be coded in Python, rather than user-entered.
That logic is used in the process of validating a particular character, but is associated with a particular game and will need to be swapped out dynamically. Is it a separate app, or should it be validation tied to the forms of the Character Manager? Or can it be both?
This is the first Django app I've built from scratch (rather than chewing on someone else's code), and I'm new to the Python philosophy to boot, so I'm all ears on this.
Thanks in advance.
A:
I would create subdirectory named rules in the app with game logic and there create module named after each game, that you would like serve. Then create a common interface for those modules, that will be utilized by your games and import proper rules module by name (if your game is called adom, then simply __import__('rules.adom') inside the main game engine and call game specific methods.
If your games don't create own models and views, then there seems to be no reason to create specific app for each of them. This is a delicate matter, because code used is based on data stored in the database. Didn't you think about storing additional gaming scripts inside the database to and then exec them? This seems more natural: a game is set of data and additional scripts associated with that game.
A:
the "rules" that are associated with each game.
for each game put into the first app, there are a sets of prerequisites, limitations, and other business logic specific to that game.
That's part of the game app, then.
There's also similarly-structured logic that will be common to all games.
That's part of the game app, then.
That logic is used in the process of validating a particular character, but is associated with a particular game.
Correct. That's part of the game app, then. Characters are associated with one or more games.
should it be validation tied to the forms of the Character Manager?
The Character Forms can have data cleansing rules which depend on a Game.
| How to best organize the rules component of a Django system? | I'm designing (and ultimately writing) a system in Django that consists of two major components:
A Game Manager: this is essentially a data-entry piece. Trusted (non-public) users will enter information on a gaming system, such as options that a player may have. The interface for this is solely the Django admin console, and it doesn't "do" anything except hold the information.
A Character Manager: this is the consumer of the above data. Public users will create characters in the role-playing systems defined above, pulling from the options entered by those trusted users. This is a separate app in the project from Django's standpoint.
There's one piece I'm not sure where to put, however, and that is the "rules" that are associated with each game. Essentially, for each game put into the first app, there are a sets of prerequisites, limitations, and other business logic specific to that game. (There's also similarly-structured logic that will be common to all games.) The logic is going to be coded in Python, rather than user-entered.
That logic is used in the process of validating a particular character, but is associated with a particular game and will need to be swapped out dynamically. Is it a separate app, or should it be validation tied to the forms of the Character Manager? Or can it be both?
This is the first Django app I've built from scratch (rather than chewing on someone else's code), and I'm new to the Python philosophy to boot, so I'm all ears on this.
Thanks in advance.
| [
"I would create subdirectory named rules in the app with game logic and there create module named after each game, that you would like serve. Then create a common interface for those modules, that will be utilized by your games and import proper rules module by name (if your game is called adom, then simply __impor... | [
1,
1
] | [] | [] | [
"architecture",
"code_organization",
"django",
"python"
] | stackoverflow_0003504405_architecture_code_organization_django_python.txt |
Q:
Reinstalling python on Mac OS 10.6 with a different gcc version
I am trying to install a Python package that requires running gcc 4.2. My gcc is pointing correctly to gcc-4.2, i.e.
$ gcc -v
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5664~38/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5664)
However, my python is built using gcc 4.0, i.e.
$ python
Python 2.5.4 (r254:67917, Dec 23 2008, 15:47:06)
[GCC 4.0.1 (Apple Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Is there any way I can re-build Python on GCC 4.2 without having to reinstall all my Python packages?
My operating system is Mac OS 10.6.
NOTE: It will not help me to just point gcc to gcc-4.0 -- I need to use gcc-4.2.
A:
On current OS X Pythons, Distutils tries to ensure that C extension modules are built using the same GCC and MACOSX_DEPLOYMENT_TARGET (ABI) as the Python interpreter itself was. This ensures that there won't be conflicts with the underlying system libraries.
But if you are on OS X 10.6, then the Python version you show is not one of the Apple-supplied Pythons, both of which are built with gcc-4.2. Chances are you have an older python.org 2.5 also installed with symlinks into /usr/local/bin.
# OS X 10.6.4
$ /usr/bin/python -c 'import sys;print(sys.version)'
2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)]
$ /usr/bin/python2.6 -c 'import sys;print(sys.version)' # same as above
2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)]
$ /usr/bin/python2.5 -c 'import sys;print(sys.version)'
2.5.4 (r254:67916, Feb 11 2010, 00:50:55)
[GCC 4.2.1 (Apple Inc. build 5646)]
$ /usr/local/bin/python2.5 -c 'import sys;print(sys.version);print(sys.executable)'
2.5.4 (r254:67917, Dec 23 2008, 14:57:27)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)]
/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python
which python will tell you which Python is being invoked. Either use an absolute path to the interpreter you want or change your shell PATH or remove the old Python 2.5.
A:
This is most likely an issue with distutils, you shouldn't need to recompile python, or reinstall any packages.
Have you checked to see what version your CC environment variable is set to? It may very well still be set to 4.0. You can try:
export CC=gcc-4.2
python setup.py build
You could also take a look at:
/Library/Frameworks/Python.framework/Versions/Current/lib/python2.5/config/Makefile
Which is where distutils gets its build settings from.
| Reinstalling python on Mac OS 10.6 with a different gcc version | I am trying to install a Python package that requires running gcc 4.2. My gcc is pointing correctly to gcc-4.2, i.e.
$ gcc -v
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5664~38/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5664)
However, my python is built using gcc 4.0, i.e.
$ python
Python 2.5.4 (r254:67917, Dec 23 2008, 15:47:06)
[GCC 4.0.1 (Apple Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Is there any way I can re-build Python on GCC 4.2 without having to reinstall all my Python packages?
My operating system is Mac OS 10.6.
NOTE: It will not help me to just point gcc to gcc-4.0 -- I need to use gcc-4.2.
| [
"On current OS X Pythons, Distutils tries to ensure that C extension modules are built using the same GCC and MACOSX_DEPLOYMENT_TARGET (ABI) as the Python interpreter itself was. This ensures that there won't be conflicts with the underlying system libraries.\nBut if you are on OS X 10.6, then the Python version y... | [
3,
1
] | [] | [] | [
"gcc",
"python"
] | stackoverflow_0003500638_gcc_python.txt |
Q:
Using web2py on Eclipse
I am trying to use the steps I found on the net to make web2py work on Eclipse, but I must have something setup wrong because Eclipse gives me error on the imports.
For instance the instructions say to do this at the top of controllers:
if 0:
from gluon.globals import *
from gluon.html import *
from gluon.http import *
from gluon.tools import *
from gluon.sql import *
from gluon.validators import *
from gluon.languages import translator as T
from gluon.sqlhtml import SQLFORM, SQLTABLE, form_factory
session = Session()
request = Request()
response = Response()
crud = Crud()
db = DAL(‘sqlite://storage.sqlite’)
auth=Auth(globals(),None)
Eclipse says T is an unresolved import. If I change it to translator (instead of translator as T) it says translator is in unresolved import.
Also it says SQLFORM, SQLTable, form_factory, Session(), Request(), Response etc, are unresolved imports? Any ideas what I am doing wrong before I switch to Django.
A:
Do these steps first.
Then do what I have above. Urghhh
| Using web2py on Eclipse | I am trying to use the steps I found on the net to make web2py work on Eclipse, but I must have something setup wrong because Eclipse gives me error on the imports.
For instance the instructions say to do this at the top of controllers:
if 0:
from gluon.globals import *
from gluon.html import *
from gluon.http import *
from gluon.tools import *
from gluon.sql import *
from gluon.validators import *
from gluon.languages import translator as T
from gluon.sqlhtml import SQLFORM, SQLTABLE, form_factory
session = Session()
request = Request()
response = Response()
crud = Crud()
db = DAL(‘sqlite://storage.sqlite’)
auth=Auth(globals(),None)
Eclipse says T is an unresolved import. If I change it to translator (instead of translator as T) it says translator is in unresolved import.
Also it says SQLFORM, SQLTable, form_factory, Session(), Request(), Response etc, are unresolved imports? Any ideas what I am doing wrong before I switch to Django.
| [
"Do these steps first.\nThen do what I have above. Urghhh\n"
] | [
1
] | [] | [] | [
"eclipse",
"python",
"web2py"
] | stackoverflow_0003467546_eclipse_python_web2py.txt |
Q:
python beautifulsoup adding extra end tags
I'm using Beautifulsoup to parse a website
request = urllib2.Request(url)
response = urllib2.urlopen(request)
soup = BeautifulSoup.BeautifulSoup(response)
I am using it to traverse a table. The problem I am running into is that BS is adding an extra end tag for the table into the html which doesn't exist, which I verified with: print soup.prettify(). So, one of the td tags is getting left out of the table and I can't select it.
A:
How about searching directly for each tag instead of trying to traverse into the table?
for td in soup.find("td"):
...
its not unusual to find the tbody tag nested within a table automatically when its not in the code. Either you can code for it or just jump straight to the tr or td tag.
| python beautifulsoup adding extra end tags | I'm using Beautifulsoup to parse a website
request = urllib2.Request(url)
response = urllib2.urlopen(request)
soup = BeautifulSoup.BeautifulSoup(response)
I am using it to traverse a table. The problem I am running into is that BS is adding an extra end tag for the table into the html which doesn't exist, which I verified with: print soup.prettify(). So, one of the td tags is getting left out of the table and I can't select it.
| [
"How about searching directly for each tag instead of trying to traverse into the table?\n for td in soup.find(\"td\"):\n ...\n\nits not unusual to find the tbody tag nested within a table automatically when its not in the code. Either you can code for it or just jump straight to the tr or td tag.\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python"
] | stackoverflow_0003505003_beautifulsoup_html_parsing_python.txt |
Q:
best way to parse a language that's ALMOST Python?
I'm working on a domain-specific language implemented on top of Python. The grammar is so close to Python's that until now we've just been making a few trivial string transformations and then feeding it into ast. For example, indentation is replaced by #endfor/#endwhile/#endif statements, so we normalize the indentation while it's still a string.
I'm wondering if there's a better way? As far as I can tell, ast is hardcoded to parse the Python grammar and I can't really find any documentation other than http://docs.python.org/library/ast.html#module-ast (and the source itself, I suppose).
Does anyone have personal experience with PyParsing, ANTLR, or PLY?
There are vague plans to rewrite the interpreter into something that transforms our language into valid Python and feeds that into the Python interpreter itself, so I'd like something compatible with compile, but this isn't a deal breaker.
Update: It just occurred to me that
from __future__ import print_function, with_statement
changes the way Python parses the following source. However, PEP 236 suggests that this is syntactic window dressing for a compiler feature. Could someone confirm that trying to override/extend __future__ is not the correct solution to my problem?
A:
PLY works. It's odd because it mimics lex/yacc in a way that's not terribly pythonic.
Both lex and yacc have an implicit interface that makes it possible to run the output from lex as a stand-alone program. This "feature" is carefully preserved. Similarly for the yacc-like features of PLY. The "feature" to create a weird, implicit stand-alone main program is carefully preserved.
However, PLY as lex/yacc-compatible toolset is quite nice. All your lex/yacc skills are preserved.
[Editorial Comment. "Fixing" Python's grammar will probably be a waste of time. Almost everyone can indent correctly without any help. Check C, Java, C++ and even Pascal code, and you'll see that almost everyone can indent really well. Indeed, people go to great lengths to indent Java where it's not needed. If indentation is unimportant in Java, why do people do such a good job of it?]
| best way to parse a language that's ALMOST Python? | I'm working on a domain-specific language implemented on top of Python. The grammar is so close to Python's that until now we've just been making a few trivial string transformations and then feeding it into ast. For example, indentation is replaced by #endfor/#endwhile/#endif statements, so we normalize the indentation while it's still a string.
I'm wondering if there's a better way? As far as I can tell, ast is hardcoded to parse the Python grammar and I can't really find any documentation other than http://docs.python.org/library/ast.html#module-ast (and the source itself, I suppose).
Does anyone have personal experience with PyParsing, ANTLR, or PLY?
There are vague plans to rewrite the interpreter into something that transforms our language into valid Python and feeds that into the Python interpreter itself, so I'd like something compatible with compile, but this isn't a deal breaker.
Update: It just occurred to me that
from __future__ import print_function, with_statement
changes the way Python parses the following source. However, PEP 236 suggests that this is syntactic window dressing for a compiler feature. Could someone confirm that trying to override/extend __future__ is not the correct solution to my problem?
| [
"PLY works. It's odd because it mimics lex/yacc in a way that's not terribly pythonic. \nBoth lex and yacc have an implicit interface that makes it possible to run the output from lex as a stand-alone program. This \"feature\" is carefully preserved. Similarly for the yacc-like features of PLY. The \"feature\"... | [
1
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0003504677_parsing_python.txt |
Q:
wxPython: centering an image in a panel
I have a GridSizer with StaticBitmap images in it. I want to put each of the images in their own panels so I can change the background color to highlight an image if it has been selected. When I try to do this, however, the images are not centered in their panels and the highlighted background color is only present on two borders. How can I make the images in the center of their panels so there is an equivalent border around all sides of each?
sizer = wx.GridSizer(rows=row,cols=cols,vgap=5)
for fn in filenames:
p = wx.Panel(self.panel)
img = wx.Image(fn, wx.BITMAP_TYPE_ANY)
img2 = wx.StaticBitmap(p, wx.ID_ANY, wx.BitmapFromImage(img))
img2.Bind(wx.EVT_LEFT_DOWN, self.OnClick, img2)
sizer.Add(p)
self.panel.SetSizer(sizer)
A:
You need to add your image to a boxSizer with a border.
You could write an imagePanel class to implement this.
You should then be able to call SetBackgroundColour on your ImgPanels to change the borders (panels) colour when ever you need to.
Here's a very rough example for an ImgPanel class
class ImgPanel(wx.Panel):
def __init__(self, parent, image):
wx.Panel.__init__(self, parent)
img = wx.Image(image, wx.BITMAP_TYPE_ANY)
self.sBmp = wx.StaticBitmap(self, wx.ID_ANY, wx.BitmapFromImage(img))
sizer = wx.BoxSizer()
sizer.Add(item=self.sBmp, proportion=0, flag=wx.ALL, border=10)
self.SetBackgroundColour('green')
self.SetSizerAndFit(sizer)
| wxPython: centering an image in a panel | I have a GridSizer with StaticBitmap images in it. I want to put each of the images in their own panels so I can change the background color to highlight an image if it has been selected. When I try to do this, however, the images are not centered in their panels and the highlighted background color is only present on two borders. How can I make the images in the center of their panels so there is an equivalent border around all sides of each?
sizer = wx.GridSizer(rows=row,cols=cols,vgap=5)
for fn in filenames:
p = wx.Panel(self.panel)
img = wx.Image(fn, wx.BITMAP_TYPE_ANY)
img2 = wx.StaticBitmap(p, wx.ID_ANY, wx.BitmapFromImage(img))
img2.Bind(wx.EVT_LEFT_DOWN, self.OnClick, img2)
sizer.Add(p)
self.panel.SetSizer(sizer)
| [
"You need to add your image to a boxSizer with a border.\nYou could write an imagePanel class to implement this.\nYou should then be able to call SetBackgroundColour on your ImgPanels to change the borders (panels) colour when ever you need to.\nHere's a very rough example for an ImgPanel class\nclass ImgPanel(wx.... | [
6
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003502772_python_wxpython.txt |
Q:
Extending the code of Python - adding language features
I have been programming in python exclusively for 4 years and have never really looked under the hood at the C code in which python is written. I have recently been looking into a problem that would involve modifying python at that level.
The code seems pretty consistent, and thus relatively easily understood. However, it's complex enough that it wasn't making sense to me just by studying it how it all worked together. Granted, I didn't spend a lot of time or effort on that, for want of a better resource. I also looked over the documentation on the python site. However, it is oriented more toward extending the language through modules.
I was hoping to find some straightforward documentation on how the parser works at the C level and how to extend the core language directly (adding language features). The module-oriented documentation provides some great insight into the way types are built and objects are managed, but I am looking for more.
Is there any such documentation out there?
A:
This article may help you get started. It takes a lot of information from the excellent PEP 339 - Design of the CPython Compiler.
A:
http://docs.python.org/extending/index.html - Custom modules/extensions
http://docs.python.org/c-api/index.html - C API, under the hood
A:
There's not too much written lore on this topic. Your best bet is to just simply follow the guidelines in PEP 306
| Extending the code of Python - adding language features | I have been programming in python exclusively for 4 years and have never really looked under the hood at the C code in which python is written. I have recently been looking into a problem that would involve modifying python at that level.
The code seems pretty consistent, and thus relatively easily understood. However, it's complex enough that it wasn't making sense to me just by studying it how it all worked together. Granted, I didn't spend a lot of time or effort on that, for want of a better resource. I also looked over the documentation on the python site. However, it is oriented more toward extending the language through modules.
I was hoping to find some straightforward documentation on how the parser works at the C level and how to extend the core language directly (adding language features). The module-oriented documentation provides some great insight into the way types are built and objects are managed, but I am looking for more.
Is there any such documentation out there?
| [
"This article may help you get started. It takes a lot of information from the excellent PEP 339 - Design of the CPython Compiler.\n",
"http://docs.python.org/extending/index.html - Custom modules/extensions\nhttp://docs.python.org/c-api/index.html - C API, under the hood\n",
"There's not too much written lore ... | [
3,
1,
1
] | [] | [] | [
"c",
"core",
"python"
] | stackoverflow_0003505029_c_core_python.txt |
Q:
Django maximum recursion depth exceeded
I'm building a small web project using Django that has one model (Image) that contains an ImageField. When I try to upload an image using the admin interface I am presented with this problem (personally identifying information removed):
RuntimeError at /admin/main/image/add/
maximum recursion depth exceeded
Request Method: POST
Request URL: http://x.x.x.x:8080/blog/admin/main/image/add/
Django Version: 1.2.1
Exception Type: RuntimeError
Exception Value:
maximum recursion depth exceeded
Exception Location: /extra/django/blog/main/models.py in __unicode__, line 26
Python Executable: /usr/bin/python
Python Version: 2.4.3
Python Path: ['/extra/django', '/usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg', '/usr/lib/python2.4/site-packages/MySQL_python-1.2.3-py2.4-linux-i686.egg', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/Numeric', '/usr/lib/python2.4/site-packages/PIL', '/usr/lib/python2.4/site-packages/gtk-2.0']
Server time: Tue, 17 Aug 2010 13:30:20 -0400
And this is a portion of my models.py:
class Image(models.Model):
image = models.ImageField(upload_to='uploads/blog_images')
caption = models.CharField(max_length=300)
post = models.ForeignKey('Post')
thumbWidth = models.IntegerField(blank=True,null=True)
thumbHeight = models.IntegerField(blank=True,null=True)
def printTag(self, newClass=''):
str = '<img '
if newClass is not '':
str = str + 'class="%s" ' %newClass
if self.thumbWidth is not None and self.thumbHeight is not None:
str += 'width="%i" height="%i" ' %(self.thumbWidth,self.thumbHeight)
str = str + 'src="%s" ' %self.image
str = str + '>%s</img>' %self.caption
return str
def __unicode__(self):
return self.printTag(self)
Line 26 is the only line inside unicode. I have the extra function (printTag) so I can choose whether or not to print the HTML tag with a "class" attribute with the default being without the attribute. Why is it recursing when I upload an image?
A:
You need return self.printTag() not return self.printTag(self)
| Django maximum recursion depth exceeded | I'm building a small web project using Django that has one model (Image) that contains an ImageField. When I try to upload an image using the admin interface I am presented with this problem (personally identifying information removed):
RuntimeError at /admin/main/image/add/
maximum recursion depth exceeded
Request Method: POST
Request URL: http://x.x.x.x:8080/blog/admin/main/image/add/
Django Version: 1.2.1
Exception Type: RuntimeError
Exception Value:
maximum recursion depth exceeded
Exception Location: /extra/django/blog/main/models.py in __unicode__, line 26
Python Executable: /usr/bin/python
Python Version: 2.4.3
Python Path: ['/extra/django', '/usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg', '/usr/lib/python2.4/site-packages/MySQL_python-1.2.3-py2.4-linux-i686.egg', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/Numeric', '/usr/lib/python2.4/site-packages/PIL', '/usr/lib/python2.4/site-packages/gtk-2.0']
Server time: Tue, 17 Aug 2010 13:30:20 -0400
And this is a portion of my models.py:
class Image(models.Model):
image = models.ImageField(upload_to='uploads/blog_images')
caption = models.CharField(max_length=300)
post = models.ForeignKey('Post')
thumbWidth = models.IntegerField(blank=True,null=True)
thumbHeight = models.IntegerField(blank=True,null=True)
def printTag(self, newClass=''):
str = '<img '
if newClass is not '':
str = str + 'class="%s" ' %newClass
if self.thumbWidth is not None and self.thumbHeight is not None:
str += 'width="%i" height="%i" ' %(self.thumbWidth,self.thumbHeight)
str = str + 'src="%s" ' %self.image
str = str + '>%s</img>' %self.caption
return str
def __unicode__(self):
return self.printTag(self)
Line 26 is the only line inside unicode. I have the extra function (printTag) so I can choose whether or not to print the HTML tag with a "class" attribute with the default being without the attribute. Why is it recursing when I upload an image?
| [
"You need return self.printTag() not return self.printTag(self)\n"
] | [
4
] | [] | [] | [
"apache",
"django",
"python",
"recursion"
] | stackoverflow_0003505467_apache_django_python_recursion.txt |
Q:
Python : Text to ASCII & ASCII to text converter program
i am a newbie to python 2.7 , trying to create a simple program, which takes an input string from the user, converts all the characters into their ascii values, adds 2 to all the ascii values and then converts the new values into text. So for example, if the user input is "test" , the output should be "vguv".
This is the code i have written so far :
message = input("enter message to encode")
for ch in message:
message2 = ord(ch) + 2
print "\n\n"
encodedmessage = ""
for item in message2.split():
encodedmessage += chr(int(item))
print ("encoded msg in text : "), encodedmessage
It doesnt seem to be working properly, any help would be appreciated. Thanks.
A:
message2 = ord(ch) + 2 makes message2 an integer, and so of course you cannot then call split on it -- it's a single int representing a single character, why ever would you want to split it?! Plus, you're resetting encodedmessage to the empty string each time through the loop, so once you've fixed the split weirdness (by simply removing it!) you'll only see the last characted of course; move the encodedmessage = '' to before the loop instead.
A:
You are mixing up characters and strings. When you loop throught a string (such as "message"), on each iteration you'll get a single character. Also, ord(ch) is an integer, a number, so you can't "split" it.
Also, don't use "input", use "raw_input" instead.
What you want is probably something similar to this:
message = raw_input("enter message to encode: ")
encoded_message = ""
for ch in message:
encoded_ord = ord(ch) + 2
Here you don't have a new message yet, as the loop gies you one character at a time, so I'm renaming the variable to "encoded_ord", which better describes what it holds.
Now, you can turn this "encoded ord" into an encoded character, and add it to the encoded message:
encoded_ch = chr(encoded_ord)
encoded_message += chr(encoded_ch)
print "encoded msg in text:", encodedmessage
A:
Are you trying to do a rot-13 (or generalized "rot-x") type function?
from string import ascii_uppercase, ascii_lowercase
def rotx(data,rotby):
total = []
for char in data:
if char in ascii_uppercase:
index = (ascii_uppercase.find(char) + rotby) % 26
total.append(ascii_uppercase[index])
elif char in ascii_lowercase:
index = (ascii_lowercase.find(char) + rotby) % 26
total.append(ascii_lowercase[index])
else:
total.append(char)
return "".join(total)
Running:
>>> import rotx
>>> rotx.rotx("test",2)
'vguv'
>>> rotx.rotx("IBM-9000",-1)
'HAL-9000'
If you blanket add 2 to ASCII characters, } becomes non-printable, ~ turns into something depending on your character encoding
| Python : Text to ASCII & ASCII to text converter program | i am a newbie to python 2.7 , trying to create a simple program, which takes an input string from the user, converts all the characters into their ascii values, adds 2 to all the ascii values and then converts the new values into text. So for example, if the user input is "test" , the output should be "vguv".
This is the code i have written so far :
message = input("enter message to encode")
for ch in message:
message2 = ord(ch) + 2
print "\n\n"
encodedmessage = ""
for item in message2.split():
encodedmessage += chr(int(item))
print ("encoded msg in text : "), encodedmessage
It doesnt seem to be working properly, any help would be appreciated. Thanks.
| [
"message2 = ord(ch) + 2 makes message2 an integer, and so of course you cannot then call split on it -- it's a single int representing a single character, why ever would you want to split it?! Plus, you're resetting encodedmessage to the empty string each time through the loop, so once you've fixed the split weird... | [
2,
1,
1
] | [] | [] | [
"ascii",
"python"
] | stackoverflow_0003505567_ascii_python.txt |
Q:
Dynamically adding checkboxes with PyQt4
I have a simple GUI built using python and PyQt4. After the user enters something into the program, the program should then add a certain number of checkboxes to the UI depending on what the user's input was. For testing purposes, I have one checkbox existing in the application from start, and that checkbox is nested inside of a QVBoxLayout, which is nested inside of a QGroupBox. I have tried reading through the PyQt4 documentation for all of this, but I have struggled to make any progress.
Here is how I am making the initial checkbox (basic output from QtCreator):
self.CheckboxField = QtGui.QGroupBox(self.GuiMain)
self.CheckboxField.setGeometry(QtCore.QRect(10, 70, 501, 41))
self.CheckboxField.setObjectName("CheckboxField")
self.verticalLayoutWidget = QtGui.QWidget(self.CheckboxField)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 10, 491, 21))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.CheckboxLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
self.CheckboxLayout.setSizeConstraint(QtGui.QLayout.SetMinimumSize)
self.CheckboxLayout.setObjectName("CheckboxLayout")
self.checkBox = QtGui.QCheckBox(self.verticalLayoutWidget)
self.checkBox.setObjectName("checkBox")
self.CheckboxLayout.addWidget(self.checkBox)
Then here is my initial attempt to add a new checkbox (in a seperate file):
checkBox1 = QtGui.QCheckBox(self.window.CheckboxField)
checkBox1.setGeometry(QtCore.QRect(90, 10, 70, 17))
checkBox1.setText(QtGui.QApplication.translate("MainWindow", "Bob Oblaw", None, QtGui.QApplication.UnicodeUTF8))
checkBox1.setObjectName("checkBox1")
self.window.CheckboxLayout.addWidget(checkBox1)
self.window.CheckboxLayout.stretch(1)
self.window.CheckboxField.adjustSize()
self.window.CheckboxField.update()
There are no errors, the checkbox just doesn't show up.
A:
I think you're making life hard for yourself by copying QtCreator's output style. I think it's important to manually code some UIs to see how it works. I suspect you're not adding the check box to the layout. Try something this (Import * used for clarity here):
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Window(QWidget):
def __init__(self):
QWidget.__init__(self)
layout = QVBoxLayout()
self.checks = []
for i in xrange(5):
c = QCheckBox("Option %i" % i)
layout.addWidget(c)
self.checks.append(c)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Window()
w.show()
app.exec_()
A:
I ended up figuring it out myself. Part of it was my fault, and the other part is a little bit hacky (seeing as it probably doesn't use a Qt function it could be using). Here is my solution:
First, I needed to lay everything out on a grid layout, this made it so my check marks started showing up when I added them
Sadly, the window didn't resize with the checkboxes, so I wrote a function like this to fix it:
def addCheckbox(self, name):
checkBox = QtGui.QCheckBox(self.window.CheckboxField)
self.window.CheckboxLayout.addWidget(checkBox)
checkBox.setText(name)
newHeight = self.geometry().height()+21#Compensate for new checkbox
self.resize(self.geometry().width(), newHeight)
| Dynamically adding checkboxes with PyQt4 | I have a simple GUI built using python and PyQt4. After the user enters something into the program, the program should then add a certain number of checkboxes to the UI depending on what the user's input was. For testing purposes, I have one checkbox existing in the application from start, and that checkbox is nested inside of a QVBoxLayout, which is nested inside of a QGroupBox. I have tried reading through the PyQt4 documentation for all of this, but I have struggled to make any progress.
Here is how I am making the initial checkbox (basic output from QtCreator):
self.CheckboxField = QtGui.QGroupBox(self.GuiMain)
self.CheckboxField.setGeometry(QtCore.QRect(10, 70, 501, 41))
self.CheckboxField.setObjectName("CheckboxField")
self.verticalLayoutWidget = QtGui.QWidget(self.CheckboxField)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 10, 491, 21))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.CheckboxLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
self.CheckboxLayout.setSizeConstraint(QtGui.QLayout.SetMinimumSize)
self.CheckboxLayout.setObjectName("CheckboxLayout")
self.checkBox = QtGui.QCheckBox(self.verticalLayoutWidget)
self.checkBox.setObjectName("checkBox")
self.CheckboxLayout.addWidget(self.checkBox)
Then here is my initial attempt to add a new checkbox (in a seperate file):
checkBox1 = QtGui.QCheckBox(self.window.CheckboxField)
checkBox1.setGeometry(QtCore.QRect(90, 10, 70, 17))
checkBox1.setText(QtGui.QApplication.translate("MainWindow", "Bob Oblaw", None, QtGui.QApplication.UnicodeUTF8))
checkBox1.setObjectName("checkBox1")
self.window.CheckboxLayout.addWidget(checkBox1)
self.window.CheckboxLayout.stretch(1)
self.window.CheckboxField.adjustSize()
self.window.CheckboxField.update()
There are no errors, the checkbox just doesn't show up.
| [
"I think you're making life hard for yourself by copying QtCreator's output style. I think it's important to manually code some UIs to see how it works. I suspect you're not adding the check box to the layout. Try something this (Import * used for clarity here):\n\nimport sys\nfrom PyQt4.QtGui import *\nfrom PyQt4.... | [
2,
1
] | [] | [] | [
"checkbox",
"dynamic",
"pyqt4",
"python",
"user_interface"
] | stackoverflow_0003496220_checkbox_dynamic_pyqt4_python_user_interface.txt |
Q:
files getting wrongly cached by the web server while using standard python file operations (Django)
I have a Django app, which populates content from a text file, and populates them using the initial option in a standard form. The file gets updated on the server, but when the form gets refreshed, it picks up content from the a previously saved version, or the version before the Apache WebServer was reloaded.
This means that the file is getting cached, and the content is picked up from a wrong cache and not the new file.
Here is my code. How do I ensure that everytime, spamsource function picks up the content from the most recently saved file, instead of from a cache.
def spamsource():
try:
f= open('center_access', 'r')
read=f.read()
# some manipulation on read
f.close()
return read
except IOError:
return "prono.nr"
class SpamForm(forms.Form):
domains =forms.CharField(widget=forms.Textarea(attrs=attrs_dict),
label=_(u'Domains to be Banned'), initial= spamsource())
def function(request):
# It writes the file center_access based on the changes in the textbox domains
A:
The issue is simply that all the parameters to fields are evaluated at form definition time. So, the initial value for domains is set to whatever the return value is from spamsource() at the time the form is defined, ie usually when the server is started.
One way of fixing this would be to override the form's __init__ method and set the initial value for domains there:
class SpamForm(forms.Form):
domains = ...
def __init__(self, *args, **kwargs):
super(SpamForm, self).__init__(*args, **kwargs)
self.fields['domains'].initial = spamsource()
Alternatively, you could set the initial value when you instantiate the form in your view:
form = SpamForm(initial={'domains': spamsource()})
A:
I fixed this. The problem was the presence of all the caching middleware in settings.py, which were being used to speed up another side of the web app.
| files getting wrongly cached by the web server while using standard python file operations (Django) | I have a Django app, which populates content from a text file, and populates them using the initial option in a standard form. The file gets updated on the server, but when the form gets refreshed, it picks up content from the a previously saved version, or the version before the Apache WebServer was reloaded.
This means that the file is getting cached, and the content is picked up from a wrong cache and not the new file.
Here is my code. How do I ensure that everytime, spamsource function picks up the content from the most recently saved file, instead of from a cache.
def spamsource():
try:
f= open('center_access', 'r')
read=f.read()
# some manipulation on read
f.close()
return read
except IOError:
return "prono.nr"
class SpamForm(forms.Form):
domains =forms.CharField(widget=forms.Textarea(attrs=attrs_dict),
label=_(u'Domains to be Banned'), initial= spamsource())
def function(request):
# It writes the file center_access based on the changes in the textbox domains
| [
"The issue is simply that all the parameters to fields are evaluated at form definition time. So, the initial value for domains is set to whatever the return value is from spamsource() at the time the form is defined, ie usually when the server is started.\nOne way of fixing this would be to override the form's __i... | [
3,
0
] | [] | [] | [
"caching",
"django",
"file",
"python"
] | stackoverflow_0003431124_caching_django_file_python.txt |
Q:
PyQt4 Threading: Sending data back to a thread
I'm writing a program, with a PyQt frontend. To ensure that the UI doesn't freeze up, I use QThreads to emit signals back to the parent. Now, I have reached a point where I need my thread to stop running, emit a signal back to the parent, then wait on the parent to return an approval for the thread to continue (after the user interacts with the UI a little bit).
I've been looking into the QMutex class, along with QThread's wait function.
How should I go about doing this properly?
A:
One approach is using a condition variable.
In my code, however, I prefer using Python's built-in Queue objects to synchronize data between threads. While I'm at it, I use Python's threads as opposed to PyQt threads, mainly because it allows me to reuse the non-GUI part of the code without an actual GUI.
| PyQt4 Threading: Sending data back to a thread | I'm writing a program, with a PyQt frontend. To ensure that the UI doesn't freeze up, I use QThreads to emit signals back to the parent. Now, I have reached a point where I need my thread to stop running, emit a signal back to the parent, then wait on the parent to return an approval for the thread to continue (after the user interacts with the UI a little bit).
I've been looking into the QMutex class, along with QThread's wait function.
How should I go about doing this properly?
| [
"One approach is using a condition variable.\nIn my code, however, I prefer using Python's built-in Queue objects to synchronize data between threads. While I'm at it, I use Python's threads as opposed to PyQt threads, mainly because it allows me to reuse the non-GUI part of the code without an actual GUI.\n"
] | [
1
] | [] | [] | [
"multithreading",
"pyqt4",
"python",
"signals",
"user_interface"
] | stackoverflow_0003505982_multithreading_pyqt4_python_signals_user_interface.txt |
Q:
Django: Managing Session Variables to manage the browser back button
I am creating a web based Mock test paper, which needs to be fairly secure.
The needs are
Each question can be attempted and answered just once.
All are multiple Choice questions
Once a question is answered and the submit pressed, then that session must expire, and the same question must not appear either through back button or some other way.
In case the browser crashes or the system crashes, the student must be able to go back to the last question which was being attempted, and not yet answered and submitted.
What would be the best strategies to adopt while implementing it in Django. How do you automatically kill the session, once the submit button is pressed? And how do you ensure that by pressing the back button, you are not able to access a question attempted and answered?
I tried googling, but I am not able to point to resources that would guide me better. I have seen django sessions documents, but I am not sure whether I know the right way to do this. Any suggestions can help
A:
And how do you ensure that by pressing the back button, you are not able to access a question attempted and answered?
Post-Redirect-Get. http://en.wikipedia.org/wiki/Post/Redirect/Get
How do you automatically kill the session, once the submit button is pressed?
Doesn't really make sense. You don't need to 'kill' the session. You need to do two things.
Update the database entry for this user to indicate how far they've gotten.
Update the session to indicate how far they've gotten.
Don't try to "kill" the session. Keep the session information (and the underlying database) correct.
Killing the session will only force them to login again -- which is merely annoying. Further, when they login again, the database must be correct or they'll start the test again. So, you only need to keep the database and session synchronized.
| Django: Managing Session Variables to manage the browser back button | I am creating a web based Mock test paper, which needs to be fairly secure.
The needs are
Each question can be attempted and answered just once.
All are multiple Choice questions
Once a question is answered and the submit pressed, then that session must expire, and the same question must not appear either through back button or some other way.
In case the browser crashes or the system crashes, the student must be able to go back to the last question which was being attempted, and not yet answered and submitted.
What would be the best strategies to adopt while implementing it in Django. How do you automatically kill the session, once the submit button is pressed? And how do you ensure that by pressing the back button, you are not able to access a question attempted and answered?
I tried googling, but I am not able to point to resources that would guide me better. I have seen django sessions documents, but I am not sure whether I know the right way to do this. Any suggestions can help
| [
"\nAnd how do you ensure that by pressing the back button, you are not able to access a question attempted and answered?\n\nPost-Redirect-Get. http://en.wikipedia.org/wiki/Post/Redirect/Get\n\nHow do you automatically kill the session, once the submit button is pressed?\n\nDoesn't really make sense. You don't nee... | [
3
] | [] | [] | [
"django",
"django_sessions",
"python",
"session"
] | stackoverflow_0003506112_django_django_sessions_python_session.txt |
Q:
Static class members python
So I'm using static class members so I can share data between class methods and static methods of the same class (there will only be 1 instantiation of the class). I understand this fine, but I'm just wondering when the static members get initialized? Is it on import? On the first use of the class? Because I'm going to be calling the static members of this class from more than 1 module (therefore more than 1 import statement). Will all the modules accessing the static methods share the same static data members? And if my main client deletes the instance of my class, and then recreates it (without terminating altogether or re-importing stuff), will my data members be preserved?
A:
They will be initialized at class definition time, which will happen at import time if you are importing the class as part of a module. This assuming a "static" class member definition style like this:
class Foo:
bar = 1
print Foo.bar # prints '1'
Note that, this being a static class member, there is no need to instantiate the class.
The import statement will execute the contents of a module exactly once, no matter how many times or where it is executed.
Yes, the static members will be shared by any code accessing them.
Yes, the static members of a class will be preserved if you delete an object whose type is that class:
# Create static member
class Foo:
bar = 1
# Create and destroy object of type Foo
foo = Foo()
del foo
# Check that static members survive
print Foo.bar # Still prints '1'
| Static class members python | So I'm using static class members so I can share data between class methods and static methods of the same class (there will only be 1 instantiation of the class). I understand this fine, but I'm just wondering when the static members get initialized? Is it on import? On the first use of the class? Because I'm going to be calling the static members of this class from more than 1 module (therefore more than 1 import statement). Will all the modules accessing the static methods share the same static data members? And if my main client deletes the instance of my class, and then recreates it (without terminating altogether or re-importing stuff), will my data members be preserved?
| [
"They will be initialized at class definition time, which will happen at import time if you are importing the class as part of a module. This assuming a \"static\" class member definition style like this:\nclass Foo:\n bar = 1\n\nprint Foo.bar # prints '1'\n\nNote that, this being a static class member, there i... | [
16
] | [] | [] | [
"python",
"static",
"static_variables"
] | stackoverflow_0003506150_python_static_static_variables.txt |
Q:
What is the best way to sort items on one of the items values
I have two instances of an object in a list
class Thing():
timeTo = 0
timeFrom = 0
name = ""
o1 = Thing()
o1.name = "One"
o1.timeFrom = 2
o2 = Thing()
o2.timeTo = 20
o2.name = "Two"
myList = [o1, o2]
biggestIndex = (myList[0].timeFrom < myList[1].timeTo) & 1
bigger = myList.pop(biggestIndex)
lesser = myList.pop()
print bigger.name
print lesser.name
both o1 and o2 have two properties that I want to compare the first in the lists timeFrom property and the second ones timeTo property to eachother.
I feel this is a bit awkward and wierd, is there perhaps a better and more readable approach to this?
A:
The best solution is to make Thing instances sortable. You do this by implementing __lt__:
class Thing():
timeTo = 0
timeFrom = 0
name = ""
def __lt__(self, other):
return self.timeFrom < other.timeTo
lesser, bigger = sorted(myList)
Python2 has lesser, bigger = sorted(myList, cmp=lambda one,other: one.timeFrom < other.timeTo).
In Python3 cmp is gone, I guess to force people to do (or learn) OOP and write a adapter.
class SortAdaper(object):
def __init__(self, obj ):
self.obj = obj
class TimeLineSorter(SortAdaper):
""" sorts in a timeline """
def __lt__(self, other):
return self.obj.timeFrom < other.obj.timeTo
class NameSorter(SortAdaper):
""" sorts by name """
def __lt__(self, other):
return self.obj.name < other.obj.name
print sorted( myList, key=TimeLineSorter)
print sorted( myList, key=NameSorter)
A:
see attrgetter
import operator
getter = operator.attrgetter('timeFrom')
bigger = max(myList, key=getter)
lesser = min(myList, key=getter)
print bigger.name
print lesser.name
EDIT :
attrgetter also wokrs with sorted or anywhere a key function is needed.
lesser, bigger = sorted(myList, key=getter)
A:
I would do this, if object can have only one of the time values:
class Thing(object):
def __init__(self, name, time = 0, timename = 'to'):
self.name, self.time, self.timename = (name,time,timename)
def __repr__(self):
return "Thing(%r, %i, %r)" % (self.name, self.time, self.timename)
def __lt__(self, other):
return self.time < other.time
o1 = Thing("One", 5, 'from')
o2 = Thing("Two", 20, 'to')
myList = [o1, o2]
print myList
print max(myList)
print min(myList)
| What is the best way to sort items on one of the items values | I have two instances of an object in a list
class Thing():
timeTo = 0
timeFrom = 0
name = ""
o1 = Thing()
o1.name = "One"
o1.timeFrom = 2
o2 = Thing()
o2.timeTo = 20
o2.name = "Two"
myList = [o1, o2]
biggestIndex = (myList[0].timeFrom < myList[1].timeTo) & 1
bigger = myList.pop(biggestIndex)
lesser = myList.pop()
print bigger.name
print lesser.name
both o1 and o2 have two properties that I want to compare the first in the lists timeFrom property and the second ones timeTo property to eachother.
I feel this is a bit awkward and wierd, is there perhaps a better and more readable approach to this?
| [
"The best solution is to make Thing instances sortable. You do this by implementing __lt__:\nclass Thing():\n timeTo = 0\n timeFrom = 0\n name = \"\"\n\n def __lt__(self, other):\n return self.timeFrom < other.timeTo\n\n\nlesser, bigger = sorted(myList)\n\nPython2 has lesser, bigger = sorted... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003503859_python.txt |
Q:
Special type of combination using itertools
I am almost finished with a task someone gave me that at first involved easy use of the product() function from itertools.
However, the person asked that it should also do something a bit different like:
li =
[[1, 2, 3],
[4, 5, 6]]
A regular product() would give something like: [1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4] ...
What it should do is:
Do a regular product(), then, add the next item from the first element in the list and so on. A complete set of example would be:
[[1, 4, 2]
[1, 4, 3],
[1, 5, 2],
[1, 5, 3],
[2, 4, 3],
[2, 5, 3],
[2, 6, 3]]
How should I use itertools in this circumstance?
EDIT:
It might help if I explain the goal of the program:
The user will enter, for example, a 5 row by 6 column list of numbers.
A normal product() will result in a 5-number combination. The person wants a 6-number combination. Where will this "6th" number come from? It would come from his choice of which row he wants.
A:
I wondering what is the magical computations you performing, but it look's like that's your formula:
k = int(raw_input('From What row items should be appeared again at the end?'))
res = [l for l in product(*(li+[li[k]])) if l[k]<l[len(li)] ]
A:
Generalized for more than two sublist (map function would be the other alternative)
from pprint import pprint
for li in ([[1, 2, 3],
[4, 5, 6]],
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
):
triples= []
prevlist=li[0]
for nextlist in li[1:]:
for spacing in range(1,len(prevlist)):
triples.extend([[first,other,second]
for first,second in zip(prevlist,prevlist[spacing:])
for other in nextlist])
pprint(sorted(triples))
| Special type of combination using itertools | I am almost finished with a task someone gave me that at first involved easy use of the product() function from itertools.
However, the person asked that it should also do something a bit different like:
li =
[[1, 2, 3],
[4, 5, 6]]
A regular product() would give something like: [1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4] ...
What it should do is:
Do a regular product(), then, add the next item from the first element in the list and so on. A complete set of example would be:
[[1, 4, 2]
[1, 4, 3],
[1, 5, 2],
[1, 5, 3],
[2, 4, 3],
[2, 5, 3],
[2, 6, 3]]
How should I use itertools in this circumstance?
EDIT:
It might help if I explain the goal of the program:
The user will enter, for example, a 5 row by 6 column list of numbers.
A normal product() will result in a 5-number combination. The person wants a 6-number combination. Where will this "6th" number come from? It would come from his choice of which row he wants.
| [
"I wondering what is the magical computations you performing, but it look's like that's your formula:\nk = int(raw_input('From What row items should be appeared again at the end?'))\nres = [l for l in product(*(li+[li[k]])) if l[k]<l[len(li)] ]\n\n",
"Generalized for more than two sublist (map function would be t... | [
1,
1
] | [] | [] | [
"python",
"python_itertools"
] | stackoverflow_0003506210_python_python_itertools.txt |
Q:
how to make a 3d effect on bars in matplotlib?
I have a very simple basic bar's graphic like this one
but i want to display the bars with some 3d effect, like this
I just want the bars to have that 3d effect...my code is:
fig = Figure(figsize=(4.6,4))
ax1 = fig.add_subplot(111,ylabel="Valeur",xlabel="Code",autoscale_on=True)
width = 0.35
ind = np.arange(len(values))
rects = ax1.bar(ind, values, width, color='#A1B214')
ax1.set_xticks(ind+width)
ax1.set_xticklabels( codes )
ax1.set_ybound(-1,values[0] * 1.1)
canvas = FigureCanvas(fig)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
i've been looking in the gallery of matplotlib,tried a few things but i wasn't lucky, Any ideas? Thxs
A:
I certainly understand your reason for needing a 3d bar plot; i suspect that's why they were created.
The libraries ('toolkits') in Matplotlib required to create 3D plots are not third-party libraries, etc., rather they are included in the base Matplotlib installation.
(This is true for the current stable version, which is 1.0, though i don't believe it was for 0.98, so the change--from 'add-on' to part of the base install--occurred within the past year, i believe)
So here you are:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as PLT
import numpy as NP
fig = PLT.figure()
ax1 = fig.add_subplot(111, projection='3d')
xpos = NP.random.randint(1, 10, 10)
ypos = NP.random.randint(1, 10, 10)
num_elements = 10
zpos = NP.zeros(num_elements)
dx = NP.ones(10)
dy = NP.ones(10)
dz = NP.random.randint(1, 5, 10)
ax1.bar3d(xpos, ypos, zpos, dx, dy, dz, color='#8E4585')
PLT.show()
To create 3d bars in Maplotlib, you just need to do three (additional) things:
import Axes3D from mpl_toolkits.mplot3d
call the bar3d method (in my scriptlet, it's called by ax1 an instance of the Axes class). The method signature:
bar3d(x, y, z, dy, dz, color='b', zsort="average", *args, **kwargs)
pass in an additional argument to add_subplot, projection='3d'
A:
As far as I know Matplotlib doesn't by design support features like the "3D" effect you just mentioned. I remember reading about this some time back. I don't know it has changed in the meantime.
See this discussion thread for more details.
Update
Take a look at John Porter's mplot3d module. This is not a part of standard matplotlib but a custom extension. Never used it myself so can't say much about its usefulness.
| how to make a 3d effect on bars in matplotlib? | I have a very simple basic bar's graphic like this one
but i want to display the bars with some 3d effect, like this
I just want the bars to have that 3d effect...my code is:
fig = Figure(figsize=(4.6,4))
ax1 = fig.add_subplot(111,ylabel="Valeur",xlabel="Code",autoscale_on=True)
width = 0.35
ind = np.arange(len(values))
rects = ax1.bar(ind, values, width, color='#A1B214')
ax1.set_xticks(ind+width)
ax1.set_xticklabels( codes )
ax1.set_ybound(-1,values[0] * 1.1)
canvas = FigureCanvas(fig)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
i've been looking in the gallery of matplotlib,tried a few things but i wasn't lucky, Any ideas? Thxs
| [
"I certainly understand your reason for needing a 3d bar plot; i suspect that's why they were created. \nThe libraries ('toolkits') in Matplotlib required to create 3D plots are not third-party libraries, etc., rather they are included in the base Matplotlib installation. \n(This is true for the current stable vers... | [
11,
1
] | [] | [] | [
"3d",
"bar_chart",
"matplotlib",
"python"
] | stackoverflow_0003501771_3d_bar_chart_matplotlib_python.txt |
Q:
How is memcache.incr() affected by App Engine maintenance periods?
I'm working on an application that will run on Google App Engine. I would like it to respond gracefully to App Engine maintenance periods.
According to the documentation, memcache will simply not store or retrieve data during maintenance periods:
During a read-only maintenance period,
calls to the memcache API will not
throw exceptions but will instead
return False for set() calls and None
for get() calls (just like any other
cache miss). In addition, memcache API
calls will return immediately during
this period, without any additional
latency.
Does this apply to incr() calls as well? It seems like it should, but I cannot find any documentation to this effect and I want to be sure.
A:
The documentation for incr() states:
The return value is a new long integer value, or None if key was not in the cache or could not be incremented for any other reason.
As the documentation also makes clear that you're unable to set or get data during maintenance, and incr() is really just a helper function around set(), you should expect a return value of None during maintenance periods for the incr() function.
| How is memcache.incr() affected by App Engine maintenance periods? | I'm working on an application that will run on Google App Engine. I would like it to respond gracefully to App Engine maintenance periods.
According to the documentation, memcache will simply not store or retrieve data during maintenance periods:
During a read-only maintenance period,
calls to the memcache API will not
throw exceptions but will instead
return False for set() calls and None
for get() calls (just like any other
cache miss). In addition, memcache API
calls will return immediately during
this period, without any additional
latency.
Does this apply to incr() calls as well? It seems like it should, but I cannot find any documentation to this effect and I want to be sure.
| [
"The documentation for incr() states:\n\nThe return value is a new long integer value, or None if key was not in the cache or could not be incremented for any other reason.\n\nAs the documentation also makes clear that you're unable to set or get data during maintenance, and incr() is really just a helper function ... | [
3
] | [] | [] | [
"google_app_engine",
"maintenance_mode",
"memcached",
"python"
] | stackoverflow_0003506503_google_app_engine_maintenance_mode_memcached_python.txt |
Q:
Using RSA in Python
I am using RSA to encrypt/decrypt my session keys in Python. I am using Pycrypto library. After generating the keypair, I want to extract the private key and public key from that generated key and store them in different files. How can I do this? I can see the has Private method which can tell that the generated keypair has private component but not able to find how to extract both the keys from this generated keypair. Any Suggestion would be of great help.
A:
If you want to get the different parts from the key, there is key attribute for that:
>>> from Crypto.PublicKey import RSA
>>> RSAkey = RSA.generate(1024)
>>> getattr(RSAkey.key, 'n')
13773...L
>>> getattr(RSAkey.key, 'p')
11731...L
>>> getattr(RSAkey.key, 'q')
11740...L
Available components are 'n', 'e', 'd', 'p', 'q', 'u'
If you just want to save it in PEM, you should use exportKey() method (available since 2.2)
>>> private = RSA.generate(1024)
>>> public = private.publickey()
>>> private.exportKey()
'-----BEGIN RSA PRIVATE KEY-----\nMIICXgIBAAKBgQDo1M0P3nryaF8ZITv8vCFVnjUJ1mnIsrqXZRTzjin69xepr3cz\nKicG3EYSUqMODQAsvMj0tGMo+ElGOVOkPFLVVBHd8izgA/E1RqUzbUDMj4WnhlhA\nQq7tNaViOXNaZ7krJZHabZKxfYvLAQtm4tr+m5NtXPBaWvjwhd5M9xvktwIDAQAB\nAoGBANVsS1Rikbymo5V7e2teYAgFb4THAEyyWIvyYlQnWp/r48rtRoyl9QQ64hhl\nm4WDsUdQ/bwhpkul3DT804jWqu2V71p68rQP7h5D6ldCBUr5nQc9o/uEyy4YCgxD\n/ZxNiY5Bb/lMP9nhb2NbG4184mhUMHu+06wWX6RrXQtMtjYhAkEA8DioToMZIy3s\nhPohri3CAgByV2Jxf7JPqVZ93JjlSlBz+aybSv1mOJUPRFpkMk2xiPmHtEn16hYr\nesVK11tcjwJBAPgf4QYAw9dV+DuVqdwz+kmTjnlkr0Q7fjaGfl60DWmuLWmxiRhe\nMYQ2+8iyPDmxcPFTGSpGqyvyJDjQ/wOlWVkCQQCRIuotZW/OnXSFc0reHa9V3kc3\nHLdOW8FdonAw0//Uwn8PnoXE7QzRqt2qgqJ+8goNpBWli/oUEIj8iC8LpptpAkBV\nFFlMfaaph8j+ZWtBHnGMGRSZe3S9qMi2WZerUYHn4tmfjEi+Gk5QT6o2Pyd3gOiB\nV0Uhwemfv/+7m65VybTBAkEA5H59kG+B9HHD5hJtksAtMh8dxk/MI8G0csduU0vu\n7K5ejL522XsHurVrWdqnk6KvjlRXqB4FsMWLE6RBgBNV0A==\n-----END RSA PRIVATE KEY-----'
>>> public.exportKey()
'-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDo1M0P3nryaF8ZITv8vCFVnjUJ\n1mnIsrqXZRTzjin69xepr3czKicG3EYSUqMODQAsvMj0tGMo+ElGOVOkPFLVVBHd\n8izgA/E1RqUzbUDMj4WnhlhAQq7tNaViOXNaZ7krJZHabZKxfYvLAQtm4tr+m5Nt\nXPBaWvjwhd5M9xvktwIDAQAB\n-----END PUBLIC KEY-----'
| Using RSA in Python | I am using RSA to encrypt/decrypt my session keys in Python. I am using Pycrypto library. After generating the keypair, I want to extract the private key and public key from that generated key and store them in different files. How can I do this? I can see the has Private method which can tell that the generated keypair has private component but not able to find how to extract both the keys from this generated keypair. Any Suggestion would be of great help.
| [
"If you want to get the different parts from the key, there is key attribute for that:\n>>> from Crypto.PublicKey import RSA\n>>> RSAkey = RSA.generate(1024)\n>>> getattr(RSAkey.key, 'n')\n13773...L\n>>> getattr(RSAkey.key, 'p')\n11731...L\n>>> getattr(RSAkey.key, 'q')\n11740...L\n\nAvailable components are 'n', 'e... | [
41
] | [] | [] | [
"pycrypto",
"python",
"rsa"
] | stackoverflow_0003504955_pycrypto_python_rsa.txt |
Q:
How to align the text in a wx.ListBox using wxPython?
I want the text of the ListBox to be centered, is that possible?
A:
No, the default ListBox won't work for that. Try the VListBox instead.
| How to align the text in a wx.ListBox using wxPython? | I want the text of the ListBox to be centered, is that possible?
| [
"No, the default ListBox won't work for that. Try the VListBox instead.\n"
] | [
1
] | [] | [] | [
"alignment",
"center",
"listbox",
"python",
"wxpython"
] | stackoverflow_0003483179_alignment_center_listbox_python_wxpython.txt |
Q:
What are the most interesting projects surrounding python?
There are many neat projects around that are extending the usefulness of python inside and outside the core language and standard library. Some that come to mind are:
pypy
stackless
twisted
unladen swallow
web frameworks
numpy
function annotations
other interesting ideas
What are some of the projects that get you excited, on and off this list?
A:
My favorites:
Full-featured web frameworks like Django - making basic web development really easy.
PyQt - binding the full power of the Qt framework to Python
Pygame - easy and fun game development
matplotlib - publication-quality scientific plots for any purpose
A:
Sage: "Sage is a free open-source mathematics software system licensed under the GPL. It combines the power of many existing open-source packages into a common Python-based interface."
A:
Pyjamas (PyJS) - Unified web and GUI framework with all components being done in native python (no more annoying JS).
A:
Reportlab - Programatic creation of PDFs.
I second all of Eli's suggestions, all realy excellent stuff especially PyQt and PySide.
A:
i like zope and plone very much.
A:
PLY - Python Lex-Yacc
It (ab)uses Python's docstrings to allow you to embed BNF grammar files directly into the code.
| What are the most interesting projects surrounding python? | There are many neat projects around that are extending the usefulness of python inside and outside the core language and standard library. Some that come to mind are:
pypy
stackless
twisted
unladen swallow
web frameworks
numpy
function annotations
other interesting ideas
What are some of the projects that get you excited, on and off this list?
| [
"My favorites:\n\nFull-featured web frameworks like Django - making basic web development really easy.\nPyQt - binding the full power of the Qt framework to Python\nPygame - easy and fun game development\nmatplotlib - publication-quality scientific plots for any purpose\n\n",
"Sage: \"Sage is a free open-source ... | [
4,
1,
1,
0,
0,
0
] | [] | [] | [
"projects",
"python"
] | stackoverflow_0003504842_projects_python.txt |
Q:
mongodb union $or problems
I have a collection which is an action log between two users. It has a src_id and a dest_id.
I'm a looking to fetch all the records that are actions between id1 and a list of ids - "ids = [id2, id3, id4]".
The following two statements work properly:
act_obs = self.db.action_log.find(
{'src_id': id1, 'dest_id': {'$in': ids} }
)
act_obs = self.db.action_log.find(
{'dest_id': id1, 'src_id': {'$in': ids} }
)
However, and this is where I can't figure out what is wrong, the following refuses to return any results at all:
act_obs = self.db.action_log.find(
{'$or': [
{'dest_id': id1, 'src_id': {'$in': ids} },
{'src_id': id1, 'dest_id': {'$in': ids} }
]}
)
Can someone shed some light on what I'm doing wrong, if that is the case? And more importantly, how to accomplish what I'm trying to do within mongo.
I'm trying to get all the records where id1 is the src_id and any of the ids in the ids list is the dest_id OR any records where id1 is the dest_id and any of the ids in the ids list is the src_id.
I'm using pymongo 1.7. Thank you!
A:
I don't think that you can use $or like that. You will have to perform the union client side.
A:
The $or operator is available in MongoDB 1.5.3 and later.
An alternative is to use a Javascript function, something like...
find = self.db.action_log.find()
find.where(pymongo.code.Code('this.dest_id==1 || this.src_id==2'))
| mongodb union $or problems | I have a collection which is an action log between two users. It has a src_id and a dest_id.
I'm a looking to fetch all the records that are actions between id1 and a list of ids - "ids = [id2, id3, id4]".
The following two statements work properly:
act_obs = self.db.action_log.find(
{'src_id': id1, 'dest_id': {'$in': ids} }
)
act_obs = self.db.action_log.find(
{'dest_id': id1, 'src_id': {'$in': ids} }
)
However, and this is where I can't figure out what is wrong, the following refuses to return any results at all:
act_obs = self.db.action_log.find(
{'$or': [
{'dest_id': id1, 'src_id': {'$in': ids} },
{'src_id': id1, 'dest_id': {'$in': ids} }
]}
)
Can someone shed some light on what I'm doing wrong, if that is the case? And more importantly, how to accomplish what I'm trying to do within mongo.
I'm trying to get all the records where id1 is the src_id and any of the ids in the ids list is the dest_id OR any records where id1 is the dest_id and any of the ids in the ids list is the src_id.
I'm using pymongo 1.7. Thank you!
| [
"I don't think that you can use $or like that. You will have to perform the union client side.\n",
"The $or operator is available in MongoDB 1.5.3 and later. \nAn alternative is to use a Javascript function, something like...\nfind = self.db.action_log.find()\nfind.where(pymongo.code.Code('this.dest_id==1 || this... | [
0,
0
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0003436386_mongodb_pymongo_python.txt |
Q:
Enthought Python, Sage, or others (in Unix clusters)
I have access to a cluster of Unix machines, but they don't have the software I need (numpy, scipy, matplotlib, etc), so I have to install them by myself (I don't have root permissions, either, so commands like apt-get or yast don't work).
In the worst case, I will have to compile them all from source. Is there any better way to proceed? I've heard something about Enthought Python and Sage, but am not sure what is the best way to go.
Any suggestions?
A:
EPD (Enthought Python Distribution) is great, but even for academics, you can only get the 32-bit version free of charge. If you intend to do anything ram-intensive, it's not really an option.
Edit: This has since changed, and the 64-bit version is freely available for academic/educational use.
On the other hand, the Intel MLK library does make a difference, and it has lots of nifty (e.g. the latest version of mayavi) things built that can otherwise be a real pain to build from source. Also, as others have said, you can just untar it into your home folder and run it. You shouldn't need root access.
EPD is an absolutely great option if you don't ever need to use more than 2GB of ram, but you will have to pay to get 64-bit builds.
Python(x,y) is great if you're on windows, but otherwise, good luck finding the linux pre-built binaries. They more-or-less no longer exist... The ubuntu repository seems to be permanently down, and I don't know of anywhere to get a pre-compiled tarball for it anymore. This may all change in the near future, though... Hopefully it does, because it would be a great option for you!
Honestly, if you just need numpy, scipy, and matplotlib, they're relatively easy to build from source (especially so if you can get away without scipy), and you can always just build your own python interpreter and then use easy_install to avoid having to build them from source. This, of course, assumes that a basic build environment (gcc, etc) are already installed on the machine you're using... That's what I've done when I was in your situation, anyway...
If you go that route, it's best to download the python source code and build your own python interpreter that you'll use for everything. Then install setuptools and easy_install the rest. (Alternately, you can download the source code for numpy, etc and build and install them in for the python interpreter you just built.)
This shows a basic idea how to build the basics (python, numpy, scipy, matplotlib, ipython) under a directory called "pythondist" in the current working directory.
#! /bin/sh
builddir=$(pwd)/pythondist
mkdir -p $builddir/source
cd $builddir/source
wget 'http://python.org/ftp/python/2.6.5/Python-2.6.5.tgz'
wget 'http://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz#md5=7df2a529a074f613b509fb44feefe74e'
tar -xvzf Python-2.6.5.tgz
# Build python
cd $builddir/source/Python-2.6.5/
# The --prefix argument is the key!
./configure --prefix=$builddir
# Be sure to speed things up with the -j option if you're
# on a multicore machine (e.g. make -j 4 build for a quadcore)
make build
make install
# Now install setuptools
cd $builddir/source
tar -xvzf setuptools-0.6c11.tar.gz
cd setuptools-0.6c11/
# The next key is to call this with the python you just built!
$builddir/bin/python setup.py build
$builddir/bin/python setup.py install
# Now just install numpy, scipy, ipython, matplotlib, etc through easy_install
$builddir/bin/easy_install numpy
$builddir/bin/easy_install scipy
$builddir/bin/easy_install matplotlib
$builddir/bin/easy_install ipython
EDIT: Minor typos in script. If numpy or scipy doesn't install properly from the egg, see the install notes.
This script is mainly intended to demonstrate building an independent python in your home directory, and assumes the system you're building on has the proper dependencies already installed, but it at least points you in the right direction.
If numpy or scipy don't build properly using easy_install, download the source tarballs and try building building them from there using different arguments. (Numpy/Scipy's setup.py autodetecting the wrong fortran compiler is common problem, in my experience) E.g.
cd $builddir/source
wget http://sourceforge.net/projects/numpy/files/NumPy/1.4.1/numpy-1.4.1.tar.gz/download
tar -xvzf numpy-1.4.1.tar.gz
cd numpy-1.4.1/
# If you don't specify an action (e.g. "build") this will enter an interactive
# mode to help diagnose problems... See the INSTALL.txt file, too!
$builddir/bin/python setup.py
For example, on my OpenSUSE 11.2 system, I need to specify "--fcompiler=gnu95" when building numpy and scipy, as I have both g77 and gfortran installed. Otherwise things won't build correctly.
However, on an older RHEL 3 system, it builds perfectly as-is from easy_install. YMMV, of course. Good luck!
A:
If you are an academic, you can use the Enthought distribution free of charge. It comes with its own installer and handles installation for you. This will definitely be easier than installing matplotlib etc. from scratch on your own. There is no requirement for admin access on the installation machine because the distribution provides its own Python binaries. I've used it and found it simple and convenient.
A:
I'd personally go for Sage on the basis of price. The main issue you will need to contend with is making sure you use your python install to access your libraries, regardless of the python suite you're using.
A:
python(x,y) is a free Python distribution similar to EPD (Enthought Python Distribution). While both include the basic standard libraries there are some differences, so you should find out which one is a better fit for your needs. One interesting aspect of EPD is that it recently adapted the Intel MKL library, so there might be performance advantages over both pythonxy and the standard numpy installer.
I don't know how these distributions work on a Unix box without root access, this is something you might just have to try out.
Sage on the other hand isn't focused on being a distribution (see the Wikipedia page), so you can't really compare it.
A:
SageMath is completely free (GPL compatible), and the first of the three main goals of the project is to be a self-contained distribution of open source math software, which is easy to install from source (or from a binary), despite its large size. You should be able to setup Sage or anything else in Sage (e.g., the web notebook) without needing root access.
A:
I use Sage on a daily basis. I'm a big fan, but I wouldn't recommend it if you're not prepared for lots of updating, tweaking, and configuring. It's not ready for prime time yet.
If you're willing to put in the effort to get it running and keep it running, the web notebook interface is amazing. I can't imagine that you would be able to get it running without root access though.
A:
You can use virtualenv to create your virtual isolated env wihtout any access and then call easy_install to install (and compiling if necessary) automatically all the libs you need in your current directory without admin rights.
Installing matplotlib with virtualenv
The only condition is to be able to run virtual env, given that you can't install anything. You will have to donwload it as a archive and call virtualenv.py manually.
| Enthought Python, Sage, or others (in Unix clusters) | I have access to a cluster of Unix machines, but they don't have the software I need (numpy, scipy, matplotlib, etc), so I have to install them by myself (I don't have root permissions, either, so commands like apt-get or yast don't work).
In the worst case, I will have to compile them all from source. Is there any better way to proceed? I've heard something about Enthought Python and Sage, but am not sure what is the best way to go.
Any suggestions?
| [
"EPD (Enthought Python Distribution) is great, but even for academics, you can only get the 32-bit version free of charge. If you intend to do anything ram-intensive, it's not really an option.\nEdit: This has since changed, and the 64-bit version is freely available for academic/educational use.\nOn the other han... | [
9,
6,
3,
3,
3,
1,
1
] | [] | [] | [
"numpy",
"python",
"scipy",
"unix"
] | stackoverflow_0002751058_numpy_python_scipy_unix.txt |
Q:
Python RTF Multi Column layout
Can anybody reccomend a way of generating a multi column RTF document with python, i was going to use PyRTF but i cant find any documentation on how to set up columns. i think i might need to edit the modules source any reccomendations?
A:
Managed to patch it up quite easily after a few technical difficulties
http://www.importsoul.net/python/pyrtf/
A:
PyRTF is abandonware and doesn't realy have anything in the way of documentation other than the examples. I don't know about columns, but it does support tables so you might be able to achieve the layout you want that way.
| Python RTF Multi Column layout | Can anybody reccomend a way of generating a multi column RTF document with python, i was going to use PyRTF but i cant find any documentation on how to set up columns. i think i might need to edit the modules source any reccomendations?
| [
"Managed to patch it up quite easily after a few technical difficulties\nhttp://www.importsoul.net/python/pyrtf/\n",
"PyRTF is abandonware and doesn't realy have anything in the way of documentation other than the examples. I don't know about columns, but it does support tables so you might be able to achieve the... | [
2,
1
] | [] | [] | [
"python",
"rtf"
] | stackoverflow_0003501068_python_rtf.txt |
Q:
Add one to a function call in python
What does the last line, return 1 + .... do ? How can you return 1 plus a function call?
Below is the assignments text:
These functions recursively count the number of instances of the key in the target string
def countSubStringMatchRecursive(target, key):
currentPosition = find(target, key)
if find(target, key) == -1:
return 0
else:
return 1 + countSubStringMatchRecursive(target[currentPosition+1:], key)
A:
The last line isn't returning "1 plus a function call", it is returning 1 + the return value of the function, which is either 0 or 1 depending on whether the condition has been met.
It is recursive, in that the return value from the function call will be 1 + the return value of another function call -- again, and again, and again, until find(target, key) == -1.
Think of it more like:
return 1 + ( 1 + (1 + (1 + (0))))
A:
Its best to think of this from the end case. Lets say you have 3 possible matches. The calls would like this,
countSubStringMatchRecursive(target, key)
(The find operation is not -1, so call again)
1 + countSubStringMatchRecursive(target, key)
(The find operation is not -1, so call again)
1 + countSubStringMatchRecursive(target, key)
In this end case, the find operation is -1, so this function returns a 0.
Return value at this level is now 1 + 0 = 1
Return value at this level is now 1 + 1 = 2
Return value at the topmost level is now 1 + 2 = 3
So as you can see, the 1+ function call is basically a way to keep track of the count.
A:
The code that you showed does this:
currentPosition = find(target, key)
if find(target, key) == -1:
when it should be doing this:
currentPosition = find(target, key)
if currentPosition == -1:
If your teacher actually wrote that code, it's time to change schools!
| Add one to a function call in python | What does the last line, return 1 + .... do ? How can you return 1 plus a function call?
Below is the assignments text:
These functions recursively count the number of instances of the key in the target string
def countSubStringMatchRecursive(target, key):
currentPosition = find(target, key)
if find(target, key) == -1:
return 0
else:
return 1 + countSubStringMatchRecursive(target[currentPosition+1:], key)
| [
"The last line isn't returning \"1 plus a function call\", it is returning 1 + the return value of the function, which is either 0 or 1 depending on whether the condition has been met.\nIt is recursive, in that the return value from the function call will be 1 + the return value of another function call -- again, a... | [
2,
1,
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0003507525_function_python.txt |
Q:
How can I discover classes in a specific package in python?
I have a package of plug-in style modules. It looks like this:
/Plugins
/Plugins/__init__.py
/Plugins/Plugin1.py
/Plugins/Plugin2.py
etc...
Each .py file contains a class that derives from PluginBaseClass. So I need to list every module in the Plugins package and then search for any classes that implement PluginBaseClass. Ideally I want to be able to do something like this:
for klass in iter_plugins(project.Plugins):
action = klass()
action.run()
I have seen some other answers out there, but my situation is different. I have an actual import to the base package (ie: import project.Plugins) and I need to find the classes after discovering the modules.
A:
Edit: here's a revised solution. I realised I was making a mistake while testing my previous one, and it doesn't really work the way you would expect. So here is a more complete solution:
import os
from imp import find_module
from types import ModuleType, ClassType
def iter_plugins(package):
"""Receives package (as a string) and, for all of its contained modules,
generates all classes that are subclasses of PluginBaseClass."""
# Despite the function name, "find_module" will find the package
# (the "filename" part of the return value will be None, in this case)
filename, path, description = find_module(package)
# dir(some_package) will not list the modules within the package,
# so we explicitly look for files. If you need to recursively descend
# a directory tree, you can adapt this to use os.walk instead of os.listdir
modules = sorted(set(i.partition('.')[0]
for i in os.listdir(path)
if i.endswith(('.py', '.pyc', '.pyo'))
and not i.startswith('__init__.py')))
pkg = __import__(package, fromlist=modules)
for m in modules:
module = getattr(pkg, m)
if type(module) == ModuleType:
for c in dir(module):
klass = getattr(module, c)
if (type(klass) == ClassType and
klass is not PluginBaseClass and
issubclass(klass, PluginBaseClass)):
yield klass
My previous solution was:
You could try something like:
from types import ModuleType
import Plugins
classes = []
for item in dir(Plugins):
module = getattr(Plugins, item)
# Get all (and only) modules in Plugins
if type(module) == ModuleType:
for c in dir(module):
klass = getattr(module, c)
if isinstance(klass, PluginBaseClass):
classes.append(klass)
Actually, even better, if you want some modularity:
from types import ModuleType
def iter_plugins(package):
# This assumes "package" is a package name.
# If it's the package itself, you can remove this __import__
pkg = __import__(package)
for item in dir(pkg):
module = getattr(pkg, item)
if type(module) == ModuleType:
for c in dir(module):
klass = getattr(module, c)
if issubclass(klass, PluginBaseClass):
yield klass
A:
You may (and probably should) define __all__ in __init__.py as a list of the submodules in your package; this is so that you support people doing from Plugins import *. If you have done so, you can iterate over the modules with
import Plugins
import sys
modules = { }
for module in Plugins.__all__:
__import__( module )
modules[ module ] = sys.modules[ module ]
# iterate over dir( module ) as above
The reason another answer posted here fails is that __import__ imports the lowest-level module, but returns the top-level one (see the docs). I don't know why.
A:
Scanning modules isn't good idea. If you need class registry you should look at metaclasses or use existing solutions like zope.interface.
Simple solution through metaclasses may look like that:
from functools import reduce
class DerivationRegistry(type):
def __init__(cls,name,bases,cls_dict):
type.__init__(cls,name,bases,cls_dict)
cls._subclasses = set()
for base in bases:
if isinstance(base,DerivationRegistry):
base._subclasses.add(cls)
def getSubclasses(cls):
return reduce( set.union,
( succ.getSubclasses() for succ in cls._subclasses if isinstance(succ,DerivationRegistry)),
cls._subclasses)
class Base(object):
__metaclass__ = DerivationRegistry
class Cls1(object):
pass
class Cls2(Base):
pass
class Cls3(Cls2,Cls1):
pass
class Cls4(Cls3):
pass
print(Base.getSubclasses())
A:
If you don't know what's going to be in Plugins ahead of time, you can get a list of python files in the package's directory, and import them like so:
# compute a list of modules in the Plugins package
import os
import Plugins
plugin_modules = [f[:-3] for f in os.listdir(os.path.dirname(Plugins.__file__))
if f.endswith('.py') and f != '__init__.py']
Sorry, that comprehension might be a mouthful for someone relatively new to python. Here's a more verbose version (might be easier to follow):
plugin_modules = []
package_path = Plugins.__file__
file_list = os.listdir(os.path.dirname(package_path))
for file_name in file_list:
if file_name.endswith('.py') and file_name != '__init__.py':
plugin_modules.append(file_name)
Then you can use __import__ to get the module:
# get the first one
plugin = __import__('Plugins.' + plugin_modules[0])
| How can I discover classes in a specific package in python? | I have a package of plug-in style modules. It looks like this:
/Plugins
/Plugins/__init__.py
/Plugins/Plugin1.py
/Plugins/Plugin2.py
etc...
Each .py file contains a class that derives from PluginBaseClass. So I need to list every module in the Plugins package and then search for any classes that implement PluginBaseClass. Ideally I want to be able to do something like this:
for klass in iter_plugins(project.Plugins):
action = klass()
action.run()
I have seen some other answers out there, but my situation is different. I have an actual import to the base package (ie: import project.Plugins) and I need to find the classes after discovering the modules.
| [
"Edit: here's a revised solution. I realised I was making a mistake while testing my previous one, and it doesn't really work the way you would expect. So here is a more complete solution:\nimport os\nfrom imp import find_module\nfrom types import ModuleType, ClassType\n\ndef iter_plugins(package):\n \"\"\"Recei... | [
7,
6,
2,
1
] | [] | [] | [
"python",
"reflection"
] | stackoverflow_0003507125_python_reflection.txt |
Q:
Python and C++ integration. Python prints string as multiple lines
I'm trying to write a program in python to run a program in C++. It wasn't working right, so I made the most basic version of each I could.
The C++ program merely takes in a string from stdin, and then prints it out.
The Python code is written as follows:
import popen2, string, StringIO
fin, fout = popen2.popen2("PyTest")
msg = ur"Hello, world!"
print msg
fout.write(msg)
print fin.readline()
The output, however looks like this:
Hello, world!
Hello,
The problem I keep seeing is that spaces seem to break apart the string, even though it is a string literal. I'm not really sure what to do here. Any suggestions?
A:
In C++, std::cin >> mystring uses spaces as separators. Use std::getline instead if you want to gobble up a whole line at a time.
| Python and C++ integration. Python prints string as multiple lines | I'm trying to write a program in python to run a program in C++. It wasn't working right, so I made the most basic version of each I could.
The C++ program merely takes in a string from stdin, and then prints it out.
The Python code is written as follows:
import popen2, string, StringIO
fin, fout = popen2.popen2("PyTest")
msg = ur"Hello, world!"
print msg
fout.write(msg)
print fin.readline()
The output, however looks like this:
Hello, world!
Hello,
The problem I keep seeing is that spaces seem to break apart the string, even though it is a string literal. I'm not really sure what to do here. Any suggestions?
| [
"In C++, std::cin >> mystring uses spaces as separators. Use std::getline instead if you want to gobble up a whole line at a time.\n"
] | [
2
] | [] | [] | [
"popen",
"python",
"stdio",
"string",
"whitespace"
] | stackoverflow_0003506850_popen_python_stdio_string_whitespace.txt |
Q:
Are there frameworks for Jython or JRuby, or is it you can run a py or ruby app on the JVM?
Are there specific frameworks for Jython or JRuby, or is it you can run a py or ruby app on the JVM?
i.e. you take your python django app, and you can run in on tomcat using jython?
Sorry little confused.
A:
JRuby 1.5.X is compatible with Ruby 1.8.7, and pretty much anything you write in Ruby will work in JRuby. This includes applications written in frameworks such as Ruby on Rails, which can be converted to a war file and deployed to Tomcat. In fact the NetBeans IDE comes with Ruby on Rails support and by default you're using JRuby. This makes it easy if you're just getting started with the language and/or the framework.
A:
I think you're right. You can run django framework python in jython, which will run on the JVM, so I think you're in good shape.
http://www.infoq.com/news/2009/09/state-of-python-on-the-jvm has a lot more details that may help you with specific ways to do this.
| Are there frameworks for Jython or JRuby, or is it you can run a py or ruby app on the JVM? | Are there specific frameworks for Jython or JRuby, or is it you can run a py or ruby app on the JVM?
i.e. you take your python django app, and you can run in on tomcat using jython?
Sorry little confused.
| [
"JRuby 1.5.X is compatible with Ruby 1.8.7, and pretty much anything you write in Ruby will work in JRuby. This includes applications written in frameworks such as Ruby on Rails, which can be converted to a war file and deployed to Tomcat. In fact the NetBeans IDE comes with Ruby on Rails support and by default you... | [
2,
1
] | [] | [] | [
"java",
"jruby",
"jvm",
"jython",
"python"
] | stackoverflow_0003322164_java_jruby_jvm_jython_python.txt |
Q:
Controlling the instantiation of python object
My question does not really have much to do with sqlalchemy but rather with pure python.
I'd like to control the instantiation of sqlalchemy Model instances. This is a snippet from my code:
class Tag(db.Model):
__tablename__ = 'tags'
query_class = TagQuery
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), unique=True, nullable=False)
def __init__(self, name):
self.name = name
I want to achieve that whenever an entry is instantiated (Tag('django')) that a new instance should be created only if there is not yet another tag with the name django inside the database. Otherwise, instead of initializing a new object, a reference to the already existent row inside the database should be returned by (Tag('django')).
As of now I am ensuring the uniqueness of tags inside the Post Model:
class Post(db.Model):
# ...
# code code code
# ...
def _set_tags(self, taglist):
"""Associate tags with this entry. The taglist is expected to be already
normalized without duplicates."""
# Remove all previous tags
self._tags = []
for tag_name in taglist:
exists = Tag.query.filter(Tag.name==tag_name).first()
# Only add tags to the database that don't exist yet
# TODO: Put this in the init method of Tag (if possible)
if not exists:
self._tags.append(Tag(tag_name))
else:
self._tags.append(exists)
It does its job but still I'd like to know how to ensure the uniqueness of tags inside the Tag class itself so that I could write the _set_tags method like this:
def _set_tags(self, taglist):
# Remove all previous tags
self._tags = []
for tag_name in taglist:
self._tags.append(Tag(tag_name))
While writing this question and testing I learned that I need to use the __new__ method. This is what I've come up with (it even passes the unit tests and I didn't forget to change the _set_tags method):
class Tag(db.Model):
__tablename__ = 'tags'
query_class = TagQuery
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), unique=True, nullable=False)
def __new__(cls, *args, **kwargs):
"""Only add tags to the database that don't exist yet. If tag already
exists return a reference to the tag otherwise a new instance"""
exists = Tag.query.filter(Tag.name==args[0]).first() if args else None
if exists:
return exists
else:
return super(Tag, cls).__new__(cls, *args, **kwargs)
What bothers me are two things:
First: I get a warning:
DeprecationWarning: object.__new__() takes no parameters
Second: When I write it like so I get errors (I also tried to rename the paramater name to n but it did not change anything) :
def __new__(cls, name):
"""Only add tags to the database that don't exist yet. If tag already
exists return a reference to the tag otherwise a new instance"""
exists = Tag.query.filter(Tag.name==name).first()
if exists:
return exists
else:
return super(Tag, cls).__new__(cls, name)
Errors (or similar):
TypeError: __new__() takes exactly 2 arguments (1 given)
I hope you can help me!
A:
I use class method for that.
class Tag(Declarative):
...
@classmethod
def get(cls, tag_name):
tag = cls.query.filter(cls.name == tag_name).first()
if not tag:
tag = cls(tag_name)
return tag
And then
def _set_tags(self, taglist):
self._tags = []
for tag_name in taglist:
self._tags.append(Tag.get(tag_name))
As for __new__, you should not confuse it with __init__. It is expected to be called w/out args, so even if your own constructor asks for some, you should not pass them to super/object unless you know that your super needs them. Typical invocation would be:
def __new__(cls, name=None):
tag = cls.query.filter(cls.name == tag_name).first()
if not tag:
tag = object.__new__(cls)
return tag
However this will not work as expected in your case, since it calls __init__ automatically if __new__ returns instance of cls. You would need to use metaclass or add some checks in __init__.
A:
Don't embed this within the class itself.
Option 1. Create a factory that has the pre-existing pool of objects.
tag_pool = {}
def makeTag( name ):
if name not in tag_pool:
tag_pool[name]= Tag(name)
return tag_pool[name]
Life's much simpler.
tag= makeTag( 'django' )
This will create the item if necessary.
Option 2. Define a "get_or_create" version of the makeTag function. This will query the database. If the item is found, return the object. If no item is found, create it, insert it and return it.
A:
Given the OP's latest error msg:
TypeError: __new__() takes exactly 2 arguments (1 given)
it seems that somewhere the class is getting instantiated without the name parameter, i.e. just Tag(). The traceback for that exception should tell you where that "somewhere" is (but we're not shown it, so that's how far as we can go;-).
That being said, I agree with other answers that a factory function (possibly nicely dressed up as a classmethod -- making factories is one of the best uses of classmethod, after all;-) is the way to go, avoiding the complication that __new__ entails (such as forcing __init__ to find out whether the object's already initialized to avoid re-initializing it!-).
| Controlling the instantiation of python object | My question does not really have much to do with sqlalchemy but rather with pure python.
I'd like to control the instantiation of sqlalchemy Model instances. This is a snippet from my code:
class Tag(db.Model):
__tablename__ = 'tags'
query_class = TagQuery
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), unique=True, nullable=False)
def __init__(self, name):
self.name = name
I want to achieve that whenever an entry is instantiated (Tag('django')) that a new instance should be created only if there is not yet another tag with the name django inside the database. Otherwise, instead of initializing a new object, a reference to the already existent row inside the database should be returned by (Tag('django')).
As of now I am ensuring the uniqueness of tags inside the Post Model:
class Post(db.Model):
# ...
# code code code
# ...
def _set_tags(self, taglist):
"""Associate tags with this entry. The taglist is expected to be already
normalized without duplicates."""
# Remove all previous tags
self._tags = []
for tag_name in taglist:
exists = Tag.query.filter(Tag.name==tag_name).first()
# Only add tags to the database that don't exist yet
# TODO: Put this in the init method of Tag (if possible)
if not exists:
self._tags.append(Tag(tag_name))
else:
self._tags.append(exists)
It does its job but still I'd like to know how to ensure the uniqueness of tags inside the Tag class itself so that I could write the _set_tags method like this:
def _set_tags(self, taglist):
# Remove all previous tags
self._tags = []
for tag_name in taglist:
self._tags.append(Tag(tag_name))
While writing this question and testing I learned that I need to use the __new__ method. This is what I've come up with (it even passes the unit tests and I didn't forget to change the _set_tags method):
class Tag(db.Model):
__tablename__ = 'tags'
query_class = TagQuery
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), unique=True, nullable=False)
def __new__(cls, *args, **kwargs):
"""Only add tags to the database that don't exist yet. If tag already
exists return a reference to the tag otherwise a new instance"""
exists = Tag.query.filter(Tag.name==args[0]).first() if args else None
if exists:
return exists
else:
return super(Tag, cls).__new__(cls, *args, **kwargs)
What bothers me are two things:
First: I get a warning:
DeprecationWarning: object.__new__() takes no parameters
Second: When I write it like so I get errors (I also tried to rename the paramater name to n but it did not change anything) :
def __new__(cls, name):
"""Only add tags to the database that don't exist yet. If tag already
exists return a reference to the tag otherwise a new instance"""
exists = Tag.query.filter(Tag.name==name).first()
if exists:
return exists
else:
return super(Tag, cls).__new__(cls, name)
Errors (or similar):
TypeError: __new__() takes exactly 2 arguments (1 given)
I hope you can help me!
| [
"I use class method for that.\nclass Tag(Declarative):\n ...\n @classmethod\n def get(cls, tag_name):\n tag = cls.query.filter(cls.name == tag_name).first()\n if not tag:\n tag = cls(tag_name)\n return tag\n\nAnd then \ndef _set_tags(self, taglist):\n self._tags = []\n ... | [
3,
2,
1
] | [] | [] | [
"metaprogramming",
"python",
"sqlalchemy"
] | stackoverflow_0003506498_metaprogramming_python_sqlalchemy.txt |
Q:
Paragraph translation in Python/Django
I translated a site using django i18n, I have no problems for menus, little paragraph, etc..
The thing I dont understand is for translating big paragraph. On my site, the admin can write some news by administration page, but he wants them in differents languages.
I can imagine some methods to do that :
one field per langage, but it will be difficult to manage with severals languages (for example news table has title and content, we will have 4 fields ? title_en title_fr content_en content_fr ?
update the .po file for each new news ?
the real solution ?
What is the best solution for that ?
Thanks ! (sorry for my english)
A:
I'm not 100% sure what you're asking for, but it sounds like you have a model called News that you want to be multilingual aware.
There is a page on the Django wiki that covers some differing approaches to the problem of storing multilingual content in models, including the one you describe of having a field for each language in the model. It also links to a number of different Django apps that attempt to solve the problem.
Based on my experience, I'd take a look at django-datatrans which seems to me to be best-of-breed both in it's approach (one object per language) and feature set.
| Paragraph translation in Python/Django | I translated a site using django i18n, I have no problems for menus, little paragraph, etc..
The thing I dont understand is for translating big paragraph. On my site, the admin can write some news by administration page, but he wants them in differents languages.
I can imagine some methods to do that :
one field per langage, but it will be difficult to manage with severals languages (for example news table has title and content, we will have 4 fields ? title_en title_fr content_en content_fr ?
update the .po file for each new news ?
the real solution ?
What is the best solution for that ?
Thanks ! (sorry for my english)
| [
"I'm not 100% sure what you're asking for, but it sounds like you have a model called News that you want to be multilingual aware.\nThere is a page on the Django wiki that covers some differing approaches to the problem of storing multilingual content in models, including the one you describe of having a field for ... | [
0
] | [] | [] | [
"django",
"internationalization",
"python"
] | stackoverflow_0003507526_django_internationalization_python.txt |
Q:
Trouble Updating Label Text
Environment:
Built interface using Glade3.
Backend is written in Python using the GTK+ Builder library.
-
Although I know the method I need to use to update a label's text (label.set_text("string")), I'm having trouble obtaining the label object in the python code.
Here's what my code looks like:
#!/usr/bin/python
# Filename: HelloPython.py
# Author: Andrew Hefley Carpenter
# Date: 18 August 2010
import sys
import gtk
class HelloPython:
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("HelloPython.xml")
self.window = builder.get_object("window")
builder.connect_signals(self)
def on_button1_clicked(self, widget):
print "Hello World!"
widget.set_label("Hello World!")
#I'd like to update
if __name__ == "__main__":
editor = HelloPython()
editor.window.show()
gtk.main()
End goal: I want to update "Object X" using it's set_text method after the callback to "Object Y" (in this case button1) as handled by "on_button1_clicked"
A:
The widget parameter to on_button1_clicked is a gtk.Button, not a gtk.Label. gtk.Button has a convenience api method called set_label().
This only works if the child of Gtk.Button is a gtk.Label. This is the default when creating a new button in Glade-3, but if you've changed the contents of the button, this will not work and you'll need a reference to the gtk.Label widget itself.
EDIT (code to update the label):
class HelloPython:
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("HelloPython.xml")
self.window = builder.get_object("window")
self.label = builder.get_object("label1") # get reference to the label
builder.connect_signals(self)
def on_button1_clicked(self, widget):
#widget.set_label("Hello World!") this would set the button's text
self.label.set_text("Hello World!") # this sets the label's text
| Trouble Updating Label Text | Environment:
Built interface using Glade3.
Backend is written in Python using the GTK+ Builder library.
-
Although I know the method I need to use to update a label's text (label.set_text("string")), I'm having trouble obtaining the label object in the python code.
Here's what my code looks like:
#!/usr/bin/python
# Filename: HelloPython.py
# Author: Andrew Hefley Carpenter
# Date: 18 August 2010
import sys
import gtk
class HelloPython:
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("HelloPython.xml")
self.window = builder.get_object("window")
builder.connect_signals(self)
def on_button1_clicked(self, widget):
print "Hello World!"
widget.set_label("Hello World!")
#I'd like to update
if __name__ == "__main__":
editor = HelloPython()
editor.window.show()
gtk.main()
End goal: I want to update "Object X" using it's set_text method after the callback to "Object Y" (in this case button1) as handled by "on_button1_clicked"
| [
"The widget parameter to on_button1_clicked is a gtk.Button, not a gtk.Label. gtk.Button has a convenience api method called set_label().\nThis only works if the child of Gtk.Button is a gtk.Label. This is the default when creating a new button in Glade-3, but if you've changed the contents of the button, this will... | [
3
] | [] | [] | [
"gtk",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0003508075_gtk_pygtk_python_user_interface.txt |
Q:
I have a series of python modules I would like to put into a package, how can I do this?
I have a series of python modules I would like to put into a package. I would like to set it up such that anyone interested can just download it and install it (on unix). How can I do this?
A:
You should use distutils/setuptools to create egg and PyPI to distribute your package.
See according tutorials on packaging and uploading to PyPI:
http://diveintopython3.org/packaging.html
http://wiki.python.org/moin/CheeseShopTutorial
| I have a series of python modules I would like to put into a package, how can I do this? | I have a series of python modules I would like to put into a package. I would like to set it up such that anyone interested can just download it and install it (on unix). How can I do this?
| [
"You should use distutils/setuptools to create egg and PyPI to distribute your package.\nSee according tutorials on packaging and uploading to PyPI:\nhttp://diveintopython3.org/packaging.html\nhttp://wiki.python.org/moin/CheeseShopTutorial\n"
] | [
1
] | [] | [] | [
"module",
"package",
"python"
] | stackoverflow_0003508103_module_package_python.txt |
Q:
How can I know if the user is connected to the local machine via ssh in my python script?
How can I know if the user is connected to the local machine via ssh in my python script?
A:
You can use the os module to check for the existence of the environment variable SSH_CONNECTION.
>>> import os
>>> using_ssh = 'SSH_CONNECTION' in os.environ
A:
Am I correct in assuming you're running your script on some sort of UNIX/Linux system? If so, you can just type "users" on the command-line, and it will show you the currently logged in users.
Also, if you call the "lastlog" command, that will show you all the users on the system and the last time they all logged in to the machine.
A:
Check any of the SSH variables SSH_CONNECTION, SSH_CLIENT, or SSH_TTY. However, these can be unset by the user.
Check the output of who am i. It will end with the remote system identification in brackets if you are connected remotely. Make sure to handle x-term sessions which will have a colon (:) in the remote system id.
| How can I know if the user is connected to the local machine via ssh in my python script? | How can I know if the user is connected to the local machine via ssh in my python script?
| [
"You can use the os module to check for the existence of the environment variable SSH_CONNECTION.\n>>> import os\n>>> using_ssh = 'SSH_CONNECTION' in os.environ\n\n",
"Am I correct in assuming you're running your script on some sort of UNIX/Linux system? If so, you can just type \"users\" on the command-line, an... | [
6,
0,
0
] | [] | [] | [
"python",
"ssh"
] | stackoverflow_0003507980_python_ssh.txt |
Q:
Recommended language for multithreaded data work
Right now, I use a combination of Python and R for all of my data processing needs. However, some of my datasets are incredibly large and would benefit strongly from multithreaded processing.
For example, if there are two steps that each have to performed on a set of several millions of data points, I would like to be able to start the second step while the first step is still being run, using the part of the data that has already been processed through the first step.
From my understanding, neither Python nor R is the ideal language for this type of work (at least, I don't know how to implement it in either language). What would be the best language/implementation for this type of data processing?
A:
It is possible to do this in Python using the multiprocessing module -- this spawns multiple processes instead of threads, which bypasses the GIL and hence allows true concurrency.
That is not to say that Python is the 'best' language for this job; that's a subjective point which can be argued over. But it is certainly capable of it.
EDIT: Yes, there are several ways to share data between processes. Pipes are the simplest; they are sort-of file-like handles which one process can write to and then another can read from. Straight from the docs:
from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join()
You could for instance have one process performing the first step and sending the results down a pipe to another process for the second step.
A:
It is pretty easy to do multiprocessing with R (or definitely not harder than in Python); check out multicore package and other listed here.
A:
I find that using R with the foreach package is really an easy way to use multithreading in your code. Use the doMC or the doMPI package as the parallel back-end if you have a UNIX-alike or windows respectively. The vignette should get you going fairly quickly. This method is mostly best for parallelizing for loops, and i find that using 7 of the 8 cores on my machine usually give nearly a sixfold speed increase. I'm not sure that you can start a second process based on results of the first, but it is worth a quick look.
Good luck. Sorry that I am a new user and can only post one link, or I would have linked all of the other pages as well.
A:
On the Python side, your best bet is probably to separate the two steps in two different processes. There are a couple of modules that help you to achieve that. You would couple the two processes through pipes. In order to pass arbitrary data through the pipe, you need to serialize and deserialize it. The pickle module would be a good candidate for this.
If you want to jump ship, languages like Erlang, Haskell, Scala or Clojure have probably the concurrency features you are looking for, but I don't know how well they would integrate with R or some other statistical package that suits you.
A:
If I remember correctly (but I might be wrong here) one of the main purposes of Ada95 was parallel processing. Funny language, that was.
Jokes aside I'm not quite sure how good performance wise it would be (but seeing you are using Python now then it shouldn't be that bad) but I'd suggest Java since the basics of multithreading are quite simple there (but making a well written, complex multithreaded application is rather hard). Heard the Concurrency library is also quite nice, I haven't tried it out myself yet, though.
A:
My experiences with Java multi-threading have been very positive, although it does take a lot of getting used to. At the end of the day, the biggest problem wasn't the syntax or the java features but the different mindset you need to develop multi-threaded code.
If you're using eclipse there's also a profiling suite that's very helpful in debugging and optimisation. Causes a rather big performance hit though :)
| Recommended language for multithreaded data work | Right now, I use a combination of Python and R for all of my data processing needs. However, some of my datasets are incredibly large and would benefit strongly from multithreaded processing.
For example, if there are two steps that each have to performed on a set of several millions of data points, I would like to be able to start the second step while the first step is still being run, using the part of the data that has already been processed through the first step.
From my understanding, neither Python nor R is the ideal language for this type of work (at least, I don't know how to implement it in either language). What would be the best language/implementation for this type of data processing?
| [
"It is possible to do this in Python using the multiprocessing module -- this spawns multiple processes instead of threads, which bypasses the GIL and hence allows true concurrency.\nThat is not to say that Python is the 'best' language for this job; that's a subjective point which can be argued over. But it is cer... | [
6,
5,
3,
1,
0,
0
] | [] | [] | [
"multithreading",
"python",
"r"
] | stackoverflow_0003507451_multithreading_python_r.txt |
Q:
Break/Decompose complex and compound sentences in nltk
Is there a way to decompose complex sentences into simple sentences in nltk or other natural language processing libraries?
For example:
The park is so wonderful when the sun is setting and a cool breeze is blowing ==> The sun is setting. a cool breeze is blowing. The park is so wonderful.
A:
This is much more complicated than it seems, so you're unlikely to find a perfectly clean method.
However, using the English parser in OpenNLP, I can take your example sentence and get a following grammar tree:
(S
(NP (DT The) (NN park))
(VP
(VBZ is)
(ADJP (RB so) (JJ wonderful))
(SBAR
(WHADVP (WRB when))
(S
(S (NP (DT the) (NN sun)) (VP (VBZ is) (VP (VBG setting))))
(CC and)
(S
(NP (DT a) (JJ cool) (NN breeze))
(VP (VBZ is) (VP (VBG blowing)))))))
(. .)))
From there, you can pick it apart as you like. You can get your sub-clauses by extracting the top-level (NP *)(VP *) minus the (SBAR *) section. And then you could split the conjunction inside the (SBAR *) into the other two statements.
Note, the OpenNLP parser is trained using the Penn Treebank corpus. I obtained a pretty accurate parsing on your example sentence, but the parser isn't perfect and can be wildly wrong on other sentences. Look here for an explanation of its tags. It assumes you already have some basic understanding of linguistics and English grammar.
Edit: Btw, this is how I access OpenNLP from Python. This assumes you have the OpenNLP jar and model files in a opennlp-tools-1.4.3 folder.
import os, sys
from subprocess import Popen, PIPE
import nltk
BP = os.path.dirname(os.path.abspath(__file__))
CP = "%(BP)s/opennlp-tools-1.4.3.jar:%(BP)s/opennlp-tools-1.4.3/lib/maxent-2.5.2.jar:%(BP)s/opennlp-tools-1.4.3/lib/jwnl-1.3.3.jar:%(BP)s/opennlp-tools-1.4.3/lib/trove.jar" % dict(BP=BP)
cmd = "java -cp %(CP)s -Xmx1024m opennlp.tools.lang.english.TreebankParser -k 1 -d %(BP)s/opennlp.models/english/parser" % dict(CP=CP, BP=BP)
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
stdin, stdout, stderr = (p.stdin, p.stdout, p.stderr)
text = "This is my sample sentence."
stdin.write('%s\n' % text)
ret = stdout.readline()
ret = ret.split(' ')
prob = float(ret[1])
tree = nltk.Tree.parse(' '.join(ret[2:]))
| Break/Decompose complex and compound sentences in nltk | Is there a way to decompose complex sentences into simple sentences in nltk or other natural language processing libraries?
For example:
The park is so wonderful when the sun is setting and a cool breeze is blowing ==> The sun is setting. a cool breeze is blowing. The park is so wonderful.
| [
"This is much more complicated than it seems, so you're unlikely to find a perfectly clean method.\nHowever, using the English parser in OpenNLP, I can take your example sentence and get a following grammar tree:\n (S\n (NP (DT The) (NN park))\n (VP\n (VBZ is)\n (ADJP (RB so) (JJ wonderful))\n ... | [
12
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0003501436_nlp_nltk_python.txt |
Q:
Start a script on a remote machine through ssh with python - but in reverse?
Here's what I need to do:
The user is on a remote machine and connects to a server via ssh. He runs a python script on the server. The script running on the server starts a script on the user's remote machine as a subprocess and opens a pipe to it for communication.
First, is this at all possible?
Second, is this possible in such a way that the user does not need to do anything fancy, like open up a reverse ssh tunnel? If they do have to open up a reverse ssh tunnel, can I figure out which port they are using?
A:
First, is this at all possible?
With simple user --SSH--> server - no, its not.
is this possible in such a way that the user does not need to do anything fancy
User will have to run sshd on his machine, add a user for your server and somehow let you to connect to it, bypassing NAT if any. So no, there is no such way with SSH.
I'd go with client-side application. Give script to user and let him run the script instead of SSH'ing. If you need to communicate with server, you can use something like paramiko on client side to connect to server from script. Then, script can launch other applications on client's computer based on data it receives from server.
| Start a script on a remote machine through ssh with python - but in reverse? | Here's what I need to do:
The user is on a remote machine and connects to a server via ssh. He runs a python script on the server. The script running on the server starts a script on the user's remote machine as a subprocess and opens a pipe to it for communication.
First, is this at all possible?
Second, is this possible in such a way that the user does not need to do anything fancy, like open up a reverse ssh tunnel? If they do have to open up a reverse ssh tunnel, can I figure out which port they are using?
| [
"\nFirst, is this at all possible?\n\nWith simple user --SSH--> server - no, its not.\n\nis this possible in such a way that the user does not need to do anything fancy\n\nUser will have to run sshd on his machine, add a user for your server and somehow let you to connect to it, bypassing NAT if any. So no, there i... | [
4
] | [] | [] | [
"python",
"ssh",
"subprocess"
] | stackoverflow_0003508164_python_ssh_subprocess.txt |
Q:
How do I find only whole words using re.search?
I have a list of words built from different HTML pages. Instead of writing rule after rule to strip out different elements, I am trying to go through the list and say if it's not a full word with only alpha characters, just move on. This is not working.
for w in words:
if re.search('\b[a-zA-Z]\b', w) == None:
continue
I am horrible with regular expressions (if you can't already tell!), so I could use some help. How would I write it so it checks each w to make sure it only have a-zA-Z in it?
A:
You're almost there. You just have to tell your search to match an entire string of 1 or more characters.
for w in words:
if re.search('^[a-zA-Z]+$', w) == None:
continue
Another solution (for this specific case atleast) would be to use isalpha();
for w in words:
if not w.isalpha():
continue
| How do I find only whole words using re.search? | I have a list of words built from different HTML pages. Instead of writing rule after rule to strip out different elements, I am trying to go through the list and say if it's not a full word with only alpha characters, just move on. This is not working.
for w in words:
if re.search('\b[a-zA-Z]\b', w) == None:
continue
I am horrible with regular expressions (if you can't already tell!), so I could use some help. How would I write it so it checks each w to make sure it only have a-zA-Z in it?
| [
"You're almost there. You just have to tell your search to match an entire string of 1 or more characters.\nfor w in words:\n if re.search('^[a-zA-Z]+$', w) == None:\n continue\n\nAnother solution (for this specific case atleast) would be to use isalpha();\nfor w in words:\n if not w.isalpha():\n ... | [
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003508283_python_regex.txt |
Q:
XMPP chat: accessing contacts' status messages with xmppPy's Roster
I'm trying to access my google talk contacts' custom status messages with xmpppy. I'm made it this far:
import xmpp
import sys
userID = 'myname@gmail.com'
password = 'mypassword'
ressource = 'Script'
jid = xmpp.protocol.JID(userID)
jabber = xmpp.Client(jid.getDomain(), debug=[])
connection = jabber.connect(('talk.google.com',5222))
auth = jabber.auth(jid.getNode(), password, ressource)
jabber.sendInitPresence(requestRoster=1)
myroster = jabber.getRoster()
the roster object myroster now contains my contacts, but the custom status message is not included.
myroster.getStatus('oneofmyfriends@gmail.com')
returns None
looking at the 'raw roster', I can see that the resources dictionary is empty
u'oneofmyfriends@googlemail.com': {'ask': None, 'resources': {}, 'name': u'Some Name', 'groups': [], 'subscription': u'both'}
The weird thing is that I have gotten this to work today, but I the code might have been slightly different, but I can't figure out what exactly I did differently...
Any help would be greatly appreciated!
Cheers,
Martin
A:
Here's one thing I've found, which was not clear to me when I first started working with xmpp. Friending is two-way.
Using presence stanzas
(a) You can "subscribe" to your friend, and your friend can return "subscribed".
(b) Your friend can "subscribe" to you, and you can return "subscribed".
Your friend will be in your roster if either (a) or (b) has happened.
You will be in your friends roster if either (a) or (b) has happened.
However...
You will not see their status unless you "subscribe" to your friend - (a) must happen
They will not see your status unless they "subscribe" to you - (b) must happen.
Most XMPP clients (pidgin, trillian, etc) will automatically make you send "subscribe" back to your friend when you send them "subscribed" (after they've sent you "subscribe"). XMPPPY does not do this out of the box. You must code it to do this.
This could explain why you weren't seeing status. Or if this doesn't cover your situation, it might be informative to someone else.
A:
It's a timing issue. Add a handler with:
jabber.RegisterHandler('presence', myPresenceHandler)
def myPresenceHandler(self, con, event):
fromjid = event.getFrom().getStripped()
status = myroster.getStatus(fromjid)
BEFORE connecting. Then make sure to call jabber.Process() in a loop. The issue is that with your code, you'll sometimes receive presence stanzas before you look at the roster object, and sometimes after.
| XMPP chat: accessing contacts' status messages with xmppPy's Roster | I'm trying to access my google talk contacts' custom status messages with xmpppy. I'm made it this far:
import xmpp
import sys
userID = 'myname@gmail.com'
password = 'mypassword'
ressource = 'Script'
jid = xmpp.protocol.JID(userID)
jabber = xmpp.Client(jid.getDomain(), debug=[])
connection = jabber.connect(('talk.google.com',5222))
auth = jabber.auth(jid.getNode(), password, ressource)
jabber.sendInitPresence(requestRoster=1)
myroster = jabber.getRoster()
the roster object myroster now contains my contacts, but the custom status message is not included.
myroster.getStatus('oneofmyfriends@gmail.com')
returns None
looking at the 'raw roster', I can see that the resources dictionary is empty
u'oneofmyfriends@googlemail.com': {'ask': None, 'resources': {}, 'name': u'Some Name', 'groups': [], 'subscription': u'both'}
The weird thing is that I have gotten this to work today, but I the code might have been slightly different, but I can't figure out what exactly I did differently...
Any help would be greatly appreciated!
Cheers,
Martin
| [
"Here's one thing I've found, which was not clear to me when I first started working with xmpp. Friending is two-way. \nUsing presence stanzas\n(a) You can \"subscribe\" to your friend, and your friend can return \"subscribed\".\n(b) Your friend can \"subscribe\" to you, and you can return \"subscribed\".\nYour fri... | [
3,
2
] | [] | [] | [
"chat",
"google_talk",
"python",
"xmpp"
] | stackoverflow_0002381597_chat_google_talk_python_xmpp.txt |
Q:
PyGTK TreeColumns all exact duplicates
I wrote a simple PyGTK script to show some basic process information in a TreeView:
import gtk
import os
import pwd
import grp
class ProcParser:
"""
Parses the status file of a particular process
"""
def __init__(self, fname):
self.lines = map(lambda x: x[:-1], open(fname).readlines())
def get_by_val(self, val):
for line in self.lines:
if line.startswith(val):
return line.split()
return []
class Proc:
"""
A process in the /proc filesystem
This class uses a ProcParser to determine it's own information
"""
def __init__(self, pid):
self.pid = int(pid)
self.parser = ProcParser("/proc/{0}/status".format(self.pid))
self._from_file()
def _from_file(self):
self.uid = self.parser.get_by_val("Uid")[1]
self.gid = self.parser.get_by_val("Gid")[1]
self.name = self.parser.get_by_val("Name")[1]
self.user = pwd.getpwuid(int(self.uid)).pw_name
self.group = grp.getgrgid(int(self.gid)).gr_name
class ProcTree:
"A tree that displays all running processes"
def __init__(self):
self.view = gtk.ScrolledWindow()
self.store = gtk.ListStore(str, int, str, str)
self.tree = gtk.TreeView(self.store)
self.cells = [
gtk.CellRendererText(),
gtk.CellRendererText(),
gtk.CellRendererText(),
gtk.CellRendererText()
]
self.tvcols = [
gtk.TreeViewColumn("Name"),
gtk.TreeViewColumn("Pid"),
gtk.TreeViewColumn("User"),
gtk.TreeViewColumn("Group")
]
def __call__(self):
return self.view
def config(self):
for col, cell in zip(self.tvcols, self.cells):
col.pack_start(cell, True)
col.add_attribute(cell, "text", 0)
self.tree.append_column(col)
self._update_store()
self.view.add_with_viewport(self.tree)
def show(self):
self.tree.show()
self.view.show()
def _update_store(self):
self.store.clear()
for item in os.listdir("/proc"):
try: pwid = int(item)
except: continue
pr = Proc(pwid)
self.store.append((pr.name, int(pr.pid), pr.user, pr.group))
class Window:
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.proctree = ProcTree()
def config(self):
self.proctree.config()
self.window.add(self.proctree())
self.window.set_title("Process Viewer")
def show(self):
self.proctree.show()
self.window.show()
def run(self):
self.config()
self.show()
win = Window()
win.run()
gtk.main()
My issue is that all of the columns' values are the same.
Notes:
Apparently this is correlated with the first column (ie If I change the first column's data, then that's what all of the other data become)
(Will add more as suggestions are posted)
A:
for append on treview you should do
rendererText = gtk.CellRendererText()
tvcols = ["Name", "Pid", "User", "Group"]
for num, name in enumerate(tvcols):
column_name = gtk.TreeViewColumn(name ,rendererText, text=num)
self.tree.append_column(column_name)
| PyGTK TreeColumns all exact duplicates | I wrote a simple PyGTK script to show some basic process information in a TreeView:
import gtk
import os
import pwd
import grp
class ProcParser:
"""
Parses the status file of a particular process
"""
def __init__(self, fname):
self.lines = map(lambda x: x[:-1], open(fname).readlines())
def get_by_val(self, val):
for line in self.lines:
if line.startswith(val):
return line.split()
return []
class Proc:
"""
A process in the /proc filesystem
This class uses a ProcParser to determine it's own information
"""
def __init__(self, pid):
self.pid = int(pid)
self.parser = ProcParser("/proc/{0}/status".format(self.pid))
self._from_file()
def _from_file(self):
self.uid = self.parser.get_by_val("Uid")[1]
self.gid = self.parser.get_by_val("Gid")[1]
self.name = self.parser.get_by_val("Name")[1]
self.user = pwd.getpwuid(int(self.uid)).pw_name
self.group = grp.getgrgid(int(self.gid)).gr_name
class ProcTree:
"A tree that displays all running processes"
def __init__(self):
self.view = gtk.ScrolledWindow()
self.store = gtk.ListStore(str, int, str, str)
self.tree = gtk.TreeView(self.store)
self.cells = [
gtk.CellRendererText(),
gtk.CellRendererText(),
gtk.CellRendererText(),
gtk.CellRendererText()
]
self.tvcols = [
gtk.TreeViewColumn("Name"),
gtk.TreeViewColumn("Pid"),
gtk.TreeViewColumn("User"),
gtk.TreeViewColumn("Group")
]
def __call__(self):
return self.view
def config(self):
for col, cell in zip(self.tvcols, self.cells):
col.pack_start(cell, True)
col.add_attribute(cell, "text", 0)
self.tree.append_column(col)
self._update_store()
self.view.add_with_viewport(self.tree)
def show(self):
self.tree.show()
self.view.show()
def _update_store(self):
self.store.clear()
for item in os.listdir("/proc"):
try: pwid = int(item)
except: continue
pr = Proc(pwid)
self.store.append((pr.name, int(pr.pid), pr.user, pr.group))
class Window:
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.proctree = ProcTree()
def config(self):
self.proctree.config()
self.window.add(self.proctree())
self.window.set_title("Process Viewer")
def show(self):
self.proctree.show()
self.window.show()
def run(self):
self.config()
self.show()
win = Window()
win.run()
gtk.main()
My issue is that all of the columns' values are the same.
Notes:
Apparently this is correlated with the first column (ie If I change the first column's data, then that's what all of the other data become)
(Will add more as suggestions are posted)
| [
"for append on treview you should do\n rendererText = gtk.CellRendererText()\n tvcols = [\"Name\", \"Pid\", \"User\", \"Group\"]\n\n for num, name in enumerate(tvcols):\n column_name = gtk.TreeViewColumn(name ,rendererText, text=num)\n self.tree.append_column(column_name)\n\n"
] | [
4
] | [] | [] | [
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003505171_gtktreeview_pygtk_python.txt |
Q:
Regular Expression 'Split' function
I'm new to this site, and new to Python.
So I'm learning about Regular Expressions and I was working through Google's expamples
here.
I was doing one of the 'Search' examples but I changed the 'Search' to 'Split' and changed the search pattern a bit just to play with it, here's the line
print re.split(r'i', 'piiig')
(notice that there are 3 'i's in the text 'piiig')
The output only has 2 spaces where it's been split.
['p', '', '', 'gs']
Just wondering why this gives that output. This isn't a real life problem and has no relevance but I'm thinking I could run into this later on and want to know what's going on.
Anybody know what's going on???
A:
Your example might make more sense if you replace i with ,:
print re.split(r',', 'p,,,g')
In this case, there are four fields found by splitting on the comma, a 'p', a 'g', and two empty ones '' in the middle.
A:
split removes the instance it finds. The two blank strings are are the two empty strings between the is.
If you joined the array back together using i as a separator, you'd get the original string back.
piiig, in that respect is p- i - i - i -g (here I'm using a dash for the empty string)
A:
Think of it this way ... (in Java as I am not so good in python)
String Text = "piiig";
List<String> Spliteds = new ArrayList<String>();
String Match = "";
int I;
char c;
for (I = 0; I < Text.length; I++) {
c = Text.charAt(I);
if (c == 'i') {
Spliteds.add(Match);
Match = "";
} else {
Match += c;
}
}
if (Match.length != 0)
Spliteds.add(Match);
So when you run ...
At the end of each loop:
When: (I == 0) => c = 'p'; Match = "p"; Spliteds = {};
When: (I == 1) => c = 'i'; Match = ""; Spliteds = {"p"};
When: (I == 2) => c = 'i'; Match = ""; Spliteds = {"p", ""};
When: (I == 3) => c = 'i'; Match = ""; Spliteds = {"p", "", ""};
When: (I == 4) => c = 'g'; Match = "g"; Spliteds = {"p", "", ""};
At the end of the program:
(I == 4) => c = 'g'; Match = "g"; Spliteds = {"p", "", "", "g"};
The RegEx engine just simple find string between each 'i' and this include empty string between 'i' right after another 'i'.
Hope this helps.
| Regular Expression 'Split' function | I'm new to this site, and new to Python.
So I'm learning about Regular Expressions and I was working through Google's expamples
here.
I was doing one of the 'Search' examples but I changed the 'Search' to 'Split' and changed the search pattern a bit just to play with it, here's the line
print re.split(r'i', 'piiig')
(notice that there are 3 'i's in the text 'piiig')
The output only has 2 spaces where it's been split.
['p', '', '', 'gs']
Just wondering why this gives that output. This isn't a real life problem and has no relevance but I'm thinking I could run into this later on and want to know what's going on.
Anybody know what's going on???
| [
"Your example might make more sense if you replace i with ,:\nprint re.split(r',', 'p,,,g')\n\nIn this case, there are four fields found by splitting on the comma, a 'p', a 'g', and two empty ones '' in the middle.\n",
"split removes the instance it finds. The two blank strings are are the two empty strings betwe... | [
6,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003508898_python_regex.txt |
Q:
Python one-liner
I want a one-liner solution in Python of the following code, but how?
total = 0
for ob in self.oblist:
total += sum(v.amount for v in ob.anoutherob)
It returns the total value. I want it in a one-liner. How can I do it?
A:
There isn't any need to double up on the sum() calls:
total = sum(v.amount for ob in self.oblist for v in ob.anotherob)
A:
You can just collapse the for loop into another level of comprehension:
total = sum(sum(v.amount for v in ob.anotherob) for ob in self.oblist)
| Python one-liner | I want a one-liner solution in Python of the following code, but how?
total = 0
for ob in self.oblist:
total += sum(v.amount for v in ob.anoutherob)
It returns the total value. I want it in a one-liner. How can I do it?
| [
"There isn't any need to double up on the sum() calls:\ntotal = sum(v.amount for ob in self.oblist for v in ob.anotherob)\n\n",
"You can just collapse the for loop into another level of comprehension:\ntotal = sum(sum(v.amount for v in ob.anotherob) for ob in self.oblist)\n\n"
] | [
38,
7
] | [] | [] | [
"python",
"sum"
] | stackoverflow_0003508766_python_sum.txt |
Q:
Console colors (Windows)
Is it possible to print out things in different colors in Python for Windows? I already enabled ANSI.sys, but this does not seam to work.
I want to be able to print one line in red, and the next in green, etc.
A:
The WConio module should be all you need to accomplish this.
WConio.textbackground(color) sets the background color without changing the foreground. See below for the color constants.
WConio.textcolor(color) sets the foreground color without changing the background. See below for the color constants.
The constants it refers to are not actually listed on the page, but are at the top of the WConio.py file:
BLACK = 0
BLUE = 1
GREEN = 2
CYAN = 3
RED = 4
MAGENTA = 5
BROWN = 6
LIGHTGRAY = LIGHTGREY = 7
DARKGRAY = DARKGREY = 8
LIGHTBLUE = 9
LIGHTGREEN = 10
LIGHTCYAN = 11
LIGHTRED = 12
LIGHTMAGENTA = 13
YELLOW = 14
WHITE = 15
So a full call to set the text foreground colour to red would be:
WConio.textcolor(WConio.RED)
| Console colors (Windows) | Is it possible to print out things in different colors in Python for Windows? I already enabled ANSI.sys, but this does not seam to work.
I want to be able to print one line in red, and the next in green, etc.
| [
"The WConio module should be all you need to accomplish this.\n\nWConio.textbackground(color) sets the background color without changing the foreground. See below for the color constants.\nWConio.textcolor(color) sets the foreground color without changing the background. See below for the color constants.\n\nThe co... | [
2
] | [] | [] | [
"ansi_escape",
"ansicon",
"colors",
"python",
"windows"
] | stackoverflow_0003508906_ansi_escape_ansicon_colors_python_windows.txt |
Q:
handling python string or list dynamically
numberofrow,
its value is dynamically set in form field.
now since numberofrow is in multiple tables,
when i receive that variable from form,
if only one numerofrow, its a String, for ex. numberofrow = 01
if more than one numberofrow, its a list, for ex. numberofrow = [01, 02, 04]
Now how do i differentiate if its a list or string in my python code?
am thinking of using,
if type(numberofrow).__name__=='list':
#do this
else:
#do this
Thanks,
Sunny.
A:
For this purpose there is a build-in called isinstance. You can use it to check if an object is an instance of that class (and compared to your solution also super classes are considered in this test).
if isinstance(numberofrow, list):
# do this
else:
# do that
It's quite common to do something like isinstance(numberofrow, basestring). basestring is the super class of both string types in Python 2 - str and unicode - and the test will match both of them.
Alternatively, you can also provide a tuple of possible classes/types like isinstance(numberofrow, (list, tuple)). This test will succeed if the instance is either a instance of a list or a tuple.
A:
What framework are you using to get that value from the form? A sensible one would definitely provide a way to return always a list -- specifically, if the value has been entered just once, a one-item list (and possibly, if the value has not been entered at all, an empty list).
For example, with good old cgi, you'd use the getlist method of the FieldStorage instance -- form.getlist('numberofrow') instead of form.getvalue('numberofrow') which behaves as you describe, returning either a string or a list -- and that would solve all your problems much more simply and elegantly!
A:
You can do what you said, but a better way would be:
if isinstance(numberofrow, list):
# do this
else:
# do that
An alternative is to use the object as a string and change behavior when something goes wrong:
try:
validated = numberofrow.isdigit()
except AttributeError:
# must be a list?
# do something else
else:
# must be a string
# do the string thing
If it acts like a string then it doesn't matter if it is a string or not.
| handling python string or list dynamically | numberofrow,
its value is dynamically set in form field.
now since numberofrow is in multiple tables,
when i receive that variable from form,
if only one numerofrow, its a String, for ex. numberofrow = 01
if more than one numberofrow, its a list, for ex. numberofrow = [01, 02, 04]
Now how do i differentiate if its a list or string in my python code?
am thinking of using,
if type(numberofrow).__name__=='list':
#do this
else:
#do this
Thanks,
Sunny.
| [
"For this purpose there is a build-in called isinstance. You can use it to check if an object is an instance of that class (and compared to your solution also super classes are considered in this test).\nif isinstance(numberofrow, list):\n # do this\nelse:\n # do that\n\nIt's quite common to do something like... | [
6,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0003509150_python.txt |
Q:
Can deleting a django Model with a ManyToManyField create orphaned database rows?
If I have two classes A and B with a many to many relationship and I want to delete an instance of A, do I need to remove all of its related Bs first or will Django sort that out for me?
I obviously don't want to leave orphaned rows in the join table.
Does it make any difference if the ManyToMany field is declared on class A or B?
Does it make any difference if there are additional fields on a join class specified using the "through" parameter?
A:
If I have two classes A and B with a many to many relationship and I want to delete an instance of A, do I need to remove all of its related Bs first or will Django sort that out for me?
Short answer: Django will sort that out for you.
Does it make any difference if the ManyToMany field is declared on class A or B?
As far as I know, no, it does not make a difference.
Does it make any difference if there are additional fields on a join class specified using the "through" parameter?
I haven't tried this myself but I don't see why there should be a problem.
| Can deleting a django Model with a ManyToManyField create orphaned database rows? | If I have two classes A and B with a many to many relationship and I want to delete an instance of A, do I need to remove all of its related Bs first or will Django sort that out for me?
I obviously don't want to leave orphaned rows in the join table.
Does it make any difference if the ManyToMany field is declared on class A or B?
Does it make any difference if there are additional fields on a join class specified using the "through" parameter?
| [
"\nIf I have two classes A and B with a many to many relationship and I want to delete an instance of A, do I need to remove all of its related Bs first or will Django sort that out for me?\n\nShort answer: Django will sort that out for you.\n\nDoes it make any difference if the ManyToMany field is declared on clas... | [
2
] | [] | [] | [
"django",
"django_models",
"many_to_many",
"python"
] | stackoverflow_0003509275_django_django_models_many_to_many_python.txt |
Q:
Edit Windows 7 Registry in Python?
I have run into another problem with my current project. The program needs to values and keys periodically while running. Each time I attempt to edit the value, I get a code 5, Access Denied. How would I go about doing this so the values can be editied, but the user doesn't have to enter admin credentials to run the application?
I am using the _winreg module with Python 2.6 on Windows 7.
A:
If you want to edit something that is writable only with administrative privileges, you just have to run under admin privileges. Everything else would be a giant security hole.
| Edit Windows 7 Registry in Python? | I have run into another problem with my current project. The program needs to values and keys periodically while running. Each time I attempt to edit the value, I get a code 5, Access Denied. How would I go about doing this so the values can be editied, but the user doesn't have to enter admin credentials to run the application?
I am using the _winreg module with Python 2.6 on Windows 7.
| [
"If you want to edit something that is writable only with administrative privileges, you just have to run under admin privileges. Everything else would be a giant security hole.\n"
] | [
1
] | [] | [] | [
"access_denied",
"editing",
"python",
"registry",
"windows_7"
] | stackoverflow_0003509471_access_denied_editing_python_registry_windows_7.txt |
Q:
Python socket client-server application
I wrote two applictions which comunicate by socket. This is the code:
Server:
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("",9999))
server_socket.listen(5)
video = True
power = True
print "TCPServer Waiting for client on port 9999"
while 1:
client_socket,address = server_socket.accept()
print "I got a connection from ", address
while 1:
data = client_socket.recv(512)
if data == 'vc' & video == True:
data = 'You can connect to Video'
video = False
client_socket.send(data)
elif data == 'pc' & power == True:
data = 'You can connect to Power Switch'
power = False
client_socket.send(data)
else :
data = 'Device is in use - wait a few secconds'
client_socket.send(data)
Client:
import socket
import time
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 9999))
while 1:
data = ( 'Please vc or pc: ' )
time.sleep(5)
if data=='pc' | data=='vc':
print 'send to server: ' + data
time.sleep(5)
client_socket.send(data)
data = client_socket.recv(512)
print data
else:
print 'bad data - please try again'
print data
time.sleep(5)
I've just started my adventure with sockets and I have a problem. Why I don't see server response? I paste in code time.sleep() to stop the program and see rosponses, but those applications terminate after I wrote first message in client terminal and press enter. Please, help me.
I work on Windows 32bit. Python 2.6
A:
You don't send anything. I presume the line data = "Please vc or pc: is meant to get input from the user, but it just assigns the string to data. Then when you check if data == 'pc' | data == 'vc' the check fails so it prints "bad data".
Also do not use | in boolean expressions - use or and and. | and & will do bitwise manipulation - sometimes that will do the right thing, but other times it will bite you in the butt.
| Python socket client-server application | I wrote two applictions which comunicate by socket. This is the code:
Server:
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("",9999))
server_socket.listen(5)
video = True
power = True
print "TCPServer Waiting for client on port 9999"
while 1:
client_socket,address = server_socket.accept()
print "I got a connection from ", address
while 1:
data = client_socket.recv(512)
if data == 'vc' & video == True:
data = 'You can connect to Video'
video = False
client_socket.send(data)
elif data == 'pc' & power == True:
data = 'You can connect to Power Switch'
power = False
client_socket.send(data)
else :
data = 'Device is in use - wait a few secconds'
client_socket.send(data)
Client:
import socket
import time
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 9999))
while 1:
data = ( 'Please vc or pc: ' )
time.sleep(5)
if data=='pc' | data=='vc':
print 'send to server: ' + data
time.sleep(5)
client_socket.send(data)
data = client_socket.recv(512)
print data
else:
print 'bad data - please try again'
print data
time.sleep(5)
I've just started my adventure with sockets and I have a problem. Why I don't see server response? I paste in code time.sleep() to stop the program and see rosponses, but those applications terminate after I wrote first message in client terminal and press enter. Please, help me.
I work on Windows 32bit. Python 2.6
| [
"You don't send anything. I presume the line data = \"Please vc or pc: is meant to get input from the user, but it just assigns the string to data. Then when you check if data == 'pc' | data == 'vc' the check fails so it prints \"bad data\".\nAlso do not use | in boolean expressions - use or and and. | and & wil... | [
2
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003509539_python_sockets.txt |
Q:
Converting a list with many items into single item lines in python
I want to convert lines in a text file from this:
animal cat, mouse, dog, horse
numbers 22,45,124,87
to this:
animal cat
animal mouse
animal dog
animal horse
numbers 22
numbers 45
numbers 124
numbers 87
How would I do this conversion in python?
Thanks
A:
with open('thefile.txt') as fin:
with open('result.txt') as fou:
for line in fin:
key, values = line.split(None, 1)
vs = [x.strip() for x in values.split(',')]
for v in vs:
fou.write('%s %s\n' % (key, v))
A:
Use a collections.defaultdict.
You might want to search SO for similar questions.
A:
With zip you could do like this:
inp="""animal cat, mouse, dog, horse
numbers 22,45,124,87
"""
for line in inp.splitlines():
key,data = line.split(None,1)
print '\n'.join("%s%8s" % line
for line in zip([key.strip()] * (data.count(',')+1),
(item.strip() for item in data.split(','))))
| Converting a list with many items into single item lines in python | I want to convert lines in a text file from this:
animal cat, mouse, dog, horse
numbers 22,45,124,87
to this:
animal cat
animal mouse
animal dog
animal horse
numbers 22
numbers 45
numbers 124
numbers 87
How would I do this conversion in python?
Thanks
| [
"with open('thefile.txt') as fin:\n with open('result.txt') as fou:\n for line in fin:\n key, values = line.split(None, 1)\n vs = [x.strip() for x in values.split(',')]\n for v in vs:\n fou.write('%s %s\\n' % (key, v))\n\n",
"Use a collections.defaultdict.\nYou might want to searc... | [
4,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003508051_list_python.txt |
Q:
how can I put a process in background using django?
I tried os.system, os.spwanl, etc.. but it doesn't work well
I need to execute some background process from django application.
A:
Try to use celery. It was originally created for this purpose and also supports scheduling tasks.
A:
The subprocess module gives you much finer-grained control over spawning processes than afforded by os.system.
A:
I have used subprocess to spawn background processes from Django before. It may depend on your environment, but I had no issue using it with both modpython and modwsgi.
A:
I've used paramiko to put the process in background for localhost/remote hots..,
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host,user,pwd,port,.......)
si, so, se = ssh.exec_command('nohup' + cmd + '&')
so.read()
se.read()
has resolved the issue....
| how can I put a process in background using django? | I tried os.system, os.spwanl, etc.. but it doesn't work well
I need to execute some background process from django application.
| [
"Try to use celery. It was originally created for this purpose and also supports scheduling tasks.\n",
"The subprocess module gives you much finer-grained control over spawning processes than afforded by os.system.\n",
"I have used subprocess to spawn background processes from Django before. It may depend on yo... | [
15,
0,
0,
0
] | [] | [] | [
"django",
"process",
"python",
"system"
] | stackoverflow_0002872605_django_process_python_system.txt |
Q:
Read 40 bytes of binary data as ascii text
I have some binary data, in hex editor it looks like:
s.o.m.e.d.a.t.a
with all these dots in between each letter
when I read with filehandle.read(40)
it shows these dots
I know that the dots aren't supposed to be there, is there a way to unpack some ascii data that is 40 bytes long with struct?
I tried '40s' and 's' but it shows weird data, or only unpacks 1 character instead of 40.
A:
If your first byte is an ASCII character (as indicated by your example) and your second byte is '\x00', then you probably have data encoded as UTF-16LE.
However it would be a good idea if you showed us unequivocably exactly what's in the first few bytes of your file. Please do this:
python -c "print(repr(open('myfile.txt', 'rb').read(20)))"
and edit your question to show us the result. If any text is confidential, please retain the sense when editing it.
We are especially interested to see if it starts with a UTF-16 BOM ('\xff\xfe' or '\xfe\xff').
For background, what platform (Windows or Linux) are you on? What produced the file?
Update I'm a bit puzzled by your statement """I tried '40s' and 's' but it shows weird data, or only unpacks 1 character instead of 40.""" Examine the following examples:
>>> data = "q\x00w\x00"
>>> unpack("4s", data)
('q\x00w\x00',) # weird? it's effectively tuple([data])
>>> unpack("s", data)
# doesn't produce a string of length 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: unpack requires a string argument of length 1
>>> unpack("ssss", data)
('q', '\x00', 'w', '\x00') # this == tuple(data)
>>>
@pxh commented """You're only getting a single character because those dots are being read as ASCII NULs (and so terminating the string).""" I doubt very much whether @pxh could actually demonstrate that struct.unpack's use of the "s" format depends in any way on the individual byte values in the data, whether NUL ("\x00") or anything else.
A:
Quick-and-dirty solution is to use s[::2] where s is the 80-characters byte string of which you want to consider only alternate bytes. The "clean: solution, per @fadden's comment, might be to read in the data as UTF-16 (then .encode it to ASCII, etc), but if the Q&D one suffices for your purposes, it might be simpler and faster (if the original data has characters that are not in the lowest 256 range, the Q&D approach will give strange results while the proper one would raise an exception -- which treatment is better depends on you app...).
A:
For reading binary data in python I am using:
val = f.read(1)
val = struct.unpack( 'c' , val )
And reading byte by byte all that I need.
For 40 byte struct I would be
val = f.read(40)
val = struct.unpack( '40c' , val )
| Read 40 bytes of binary data as ascii text | I have some binary data, in hex editor it looks like:
s.o.m.e.d.a.t.a
with all these dots in between each letter
when I read with filehandle.read(40)
it shows these dots
I know that the dots aren't supposed to be there, is there a way to unpack some ascii data that is 40 bytes long with struct?
I tried '40s' and 's' but it shows weird data, or only unpacks 1 character instead of 40.
| [
"If your first byte is an ASCII character (as indicated by your example) and your second byte is '\\x00', then you probably have data encoded as UTF-16LE. \nHowever it would be a good idea if you showed us unequivocably exactly what's in the first few bytes of your file. Please do this:\npython -c \"print(repr(open... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003507925_python.txt |
Q:
Pure Python in Xcode
Is there a way to program using pure python in Xcode? I want something like the c++ command line utility except for python, I found a tutorial that did not work for me: (after playing around with which active architecture finally decided on i386) when trying to print "Hello, World!" I get the following error "Data Formatters temporarily unavailable, will re-try after a 'continue'. (Cannot call into the loader at present, it is locked.)" (Using an intel Mac OS 10.6.4 and Xcode 3.2.3)
Here is how I followed the steps:
1) Opened Xcode went to File -> New Project
2) Selected from 'Other', 'Empty Project'
3) Named it 'PyProject' in a local directory on my computer
4) Went to File -> New File
5) From 'Pure Python' I selected 'Python tool', named it main.py then clicked finish
6) Added print ('Hello, World!') to the file, and saved the file
7) Went to Project -> New Custom Executable
8) Named it PyExecutable, gave it path" /Library/Frameworks/Python.framework/Versions/2.6/bin/python" and added it to project PyProject, then clicked Finish
9) Double-clicked PyExecutable in PyProject window
10) Went to Arguments and added the path of my main.py file "/Users/jordan/PyProject/main.py"
11) Switched Active Architecture from the pull down menu at the top of the PyProject window to i386 (Now is in Debug, No Active Target, PyExecutable Is Active Executable and Architecture is i386)(If I don't switch the architecture and leave it on default x86_64 I get this error as a pop-up "The active architecture x86_64 is not present in the executable 'PyExecutable' which contains ppc/i386")
12) Clicked Run -> Run and then I get the error listed above in the console
Before anyone suggests it: I know Xcode is not the best option for pure python please do not suggest that I use another text editor.
Edit: details of what was not working when following the tutorial
Edit: my system details were added, and the steps I followed to get the error
Update: I wrapped the path of main.py in double quotes "" and now when I press continue after the error the console prints hello world, but I get the same error originally.
A:
/Library/Frameworks/Python.framework/Versions/2.6/bin/python is typically the path to the python.org installer Python (or possibly other non-Apple Python) which, indeed, includes only 32-bit architectures (ppc and i386). It also is built using the OS X 10.4u SDK (an optional install with Xcode on 10.6). The Apple-supplied Python 2.6 in 10.6 is built using a 10.6 SDK and includes 32-bit and 64-bit archs (i386, x86_64, and ppc for compatibility).
$ /usr/local/bin/python2.6 -c 'import sys;print(sys.executable)' # python.org Python
/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python
$ /usr/bin/python2.6 -c 'import sys;print(sys.executable)' # Apple-supplied Python
/usr/bin/python2.6
Decide which Python you want to use and change your Xcode project accordingly.
| Pure Python in Xcode | Is there a way to program using pure python in Xcode? I want something like the c++ command line utility except for python, I found a tutorial that did not work for me: (after playing around with which active architecture finally decided on i386) when trying to print "Hello, World!" I get the following error "Data Formatters temporarily unavailable, will re-try after a 'continue'. (Cannot call into the loader at present, it is locked.)" (Using an intel Mac OS 10.6.4 and Xcode 3.2.3)
Here is how I followed the steps:
1) Opened Xcode went to File -> New Project
2) Selected from 'Other', 'Empty Project'
3) Named it 'PyProject' in a local directory on my computer
4) Went to File -> New File
5) From 'Pure Python' I selected 'Python tool', named it main.py then clicked finish
6) Added print ('Hello, World!') to the file, and saved the file
7) Went to Project -> New Custom Executable
8) Named it PyExecutable, gave it path" /Library/Frameworks/Python.framework/Versions/2.6/bin/python" and added it to project PyProject, then clicked Finish
9) Double-clicked PyExecutable in PyProject window
10) Went to Arguments and added the path of my main.py file "/Users/jordan/PyProject/main.py"
11) Switched Active Architecture from the pull down menu at the top of the PyProject window to i386 (Now is in Debug, No Active Target, PyExecutable Is Active Executable and Architecture is i386)(If I don't switch the architecture and leave it on default x86_64 I get this error as a pop-up "The active architecture x86_64 is not present in the executable 'PyExecutable' which contains ppc/i386")
12) Clicked Run -> Run and then I get the error listed above in the console
Before anyone suggests it: I know Xcode is not the best option for pure python please do not suggest that I use another text editor.
Edit: details of what was not working when following the tutorial
Edit: my system details were added, and the steps I followed to get the error
Update: I wrapped the path of main.py in double quotes "" and now when I press continue after the error the console prints hello world, but I get the same error originally.
| [
"/Library/Frameworks/Python.framework/Versions/2.6/bin/python is typically the path to the python.org installer Python (or possibly other non-Apple Python) which, indeed, includes only 32-bit architectures (ppc and i386). It also is built using the OS X 10.4u SDK (an optional install with Xcode on 10.6). The Appl... | [
2
] | [] | [] | [
"macos",
"python",
"xcode"
] | stackoverflow_0003498839_macos_python_xcode.txt |
Q:
Dynamically loading Python application code from database under Google App Engine
I need to store python code in a database and load it in some kind of bootstrap.py application for execution. I cannot use filesystem because I'm using GAE, so this is my only choice.
However I'm not a python experienced user.
I already was able to load 1 line of code and run it using eval, however a piece of code with two lines or more gave me a "invalid syntax" error.
I'm also thinking if it's possible to extend the "import" loader to implement the DB loading.
Thanks!
A:
I was able to do what I intent after reading more about Python dynamic code loading.
Here is the sample code. I removed headers to be lighter:
Thanks anyway!
=============
class DynCode(db.Model):
name = db.StringProperty()
code = db.TextProperty(default=None)
=============
class MainHandler(webapp.RequestHandler):
def get(self):
dyn = DynCode()
dyn = "index"
dyn.code = """
from google.appengine.ext import webapp
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("Hello World\\n")
self.response.out.write("Hello World 2\\n")
"""
dyn.put()
self.response.out.write("OK.")
def main():
application = webapp.WSGIApplication([('/update', MainHandler)], debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
==================================
def main():
query = DynCode.all()
dyncodes = query.fetch(1)
module = imp.new_module('mymodule')
for dyn in dyncodes:
exec dyn.code in module.__dict__
application = webapp.WSGIApplication([('/', module.MainHandler)], debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
=======================
A:
If you want a more robust mechanism, you probably want to read PEP302, which describes input hooks. You can use these to import code rather than having to eval it.
A:
I somewhat agree with the commentators above, it sounds kind of dangerous. However:
I experimented a little with App Engine Console ( http://con.appspot.com/console/ ), and eval() indeed tended to throw SyntaxError's.
Instead, the exec statement might be your friend ( http://docs.python.org/release/2.5.2/ref/exec.html ).
I managed to run this in App Engine Console:
>>> exec "def f(x):\n x = x + 1\n y = 10\n return x + y"
>>> f(10)
21
So try the exec statement, but remember the many, many (many!) perils of code coming directly from end-users.
| Dynamically loading Python application code from database under Google App Engine | I need to store python code in a database and load it in some kind of bootstrap.py application for execution. I cannot use filesystem because I'm using GAE, so this is my only choice.
However I'm not a python experienced user.
I already was able to load 1 line of code and run it using eval, however a piece of code with two lines or more gave me a "invalid syntax" error.
I'm also thinking if it's possible to extend the "import" loader to implement the DB loading.
Thanks!
| [
"I was able to do what I intent after reading more about Python dynamic code loading.\nHere is the sample code. I removed headers to be lighter:\nThanks anyway!\n=============\nclass DynCode(db.Model):\n name = db.StringProperty()\n code = db.TextProperty(default=None)\n\n=============\nclass MainHandler(weba... | [
4,
3,
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003505357_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python: How to check if a unicode string contains a cased character?
I'm doing a filter wherein I check if a unicode (utf-8 encoding) string contains no uppercase characters (in all languages). It's fine with me if the string doesn't contain any cased character at all.
For example: 'Hello!' will not pass the filter, but "!" should pass the filter, since "!" is not a cased character.
I planned to use the islower() method, but in the example above, "!".islower() will return False.
According to the Python Docs, "The python unicode method islower() returns True if the unicode string's cased characters are all lowercase and the string contained at least one cased character, otherwise, it returns False."
Since the method also returns False when the string doesn't contain any cased character, ie. "!", I want to do check if the string contains any cased character at all.
Something like this....
string = unicode("!@#$%^", 'utf-8')
#check first if it contains cased characters
if not contains_cased(string):
return True
return string.islower():
Any suggestions for a contains_cased() function?
Or probably a different implementation approach?
Thanks!
A:
import unicodedata as ud
def contains_cased(u):
return any(ud.category(c)[0] == 'L' for c in u)
A:
Here is the full scoop on Unicode character categories.
Letter categories include:
Ll -- lowercase
Lu -- uppercase
Lt -- titlecase
Lm -- modifier
Lo -- other
Note that Ll <-> islower(); similarly for Lu; (Lu or Lt) <-> istitle()
You may wish to read the complicated discussion on casing, which includes some discussion of Lm letters.
Blindly treating all "letters" as cased is demonstrably wrong. The Lo category includes 45301 codepoints in the BMP (counted using Python 2.6). A large chunk of these would be Hangul Syllables, CJK Ideographs, and other East Asian characters -- very hard to understand how they might be considered "cased".
You might like to consider an alternative definition, based on the (unspecified) behaviour of "cased characters" that you expect. Here's a simple first attempt:
>>> cased = lambda c: c.upper() != c or c.lower() != c
>>> sum(cased(unichr(i)) for i in xrange(65536))
1970
>>>
Interestingly there are 1216 x Ll and 937 x Lu, a total of 2153 ... scope for further investigation of what Ll and Lu really mean.
A:
use module unicodedata,
unicodedata.category(character)
returns "Ll" for lowercase letters and "Lu" for uppercase ones.
here you can find list of unicode character categories
| Python: How to check if a unicode string contains a cased character? | I'm doing a filter wherein I check if a unicode (utf-8 encoding) string contains no uppercase characters (in all languages). It's fine with me if the string doesn't contain any cased character at all.
For example: 'Hello!' will not pass the filter, but "!" should pass the filter, since "!" is not a cased character.
I planned to use the islower() method, but in the example above, "!".islower() will return False.
According to the Python Docs, "The python unicode method islower() returns True if the unicode string's cased characters are all lowercase and the string contained at least one cased character, otherwise, it returns False."
Since the method also returns False when the string doesn't contain any cased character, ie. "!", I want to do check if the string contains any cased character at all.
Something like this....
string = unicode("!@#$%^", 'utf-8')
#check first if it contains cased characters
if not contains_cased(string):
return True
return string.islower():
Any suggestions for a contains_cased() function?
Or probably a different implementation approach?
Thanks!
| [
"import unicodedata as ud\n\ndef contains_cased(u):\n return any(ud.category(c)[0] == 'L' for c in u)\n\n",
"Here is the full scoop on Unicode character categories.\nLetter categories include:\nLl -- lowercase\nLu -- uppercase\nLt -- titlecase\nLm -- modifier\nLo -- other\n\nNote that Ll <-> islower(); similarly... | [
8,
8,
1
] | [] | [] | [
"lowercase",
"python",
"unicode",
"uppercase"
] | stackoverflow_0003508490_lowercase_python_unicode_uppercase.txt |
Q:
Getting list of all strings from a Django app
Eclipse has a function called Externalise all Strings, which will move all strings to an properties file.
Is there such a solution available for Django/Python?
Basically I have a large project with number of views/models/templates, and going through all of them, and putting
string -> _("string") etc is a big pain, so is there a way to automate this?
A:
It is automated in Django and has been for a long time. But the docs are a bit hard to find ;)
You can use the makemessages management command, or if you run an older version of django run django/bin/make-messages.py.
Link to the docs: http://docs.djangoproject.com/en/dev/ref/django-admin/#makemessages
Example:
django-admin.py makemessages --locale=en
| Getting list of all strings from a Django app | Eclipse has a function called Externalise all Strings, which will move all strings to an properties file.
Is there such a solution available for Django/Python?
Basically I have a large project with number of views/models/templates, and going through all of them, and putting
string -> _("string") etc is a big pain, so is there a way to automate this?
| [
"It is automated in Django and has been for a long time. But the docs are a bit hard to find ;)\nYou can use the makemessages management command, or if you run an older version of django run django/bin/make-messages.py.\nLink to the docs: http://docs.djangoproject.com/en/dev/ref/django-admin/#makemessages\nExample:... | [
1
] | [] | [] | [
"django",
"internationalization",
"python"
] | stackoverflow_0003509512_django_internationalization_python.txt |
Q:
Use (Python) Gstreamer to decode audio (to PCM data)
I'm writing an application that uses the Python Gstreamer bindings to play audio, but I'm now trying to also just decode audio -- that is, I'd like to read data using a decodebin and receive a raw PCM buffer. Specifically, I want to read chunks of the file incrementally rather than reading the whole file into memory.
Some specific questions: How can I accomplish this with Gstreamer? With pygst specifically? Is there a particular "sink" element I need to use to read data from the stream? Is there a preferred way to read data from a pygst Buffer object? How do I go about controlling the rate at which I consume data (rather than just entering a "main loop")?
A:
To get the data back in your application, the recommended way is appsink.
Based on a simple audio player like this one (and replace the oggdemux/vorbisdec by decodebin & capsfilter with caps = "audio/x-raw-int"), change autoaudiosink to appsink, and connect "new-buffer" signal to a python function + set "emit-signals" to True. The function will receive decoded chunks of PCM/int data. The rate of the decoding will depend on the rate at which you can decode and consume. Since the new-buffer signal is in the Gstreamer thread context, you could just sleep/wait in that function to control or slow down the decoding speed.
| Use (Python) Gstreamer to decode audio (to PCM data) | I'm writing an application that uses the Python Gstreamer bindings to play audio, but I'm now trying to also just decode audio -- that is, I'd like to read data using a decodebin and receive a raw PCM buffer. Specifically, I want to read chunks of the file incrementally rather than reading the whole file into memory.
Some specific questions: How can I accomplish this with Gstreamer? With pygst specifically? Is there a particular "sink" element I need to use to read data from the stream? Is there a preferred way to read data from a pygst Buffer object? How do I go about controlling the rate at which I consume data (rather than just entering a "main loop")?
| [
"To get the data back in your application, the recommended way is appsink.\nBased on a simple audio player like this one (and replace the oggdemux/vorbisdec by decodebin & capsfilter with caps = \"audio/x-raw-int\"), change autoaudiosink to appsink, and connect \"new-buffer\" signal to a python function + set \"emi... | [
5
] | [] | [] | [
"audio",
"decode",
"gstreamer",
"pcm",
"python"
] | stackoverflow_0003507746_audio_decode_gstreamer_pcm_python.txt |
Q:
Passing subclasses to imported library
I have library which returns collections of some semi-abstract objects.
class Item1(object):
pass
class Item2(object):
pass
class Collection1(object):
pass
class Provider(object):
def retrieve_collection(self):
col = Collection1()
col.add(Item1())
col.add(Item2())
return col
It just populates attributes of the objects, and these item/collection classes are intended to be subclassed in caller code.
So there would be some script
from mylib import Provider, Item1
class MyItem(Item1):
pass
provider = Provider()
col = provider.retrieve_collection()
And the question is, what is elegant and pythonic solution to pass MyItem (and any other subclasses) to Provider?
I can pass it as Provider(item1=MyItem), store it as self.item1, and then instantiate it as self.item1() instead of Item1(), but this seems fugly. Plus I'll have horrible, long constructor calls all over client code.
Other option would be to override classes on module level, like mylib.Item1 = MyItem, but this can lead to many unexpected and hard to debug problems. Besides, there could be several different provider classes which use same item base classes, but which would require different subclasses from client.
Maybe some form of classes registry and factories instead of actual classes? So Item1() would try to figure which class to instantiate based on some context, but I'm not sure how that would work.
A:
mylib.py
class Item1(object):
def __repr__(self):
return "Base Item1"
class Item2(object):
def __repr__(self):
return "Base Item2"
class Collection1(set):
pass
class Provider(object):
Item1=Item1
Item2=Item2
def retrieve_collection(self):
col = Collection1()
col.add(self.Item1())
col.add(self.Item2())
return col
from mylib import Provider
class MyProvider(Provider):
class Item1(Provider.Item1):
def __repr__(self):
return "Subclass Item1"
p=Provider()
print p.retrieve_collection()
p=MyProvider()
print p.retrieve_collection()
Output:
Collection1([Base Item2, Base Item1])
Collection1([Base Item2, Subclass Item1])
A:
Would you consider this as fugly?
class Provider(object):
def retrieve_collection(self, type0=Item1, type1=Item2):
col = Collection1()
col.add(type0())
col.add(type1())
return col
col = provider.retrieve_collection(MyItem)
A:
mylib.py
class Item1(object):
def __repr__(self):
return "Base Item1"
class Item2(object):
def __repr__(self):
return "Base Item2"
class Collection1(set):
pass
class Provider(object):
Item1=Item1
Item2=Item2
def retrieve_collection(self):
col = Collection1()
col.add(self.Item1())
col.add(self.Item2())
return col
def ProviderFactory(**kw):
return type('Provider', (Provider,)+Provider.__bases__, kw)
from mylib import ProviderFactory, Item1
class Item1(Item1):
def __repr__(self):
return "Subclass Item1"
MyProvider=ProviderFactory(Item1=Item1)
p=MyProvider()
print p.retrieve_collection()
Output:
Collection1([Base Item2, Subclass Item1])
| Passing subclasses to imported library | I have library which returns collections of some semi-abstract objects.
class Item1(object):
pass
class Item2(object):
pass
class Collection1(object):
pass
class Provider(object):
def retrieve_collection(self):
col = Collection1()
col.add(Item1())
col.add(Item2())
return col
It just populates attributes of the objects, and these item/collection classes are intended to be subclassed in caller code.
So there would be some script
from mylib import Provider, Item1
class MyItem(Item1):
pass
provider = Provider()
col = provider.retrieve_collection()
And the question is, what is elegant and pythonic solution to pass MyItem (and any other subclasses) to Provider?
I can pass it as Provider(item1=MyItem), store it as self.item1, and then instantiate it as self.item1() instead of Item1(), but this seems fugly. Plus I'll have horrible, long constructor calls all over client code.
Other option would be to override classes on module level, like mylib.Item1 = MyItem, but this can lead to many unexpected and hard to debug problems. Besides, there could be several different provider classes which use same item base classes, but which would require different subclasses from client.
Maybe some form of classes registry and factories instead of actual classes? So Item1() would try to figure which class to instantiate based on some context, but I'm not sure how that would work.
| [
"mylib.py\nclass Item1(object):\n def __repr__(self):\n return \"Base Item1\"\nclass Item2(object):\n def __repr__(self):\n return \"Base Item2\"\nclass Collection1(set):\n pass \n\nclass Provider(object):\n Item1=Item1\n Item2=Item2\n def retrieve_collection(self):\n col = Co... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003509961_python.txt |
Q:
Why does python libs (eg imaplib) does not use logging but use sys.stderr.write?
I'm not sure if it's because sys.stderr.write is faster.
A:
imaplib is much older (it was in Python1.5.2) than the logging module (Python2.3), so perhaps noone has needed to update it to use logging yet
| Why does python libs (eg imaplib) does not use logging but use sys.stderr.write? | I'm not sure if it's because sys.stderr.write is faster.
| [
"imaplib is much older (it was in Python1.5.2) than the logging module (Python2.3), so perhaps noone has needed to update it to use logging yet\n"
] | [
6
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0003510747_logging_python.txt |
Q:
Looking For: A “demo” web web-based application that uses web services
Greetings – I am experimenting with various software techniques to capture and analyze the messages being exchanged between web services, web services that together would form a cloud hosted web application. One of the initial steps is locating a “demo” application to actually experiment against, one that actually consists of and uses a multitude of web services.
Well, finding such has turned out to be harder than I expected. After searching numerous places the initial candidate applications I found did not pan out – each either uses callbacks (such as into Python / GAE libraries) instead of web service invocations, or the source code was not available.
I am seeking recommendations for a web services “demonstration” application:
That consists of and invokes a multitude of web services (SOAP or REST – or JSON??)
Has source code available, the “main” application as well invoked web services (so I can tweak the code to instrument the messages being passed around)
Runs on an available hosting service / engine (such as GAE)
I would prefer (but do not require) Python as the programming language since I have spent the last month learning it, and using it on GAE.
Thanks from this newbie for your contribution!
Steve
A:
The piston add-in for Django is nice. It has sample RESTful web services applications you can run.
http://bitbucket.org/jespern/django-piston/wiki/Home
You might want to use the demo app from the presentation.
http://bitbucket.org/Josh/django-piston-presentation/wiki/Home
A:
I recall using an add-on for turbogears called tgws a few years back but I don't know if it works with the latest turbogears. It was pretty easy to build out web services, but I am not sure it has any demo interfaces. It was even easy to add extra services (like xmlrpc).
Sorry this isn't more helpful but I figured it might give you a place to start. As well, for all I know turbogears 2 or django have stronger support for exposing web services out of the box... (haven't done work on that side for a while).
A:
I would start with this article
http://www.opensourcetutorials.com/tutorials/Server-Side-Coding/Python/python-soap-libraries/page1.html
We are implementing soap services now, but have decided to pursue a REST approach.
I am trying to implement rest returning JSON and XML right now, and I have been editing a clean and simple python framework for building them.
after much consideration, I have forked a python wsgi library called starlight (my fork is called - twilight)
I have been working on the documentation, and this project is going where you probably want to be.
I will have a demo that returns json and XML in the next couple of days.
http://bitbucket.org/marchon/twilight
| Looking For: A “demo” web web-based application that uses web services | Greetings – I am experimenting with various software techniques to capture and analyze the messages being exchanged between web services, web services that together would form a cloud hosted web application. One of the initial steps is locating a “demo” application to actually experiment against, one that actually consists of and uses a multitude of web services.
Well, finding such has turned out to be harder than I expected. After searching numerous places the initial candidate applications I found did not pan out – each either uses callbacks (such as into Python / GAE libraries) instead of web service invocations, or the source code was not available.
I am seeking recommendations for a web services “demonstration” application:
That consists of and invokes a multitude of web services (SOAP or REST – or JSON??)
Has source code available, the “main” application as well invoked web services (so I can tweak the code to instrument the messages being passed around)
Runs on an available hosting service / engine (such as GAE)
I would prefer (but do not require) Python as the programming language since I have spent the last month learning it, and using it on GAE.
Thanks from this newbie for your contribution!
Steve
| [
"The piston add-in for Django is nice. It has sample RESTful web services applications you can run.\nhttp://bitbucket.org/jespern/django-piston/wiki/Home\nYou might want to use the demo app from the presentation.\nhttp://bitbucket.org/Josh/django-piston-presentation/wiki/Home\n",
"I recall using an add-on for tu... | [
1,
0,
0
] | [] | [] | [
"python",
"web_applications",
"web_services"
] | stackoverflow_0003508878_python_web_applications_web_services.txt |
Q:
Python: Slice a 2d array into tiles
I have a raw data file which I read into a byte buffer (a python string). Each data value represents an 8bit pixel of a 2d array representing an image. I know the width and height of this image.
I would like to split the image into tiles so that each tiles area must be larger than a 'min tile area' (eg 1024 bytes) and smaller than 'max tile area(eg 2048 bytes). The height and width of these tiles is arbirary as long as the area constraints are met, and the tiles need not all be the same size. Also the size/length of the input data is not guaranteed to be a power of two.
Whats the best way of doing this in python
Regards
A:
As you give no indication of the meaning of "best", I will suppose that it means "with the less cluttered code".
Let's say you have the following data:
from collections import Sequence
import operator
assert(type(MIN_AREA) is int)
assert(type(MAX_AREA) is int)
assert(type(width) is int)
assert(type(height) is int)
assert(instanceof(data, Sequence))
assert(len(data) == width * height)
assert(MAX_AREA >= 2 * MIN_AREA)
(The condition on the MIN and MAX areas is necessary for this to work)
There is some cases in which this can't be done with any algorithm, for instance splitting a 3x3 image in tiles of between 4 and 8.
Suppose the data is stored by rows (like in PNM specification for instance).
def split_(seq, size):
return [seq[i:i+size] for i in range(0,len(seq),size)]
tiles = list()
if width >= MIN_AREA:
# each row is subdivided into multiple tiles
tile_width = width / (width / MIN_AREA) # integral division
rows = split_(data, width)
row_tiles = [split_(row, tile_width) for row in rows]
tiles = reduce(operator.add, row_tiles)
elif width < MIN_AREA:
# each tile is composed of rows
min_tile_height = int(MIN_AREA / width) + 1
tile_height = height / (height / min_tile_height)
tile_size = tile_height * width
tiles = split_(data, tile_size)
if len(tiles[-1]) < MIN_AREA:
if (tile_height > 2):
tiles[-2] += tiles[-1]
del tiles[-1]
else: # tile_height == 2, the case 1 don't pass here
# special case, we need to split vertically the last three rows
# if the width was 3 too we have a problem but then if we are here
# then MIN_AREA was 4, and MAX_AREA was 8, and the rows are >= 5
if width > 3:
last_three_rows = split_(tiles[-2] + tiles[-1], width)
tiles[-2] = reduce(operator.add,[row[:width/2] for row in last_three_rows])
tiles[-1] = reduce(operator.add,[row[width/2:] for row in last_three_rows])
else: # width = 3 and MIN_AREA = 4
last_five_rows = reduce(operator.add, tiles[-3:])
three_columns = [last_five_rows[i::3] for i in range(3)]
tiles[-3:] = three_columns
Just remember that in the last cases you get two or three tiles side-by-side, and all the others are stacked above them (or below, depending on where is row '0').
If you need to store more than the raw pixel data, just adjust the tile creation process.
A:
If you're working with images you should use PIL (Python Imaging Library). Then you just load the image:
import Image
i = Image.open(imagefile)
and the you can easily crop a region of arbitrary size:
box = (FirstCornerX, FirstCornerY, SecondCornerX, SecondCornerY)
region = im.crop(box)
so you can work with it. You can also convert between Image object and 2d arrays but I don't quite remember how it was done. I had a couple functions to transform both ways between images an numpy arrays, I'll see if I can find them.
Also, you may want to look at the PIL handbook to find documentation and recipes for working with images.
| Python: Slice a 2d array into tiles | I have a raw data file which I read into a byte buffer (a python string). Each data value represents an 8bit pixel of a 2d array representing an image. I know the width and height of this image.
I would like to split the image into tiles so that each tiles area must be larger than a 'min tile area' (eg 1024 bytes) and smaller than 'max tile area(eg 2048 bytes). The height and width of these tiles is arbirary as long as the area constraints are met, and the tiles need not all be the same size. Also the size/length of the input data is not guaranteed to be a power of two.
Whats the best way of doing this in python
Regards
| [
"As you give no indication of the meaning of \"best\", I will suppose that it means \"with the less cluttered code\".\nLet's say you have the following data:\nfrom collections import Sequence\nimport operator\n\nassert(type(MIN_AREA) is int)\nassert(type(MAX_AREA) is int)\nassert(type(width) is int)\nassert(type(he... | [
2,
1
] | [] | [] | [
"python",
"slice"
] | stackoverflow_0003510057_python_slice.txt |
Q:
Python yield returns characters instead of string from single-element tuple
I'm using yield to process each element of a list. However, if the tuple only has a single string element, yield returns the characters of the string, instead of the whole string:
self.commands = ("command1")
...
for command in self.commands:
yield command # returns 'c' not 'command1'
how can i fix this?
Thanks
A:
A tuple having only 1 element should be written with a trailing comma.
self.commands = ("command1",)
A:
self.commands = ["command1"]
You never told the loop that you had a list, so it's treating the string as the sequence.
edit: or you could just fix the tuple, as recommended ... I assumed you'd want to use a list instead of a tuple.
| Python yield returns characters instead of string from single-element tuple | I'm using yield to process each element of a list. However, if the tuple only has a single string element, yield returns the characters of the string, instead of the whole string:
self.commands = ("command1")
...
for command in self.commands:
yield command # returns 'c' not 'command1'
how can i fix this?
Thanks
| [
"A tuple having only 1 element should be written with a trailing comma.\nself.commands = (\"command1\",)\n\n",
"self.commands = [\"command1\"]\n\nYou never told the loop that you had a list, so it's treating the string as the sequence.\nedit: or you could just fix the tuple, as recommended ... I assumed you'd wan... | [
6,
0
] | [] | [] | [
"python",
"yield"
] | stackoverflow_0003511292_python_yield.txt |
Q:
Factory pattern in Python
I'm currently implementing the Factory design pattern in Python and I have a few questions.
Is there any way to prevent the direct instantiation of the actual concrete classes? For example, if I have a VehicleFactory that spawns Vehicles, I want users to just use that factory, and prevent anyone from accidentally instantiating Car() or Truck() directly. I can throw an exception in init() perhaps, but that would also mean that the factory can't create an instance of it...
It seems to me now that factories are getting addictive. Seems like everything should become a factory so that when I change internal implementation, the client codes will not change. I'm interested to know when is there an actual need to use factories, and when is it not appropriate to use. For example, I might have a Window class and there's only one of this type now (no PlasticWindow, ReinforcedWindow or anything like that). In that case, should I use a factory for the client to generate the Window, just in case I might add more types of Windows in the future?
I'm just wondering if there is a usual way of calling the factories. For example, now I'm calling my Vehicle factory as Vehicles, so the codes will go something like Vehicles.create(...). I see a lot of tutorials doing it like VehicleFactory, but I find it too long and it sort of exposes the implementation as well.
EDIT: What I meant by "exposes the implementation" is that it lets people know that it's a factory. What I felt was that the client need not know that it's a factory, but rather as some class that can return objects for you (which is a factory of course but maybe there's no need to explicitly tell clients that?). I know that the soure codes are easily exposed, so I didn't mean "exposing the way the functionalities are implemented in the source codes".
Thanks!
A:
Be Pythonic. Don't overcomplicate your code with "enterprise" language (like Java) solutions that add unnecessary levels of abstraction.
Your code should be simple, and intuitive. You shouldn't need to delegate to another class to instantiate another.
A:
Don't expose the class (for example make it private __MyClass, or obvious that you don't want it used directly _MyClass). This way it can only be instantiated via the factory function.
Perhaps you should review the use of keyword arguments, and inheritance. It sounds like you may be overlooking these, which will generally reduce your dependence on complex factories (To be honest, I've rarely needed factories).
In Python you cannot easily protect against exposing implementation, it goes against the Zen of Python. (It's the same in any language, a determined individual can get what they want eventually). At most you should try to ensure that a user of your code does not accidentally do the wrong thing, but never presume to know what the end-user may decide to achieve with your code. Don't make it obfuscated and difficult to work with.
A:
Is there any way to prevent the direct instantiation of the actual concrete classes?
Why? Are your programmers evil sociopaths who refuse to follow the rules? If you provide a factory -- and the factory does what people need -- then they'll use the factory.
You can't "prevent" anything. Remember. This is Python -- they have the source.
should I use a factory for the client to generate the Window, just in case I might add more types of Windows in the future?
Meh. Neither good nor bad. It can get cumbersome to manage all the class-hierarchy-and-factory details.
Adding a factory isn't hard. This is Python -- you have all the source at all times -- you can use grep to find a class constructor and replace it with a factory when you need to.
Since you can use grep to find and fix your mistakes, you don't need to pre-plan this kind of thing as much as you might in Java or C++.
I see a lot of tutorials doing it like VehicleFactory, but I find it too long and it sort of exposes the implementation as well.
"Too Long"? It's used so rarely that it barely matters. Use long names -- it helps other folks understand what you're doing. This is not Code Golf where fewest keystrokes wins.
"exposes the implementation"? First, It exposes nothing. Second, this is Python -- you have all the source at all times -- everything is already exposed.
Stop thinking so much about prevention and privacy. It isn't helpful.
| Factory pattern in Python | I'm currently implementing the Factory design pattern in Python and I have a few questions.
Is there any way to prevent the direct instantiation of the actual concrete classes? For example, if I have a VehicleFactory that spawns Vehicles, I want users to just use that factory, and prevent anyone from accidentally instantiating Car() or Truck() directly. I can throw an exception in init() perhaps, but that would also mean that the factory can't create an instance of it...
It seems to me now that factories are getting addictive. Seems like everything should become a factory so that when I change internal implementation, the client codes will not change. I'm interested to know when is there an actual need to use factories, and when is it not appropriate to use. For example, I might have a Window class and there's only one of this type now (no PlasticWindow, ReinforcedWindow or anything like that). In that case, should I use a factory for the client to generate the Window, just in case I might add more types of Windows in the future?
I'm just wondering if there is a usual way of calling the factories. For example, now I'm calling my Vehicle factory as Vehicles, so the codes will go something like Vehicles.create(...). I see a lot of tutorials doing it like VehicleFactory, but I find it too long and it sort of exposes the implementation as well.
EDIT: What I meant by "exposes the implementation" is that it lets people know that it's a factory. What I felt was that the client need not know that it's a factory, but rather as some class that can return objects for you (which is a factory of course but maybe there's no need to explicitly tell clients that?). I know that the soure codes are easily exposed, so I didn't mean "exposing the way the functionalities are implemented in the source codes".
Thanks!
| [
"Be Pythonic. Don't overcomplicate your code with \"enterprise\" language (like Java) solutions that add unnecessary levels of abstraction.\nYour code should be simple, and intuitive. You shouldn't need to delegate to another class to instantiate another.\n",
"\nDon't expose the class (for example make it private... | [
23,
12,
6
] | [] | [] | [
"design_patterns",
"factory",
"factory_pattern",
"python"
] | stackoverflow_0003511027_design_patterns_factory_factory_pattern_python.txt |
Q:
How to remove list of words from a list of strings
Sorry if the question is bit confusing. This is similar to this question
I think this the above question is close to what I want, but in Clojure.
There is another question
I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed.
Hope I made myself clear.
I think that this is due to the fact that strings in python are immutable.
I have a list of noise words that need to be removed from a list of strings.
If I use the list comprehension, I end up searching the same string again and again. So, only "of" gets removed and not "the". So my modified list looks like this
places = ['New York', 'the New York City', 'at Moscow' and many more]
noise_words_list = ['of', 'the', 'in', 'for', 'at']
for place in places:
stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)]
I would like to know as to what mistake I'm doing.
A:
Without regexp you could do like this:
places = ['of New York', 'of the New York']
noise_words_set = {'of', 'the', 'at', 'for', 'in'}
stuff = [' '.join(w for w in place.split() if w.lower() not in noise_words_set)
for place in places
]
print stuff
A:
Here is my stab at it. This uses regular expressions.
import re
pattern = re.compile("(of|the|in|for|at)\W", re.I)
phrases = ['of New York', 'of the New York']
map(lambda phrase: pattern.sub("", phrase), phrases) # ['New York', 'New York']
Sans lambda:
[pattern.sub("", phrase) for phrase in phrases]
Update
Fix for the bug pointed out by gnibbler (thanks!):
pattern = re.compile("\\b(of|the|in|for|at)\\W", re.I)
phrases = ['of New York', 'of the New York', 'Spain has rain']
[pattern.sub("", phrase) for phrase in phrases] # ['New York', 'New York', 'Spain has rain']
@prabhu: the above change avoids snipping off the trailing "in" from "Spain". To verify run both versions of the regular expressions against the phrase "Spain has rain".
A:
>>> import re
>>> noise_words_list = ['of', 'the', 'in', 'for', 'at']
>>> phrases = ['of New York', 'of the New York']
>>> noise_re = re.compile('\\b(%s)\\W'%('|'.join(map(re.escape,noise_words_list))),re.I)
>>> [noise_re.sub('',p) for p in phrases]
['New York', 'New York']
A:
Since you would like to know what you are doing wrong, this line:
stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)]
takes place, and then begins to loop over words. First it checks for "of". Your place (e.g. "of the New York") is checked to see if it starts with "of". It is transformed (call to replace and strip) and added to the result list. The crucial thing here is that result is never examined again. For every word you iterate over in the comprehension, a new result is added to the result list. So the next word is "the" and your place ("of the New York") doesn't start with "the", so no new result is added.
I assume the result you got eventually is the concatenation of your place variables. A simpler to read and understand procedural version would be (untested):
results = []
for place in places:
for word in words:
if place.startswith(word):
place = place.replace(word, "").strip()
results.append(place)
Keep in mind that replace() will remove the word anywhere in the string, even if it occurs as a simple substring. You can avoid this by using regexes with a pattern something like ^the\b.
| How to remove list of words from a list of strings | Sorry if the question is bit confusing. This is similar to this question
I think this the above question is close to what I want, but in Clojure.
There is another question
I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed.
Hope I made myself clear.
I think that this is due to the fact that strings in python are immutable.
I have a list of noise words that need to be removed from a list of strings.
If I use the list comprehension, I end up searching the same string again and again. So, only "of" gets removed and not "the". So my modified list looks like this
places = ['New York', 'the New York City', 'at Moscow' and many more]
noise_words_list = ['of', 'the', 'in', 'for', 'at']
for place in places:
stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)]
I would like to know as to what mistake I'm doing.
| [
"Without regexp you could do like this:\nplaces = ['of New York', 'of the New York']\n\nnoise_words_set = {'of', 'the', 'at', 'for', 'in'}\nstuff = [' '.join(w for w in place.split() if w.lower() not in noise_words_set)\n for place in places\n ]\nprint stuff\n\n",
"Here is my stab at it. This uses... | [
15,
11,
4,
1
] | [] | [] | [
"list_comprehension",
"python",
"regex",
"stop_words"
] | stackoverflow_0003510846_list_comprehension_python_regex_stop_words.txt |
Q:
Is there any generic binary protocol codec library for python?
There is nice one for java - MINA.
Once I've heard that there is something similar for python. But can't remind.
EDIT:
to be more specific, I would like to have a tool which would help me to create a coded for some binary stream.
EDIT2:
I'd like to list solutions here (thanks Scott for related topics)
Listed in order i'd use it.
bitstring (great documentation, which i'll choose)
hachoir
BitVector (to cryptic at the first glance)
bitarray
struct (python std)
bitmanipulation tut
A:
python has pack/unpack in the standard lib that can be used to interpret binary data and map them to structs
see "11.3. Working with Binary Data Record Layouts" here http://docs.python.org/tutorial/stdlib2.html
or here http://docs.python.org/library/struct.html
A:
Have you tried the bitstring module? (Full disclosure: I wrote it).
It's designed to make constructing and parsing binary data as simple as possible. Take a look at a few examples to see if it's anything like you need.
This snippet does some parsing of a H.264 video file:
from bitstring import ConstBitStream
s = ConstBitStream(filename='somefile.h264')
profile_idc = s.read('uint:8')
# Multiple reads in one go returns a list:
constraint_flags = s.readlist('4*uint:1')
reserved_zero_4bits = s.read('bin:4')
level_idc = s.read('uint:8')
seq_parameter_set_id = s.read('ue')
if profile_idc in [100, 110, 122, 244, 44, 83, 86]:
chroma_format_idc = s.read('ue')
if chroma_format_idc == 3:
separate_colour_plane_flag = s.read('uint:1')
bit_depth_luma_minus8 = s.read('ue')
bit_depth_chroma_minus8 = s.read('ue')
...
| Is there any generic binary protocol codec library for python? | There is nice one for java - MINA.
Once I've heard that there is something similar for python. But can't remind.
EDIT:
to be more specific, I would like to have a tool which would help me to create a coded for some binary stream.
EDIT2:
I'd like to list solutions here (thanks Scott for related topics)
Listed in order i'd use it.
bitstring (great documentation, which i'll choose)
hachoir
BitVector (to cryptic at the first glance)
bitarray
struct (python std)
bitmanipulation tut
| [
"python has pack/unpack in the standard lib that can be used to interpret binary data and map them to structs \nsee \"11.3. Working with Binary Data Record Layouts\" here http://docs.python.org/tutorial/stdlib2.html\nor here http://docs.python.org/library/struct.html\n",
"Have you tried the bitstring module? (Ful... | [
5,
5
] | [] | [] | [
"binary",
"protocols",
"python"
] | stackoverflow_0003511217_binary_protocols_python.txt |
Q:
rewrite small piece of python code
I have lots of small pieces of code that look like:
for it in <iterable>:
if <condition>:
return True/False
Is there a way I can rewrite this piece of code with a lambda expression ? I know I can factor it out in a small method/function, but I am looking for some lambda thing if it can be done.
A:
Use the built-in any function.
e.g.
any(<condition> for it in <iterable>) # return True on <condition>
A:
In addition to what everyone else has said, for the reverse case:
for it in <iterable>:
if <condition>:
return False
return True
use all():
b = all(<condition> for it in <iterable>)
A:
Here is a simple example which returns True if any of the objects in it is equal to 2. by using the map function:
any(map(lambda x: x==2, it))
Change the lambda expression to reflect your condition.
Another nice way is to use any with a list comprehension:
any([True for x in it if x==2])
or alternatively, a generator expression:
any(x==2 for x in it)
A:
if you want to check the condition for every item of iterable you can use
listcomprehensions to to this
b = [ x == whatever for x in a ]
you can combine this with any if you only need to know if there is one element
that evals to true for your condition
b = any(x == whatever for x in a)
| rewrite small piece of python code | I have lots of small pieces of code that look like:
for it in <iterable>:
if <condition>:
return True/False
Is there a way I can rewrite this piece of code with a lambda expression ? I know I can factor it out in a small method/function, but I am looking for some lambda thing if it can be done.
| [
"Use the built-in any function.\ne.g. \nany(<condition> for it in <iterable>) # return True on <condition>\n\n",
"In addition to what everyone else has said, for the reverse case:\nfor it in <iterable>:\n if <condition>:\n return False\nreturn True\n\nuse all():\nb = all(<condition> for it in <iterable... | [
6,
1,
0,
0
] | [] | [] | [
"python",
"refactoring"
] | stackoverflow_0003511115_python_refactoring.txt |
Q:
Country-based Super User Access, and modifiying Django Auth
I'm looking to give super user access to users of a program I'm devving.
All the entities have a country id value, so i'm just lookign to hook up my user model to have a country ID
Looking at Django Auth, It should be nice and easy to add a super_user_country_id field.
However, how frowned upon is it to modify the core django classes?
Is there any easier way to go about this or?
A:
At the moment, the recommended way is to create a Profile model and link it to the User model with a OneToOneField or a ForeignKey (depending on your requirements). Here's a good tutorial on the topic.
The Django devs have repeatedly expressed their intent to make extending the User model more straightforward, but AFAIK, no concrete design has been proposed, yet.
A:
Adding a custom UserProfile would be one way to go about this. UserProfile can link to Country and you can prevent users based on their UserProfile. I found James Bennett's article on extending the User model useful when I had a similar requirement.
It is generally not a good idea to patch auth (or other built in) classes. Custom patches can become a pain to maintain and keep up to date.
| Country-based Super User Access, and modifiying Django Auth | I'm looking to give super user access to users of a program I'm devving.
All the entities have a country id value, so i'm just lookign to hook up my user model to have a country ID
Looking at Django Auth, It should be nice and easy to add a super_user_country_id field.
However, how frowned upon is it to modify the core django classes?
Is there any easier way to go about this or?
| [
"At the moment, the recommended way is to create a Profile model and link it to the User model with a OneToOneField or a ForeignKey (depending on your requirements). Here's a good tutorial on the topic.\nThe Django devs have repeatedly expressed their intent to make extending the User model more straightforward, bu... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003511620_django_python.txt |
Q:
Auto-adjusting size for Tkinter frame
I'm working on a gui and I'd like to know how to adjust the size of the menus of a frame in order to have them take all the horizontal space of the frame.
The problem has changed : now the menu buttons are ok when the window is in normal size but when I resize it the menu buttons drop in the middle of the window. How can I make them stick to the top of the frame ?
rgds,
A:
Your question lacks enough detail to give you a good answer. Are you creating a menubar by putting menu buttons in a frame? If so, that's the wrong way to do it. Create a menu widget and assign it to the menu property of the main window and you'll end up with standard menus that behave normally.
Here's a simple example:
import Tkinter
root = Tkinter.Tk()
menubar = Tkinter.Menu(root)
root.config(menu=menubar)
fileMenu = Tkinter.Menu(menubar, tearoff=False)
editMenu = Tkinter.Menu(menubar, tearoff=False)
menubar.add_cascade(label="File",underline=0, menu=fileMenu)
menubar.add_cascade(label="Edit",underline=0, menu=editMenu)
fileMenu.add_command(label="Open...", underline=0)
fileMenu.add_command(label="Save", underline=0)
fileMenu.add_separator()
fileMenu.add_command(label="Exit", underline=1)
editMenu.add_command(label="Cut", underline=2)
editMenu.add_command(label="Copy", underline=0)
editMenu.add_command(label="Paste", underline=0)
root.mainloop()
| Auto-adjusting size for Tkinter frame | I'm working on a gui and I'd like to know how to adjust the size of the menus of a frame in order to have them take all the horizontal space of the frame.
The problem has changed : now the menu buttons are ok when the window is in normal size but when I resize it the menu buttons drop in the middle of the window. How can I make them stick to the top of the frame ?
rgds,
| [
"Your question lacks enough detail to give you a good answer. Are you creating a menubar by putting menu buttons in a frame? If so, that's the wrong way to do it. Create a menu widget and assign it to the menu property of the main window and you'll end up with standard menus that behave normally. \nHere's a simple ... | [
0
] | [] | [] | [
"menu",
"python",
"tkinter"
] | stackoverflow_0003511791_menu_python_tkinter.txt |
Q:
What does %d mean in struct.pack?
I was reading though a library of python code, and I'm stumped by this statement:
struct.pack( "<ii%ds"%len(value), ParameterTypes.String, len(value), value.encode("UTF8") )
I understand everything but%d, and I'm not sure why the length of value is being packed in twice.
As I understand it, the structure will have little endian encoding (<) and will contain two integers (ii) followed by %d, followed by a string (s).
What is the significance of %d?
A:
Aarrrgh the mind boggles ....
@S.Lott: """I don't think the number is particularly important, since Python will tend to pack correctly without it.""" -1. Don't think; investigate. Without a number means merely that the number defaults to 1. Tends to pack correctly??? Perhaps you think that struct.pack("s", foo) works the same way as "%s" % foo? It doesn't; docs say """For the 's' format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters. For packing, the string is truncated or padded with null bytes as appropriate to make it fit."""
@Brendan: -1. value is not an array (whatever that is); it is patently obviously intended to be a unicode string ... lookee here: value.encode("UTF8")
@Matt Ellen: The line of code that you quote is severely broken. If there are any non-ASCII characters in value, data will be lost.
Let's break it down:
`struct.pack("<ii%ds"%len(value), ParameterTypes.String, len(value), value.encode("UTF8"))`
Reduce problem space by removing the first item
struct.pack("<i%ds"%len(value), len(value), value.encode("UTF8"))
Now let's suppose that value is u'\xff\xff', so len(value) is 2.
Let v8 = value.encode('UTF8') i.e. '\xc3\xbf\xc3\xbf'.
Note that len(v8) is 4. Is the penny dropping yet?
So what we now have is
struct.pack("<i2s", 2, v8)
The number 2 is packed as 4 bytes, 02 00 00 00. The 4-byte string v8 is TRUNCATED (by the length 2 in "2s") to length two. DATA LOSS. FAIL.
The correct way to do what is presumably wanted is:
v8 = value.encode('UTF8')
struct.pack("<ii%ds" % len(v8), ParameterTypes.String, len(v8), v8)
A:
It is an ordinary string format which is being used to create the struct format
Try reading it to begin with as an ordinary string (forget struct for the moment) ...
"<ii%ds" % len(value)
If, for example, the length of the value iterable is 4 then the string will be, <ii4s. This is then passed to struct.pack ready to pack two integers followed by a string of length four bytes from the value iterable
A:
The significance of %d is that it's a formatting parameter for strings:
String Formatting Operations
When broken apart, "<ii%ds" % len(value) is a bit easier to understand. It is replacing the %d conversion indicator in the string with the return value of len(value), typecast appropriately.
>>> str = "<ii%ds"
>>> str % 5
'<ii5s'
>>> str % 3
'<ii3s'
A:
The %d means this works in two steps.
Step 1.
"<ii%ds"%len(value)
Creates the struct formatting string of "<ii...some number...s".
Step 2.
The resulting formatting string is applied to three values
ParameterTypes.String, len(value), value.encode("UTF8")
A:
It's used to specify that a string (value) of len(value) characters is to be packed after those two integers.
If, for instance, value contained "boo" then the actual format specifier for pack would be "<ii3s".
| What does %d mean in struct.pack? | I was reading though a library of python code, and I'm stumped by this statement:
struct.pack( "<ii%ds"%len(value), ParameterTypes.String, len(value), value.encode("UTF8") )
I understand everything but%d, and I'm not sure why the length of value is being packed in twice.
As I understand it, the structure will have little endian encoding (<) and will contain two integers (ii) followed by %d, followed by a string (s).
What is the significance of %d?
| [
"Aarrrgh the mind boggles ....\n@S.Lott: \"\"\"I don't think the number is particularly important, since Python will tend to pack correctly without it.\"\"\" -1. Don't think; investigate. Without a number means merely that the number defaults to 1. Tends to pack correctly??? Perhaps you think that struct.pack(\"s\... | [
2,
1,
1,
0,
0
] | [] | [] | [
"python",
"struct"
] | stackoverflow_0003510814_python_struct.txt |
Q:
Does this PyList_Append(list, Py_BuildValue(...)) leak?
Does this leak?:
static PyObject* foo(PyObject* self, PyObject* args){
PyObject* list = PyList_New(0);
for(int i = 0; i < 100; i++)
// leak? does PyList_Append increment ref of the temporary?
PyList_Append(list, Py_BuildValue("i", 42));
return list;
}
Though, I suppose it's better to do this, in any case?:
static PyObject* foo(PyObject* self, PyObject* args){
PyObect* list = PyList_New(100);
for(int i = 0; i < 100; i++)
PyList_SetItem(list, i, Py_BuildValue("i", 42));
return list;
}
A:
PyList_Append does indeed increment the reference counter, so, yes, the first example will leak. PyList_SetItem does not, making it a weird exception.
The second option will be slightly more efficient because the list will be allocated to excatly the right size and Python does have to dynamically resize it as items are appended.
| Does this PyList_Append(list, Py_BuildValue(...)) leak? | Does this leak?:
static PyObject* foo(PyObject* self, PyObject* args){
PyObject* list = PyList_New(0);
for(int i = 0; i < 100; i++)
// leak? does PyList_Append increment ref of the temporary?
PyList_Append(list, Py_BuildValue("i", 42));
return list;
}
Though, I suppose it's better to do this, in any case?:
static PyObject* foo(PyObject* self, PyObject* args){
PyObect* list = PyList_New(100);
for(int i = 0; i < 100; i++)
PyList_SetItem(list, i, Py_BuildValue("i", 42));
return list;
}
| [
"PyList_Append does indeed increment the reference counter, so, yes, the first example will leak. PyList_SetItem does not, making it a weird exception.\nThe second option will be slightly more efficient because the list will be allocated to excatly the right size and Python does have to dynamically resize it as it... | [
29
] | [] | [] | [
"c",
"python"
] | stackoverflow_0003512414_c_python.txt |
Q:
How to get read-only objects from database?
I'd like to query the database and get read-only objects with session object. I need to save the objects in my server and use them through the user session. If I use a object outside of the function that calls the database, I get this error:
"DetachedInstanceError: Parent instance is not bound to a Session; lazy load operation of attribute 'items' cannot proceed"
I don't need to make any change in those objects, so I don't need to load them again.
Is there any way that I can get that?
Thanks in advance!
A:
You must load the parent object again.
| How to get read-only objects from database? | I'd like to query the database and get read-only objects with session object. I need to save the objects in my server and use them through the user session. If I use a object outside of the function that calls the database, I get this error:
"DetachedInstanceError: Parent instance is not bound to a Session; lazy load operation of attribute 'items' cannot proceed"
I don't need to make any change in those objects, so I don't need to load them again.
Is there any way that I can get that?
Thanks in advance!
| [
"You must load the parent object again.\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003513433_python_sqlalchemy.txt |
Q:
What possibilities exist to build an installer for a windows application on Linux (install target=windows, build environment=Linux)
After playing around with NSIS (Nullsoft Scriptable Installation System) for a few days, I really feel the pain it's use brings me. No wonder, the authors claim it's scripting implementation is a "mixture of PHP and Assembly".
So, I hope there is something better to write installation procedures to get Windows programs installed, while creating the installation package on Linux.
But I did not find anything yet. Wix looks promising, but seems not really to run on Linux, Python can create .msi files - but only when running on Windows.
Izpack is out of the game because it requires Java for the installer to run on the target system.
Our app to be installed is a python app (and I'm even thinking about scripting the whole install myself in Python).
Any other ideas?
Forgot to say: Free/OpenSource apps preferred.
Not only because of cost, because of the power to control and adjust everything.
We might be willing to pay professional support if it helps us getting to our goals fast, but we also want to have full control over the build system.
A:
You may be interested by BitRock
A:
You might try looking at InstallAnywhere, but it may require Java.
A:
Try running InnoSetup under Wine. It should work unless you have some very specific needs. InnoSetup is open source, BTW.
A:
It seems that pyinstaller might do the trick. I'm also looking for something like what you need. I have not tried it yet ...
| What possibilities exist to build an installer for a windows application on Linux (install target=windows, build environment=Linux) | After playing around with NSIS (Nullsoft Scriptable Installation System) for a few days, I really feel the pain it's use brings me. No wonder, the authors claim it's scripting implementation is a "mixture of PHP and Assembly".
So, I hope there is something better to write installation procedures to get Windows programs installed, while creating the installation package on Linux.
But I did not find anything yet. Wix looks promising, but seems not really to run on Linux, Python can create .msi files - but only when running on Windows.
Izpack is out of the game because it requires Java for the installer to run on the target system.
Our app to be installed is a python app (and I'm even thinking about scripting the whole install myself in Python).
Any other ideas?
Forgot to say: Free/OpenSource apps preferred.
Not only because of cost, because of the power to control and adjust everything.
We might be willing to pay professional support if it helps us getting to our goals fast, but we also want to have full control over the build system.
| [
"You may be interested by BitRock\n",
"You might try looking at InstallAnywhere, but it may require Java.\n",
"Try running InnoSetup under Wine. It should work unless you have some very specific needs. InnoSetup is open source, BTW.\n",
"It seems that pyinstaller might do the trick. I'm also looking for somet... | [
2,
0,
0,
0
] | [] | [] | [
"installation",
"linux",
"python",
"windows"
] | stackoverflow_0001562999_installation_linux_python_windows.txt |
Q:
(Unintentionally) skipping items when iterating over a list
I have a list and I want to remove from it the items that don't appear in another list. I've tried the following:
for w in common:
for i in range(1,n):
if not w in words[i]:
common.remove(w)
However, this fails to remove some of the items. Adding print statements for w in common:
for i in range(1,n):
print w
if not w in words[i]:
print w
common.remove(w)results in some w never being printed. Any ideas as to what's happening? I assume the answer's simple and I just don't have adequate Python knowledge, but I'm completely out of ideas.
A:
I think you can simplify your statement with something like this:
filtered = filter(lambda x: x in words, common)
That's checking each element in common for it's presence in words and removing based on it. You may need to try x not in words depending on what you're desired result is, but I think that should come close.
I wanted to add one other approach, that might also come close, though I would need to see examples of your initial lists to test it fully.
filtered = [x for x in common if x in words]
-- EDITED -- I had the syntax in the list comprehension backwards, but caught it after I saw the comment. Thanks!
A:
You can't delete items from the list you're iterating over. Try iterating over a copy of the list instead.
for w in common[:]:
for i in range(1,n):
if not w in words[i]:
common.remove(w)
A:
From the Python docs:
It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.
A:
You are modifying the list while trying to iterate through it.
You could modify the first line of the code to iterate through a copy of the list (using common[:]).
A:
If you delete (say) item 5, then the old item 6 will now be item 5. So if you think to move to item 6 you will skip it.
Is it possible to iterate backwards over that list? Then index-changes happen in parts you already processed.
| (Unintentionally) skipping items when iterating over a list | I have a list and I want to remove from it the items that don't appear in another list. I've tried the following:
for w in common:
for i in range(1,n):
if not w in words[i]:
common.remove(w)
However, this fails to remove some of the items. Adding print statements for w in common:
for i in range(1,n):
print w
if not w in words[i]:
print w
common.remove(w)results in some w never being printed. Any ideas as to what's happening? I assume the answer's simple and I just don't have adequate Python knowledge, but I'm completely out of ideas.
| [
"I think you can simplify your statement with something like this:\nfiltered = filter(lambda x: x in words, common)\n\nThat's checking each element in common for it's presence in words and removing based on it. You may need to try x not in words depending on what you're desired result is, but I think that should c... | [
8,
3,
3,
2,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003513531_list_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.