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:
distributing independent python app to other machines
I created independent python app using cxfreeze under linux and can run it other machines without python and other dependencies.
But while doing it for mac OS X, in other machines the app searches for the following python installed location which actually present in the machine where it is frozen.
"/Library/Frameworks/Python.framework/Versions/3.1/Python"
How to execute this app without this dependency?
A:
Try py2app for Mac OS X. (And py2exe for Windows.)
| distributing independent python app to other machines | I created independent python app using cxfreeze under linux and can run it other machines without python and other dependencies.
But while doing it for mac OS X, in other machines the app searches for the following python installed location which actually present in the machine where it is frozen.
"/Library/Frameworks/Python.framework/Versions/3.1/Python"
How to execute this app without this dependency?
| [
"Try py2app for Mac OS X. (And py2exe for Windows.)\n"
] | [
1
] | [] | [] | [
"cx_freeze",
"distribution",
"python"
] | stackoverflow_0003201642_cx_freeze_distribution_python.txt |
Q:
What is the easiest way to access a a computers microphone in Python?
I need to get some numbers so I can generate random numbers using ambient sound.
I want something on this level
pseudo code:
import microphone
p = pitch.get()
print p
Edit:
This is in Windows 7, BTW
A:
Depends on the platform. On Windows, this SO question has some answers; for Linux, try this one instead.
A:
I don't know if it is as easy as you would like but I know that it is possible to access the microphone with tksnack. I think it is available on main platforms.
microphone access should be possible with the record method of the Sound class
I hope it helps
| What is the easiest way to access a a computers microphone in Python? | I need to get some numbers so I can generate random numbers using ambient sound.
I want something on this level
pseudo code:
import microphone
p = pitch.get()
print p
Edit:
This is in Windows 7, BTW
| [
"Depends on the platform. On Windows, this SO question has some answers; for Linux, try this one instead.\n",
"I don't know if it is as easy as you would like but I know that it is possible to access the microphone with tksnack. I think it is available on main platforms.\nmicrophone access should be possible wit... | [
1,
0
] | [] | [] | [
"audio",
"microphone",
"python"
] | stackoverflow_0003217885_audio_microphone_python.txt |
Q:
Scripting Languages
I am looking for a good scripting language to link to my program.
I am looking for 2 important attributes:
Scripting language should be hard linked into the executable (not requiring 3rd party
installations). This is important to me to simplify distribution.
Scripting should allow some run-time debugging option (When running a script inside my program I would like to easily run it inside a debugger while it is running in the context of my program)
Can python,lua or some other language supply me with this?
A:
Both Lua and Python can provide the features you mention, so choosing one of them will depend on other criteria.
Lua is a lighter weight solution, it will have a much smaller disk footprint and likely a smaller memory overhead than Python too. For some uses it may be faster. Python has a much richer standard library, more mature third party libraries and a more expressive language.
Both have been embedded into major applications. Python can be found in Blender, OpenOffice and Civilization 4. Lua can be found in World of Warcraft and Adobe Lightroom. I'd recommend looking at a few tutorials for each and the facilities available to embed them in your application and just choose the one that fits your brain best.
A:
Lua is designed for this:
static linking? check!
debugging? check!
A:
Typically, Lua is the better choice for embedding into another project. Python is better as a standalone platform because the library support is so much broader. See Lua Versus Python for more details.
Personally, I use both very frequently depending on the job at hand. I always use Lua for embedding into C/C++ applications or scripting functionality that is imported from C/C++ shared libraries (i.e. a DLL). Python is always my first choice for standalone tasks that do not require low-level C/C++ code.
A:
I'd put my two cents in for python. I don't know a lot of the details, but the computer graphics suite blender does a wonderful job of implementing python scripting.
As far as I can tell in blender 2.5 the interpreter is run from inside the executable,
import sys
sys.executable
shows /blender/blender.exe
and there is good debugging support, it even has a full interactive interpreter inside.
For more info check out: http://www.blender.org/
A:
I really like Lua for embedding, but just as another alternative, JavaScript is easily embeddable in C, C++ (SpiderMonkey and V8) and Java (Rhino) programs.
A:
In addition to Tcl, Lua, and Javascript (all already mentioned), Guile is another language designed explicitly for this.
A:
I'll add Tcl to the mix. It's designed to be easily embedded into other programs.
| Scripting Languages | I am looking for a good scripting language to link to my program.
I am looking for 2 important attributes:
Scripting language should be hard linked into the executable (not requiring 3rd party
installations). This is important to me to simplify distribution.
Scripting should allow some run-time debugging option (When running a script inside my program I would like to easily run it inside a debugger while it is running in the context of my program)
Can python,lua or some other language supply me with this?
| [
"Both Lua and Python can provide the features you mention, so choosing one of them will depend on other criteria.\nLua is a lighter weight solution, it will have a much smaller disk footprint and likely a smaller memory overhead than Python too. For some uses it may be faster. Python has a much richer standard libr... | [
13,
9,
7,
2,
1,
1,
0
] | [] | [] | [
"dynamic_languages",
"lua",
"programming_languages",
"python",
"scripting"
] | stackoverflow_0003193012_dynamic_languages_lua_programming_languages_python_scripting.txt |
Q:
Virtuozzo and automating commands with Python's subprocesses
I'm dealing with a Virtuozzo server and want to automate logging into each container and issuing a few commands in Python by creating a subprocess for 'vzctl enter '.
Here is the snippet that I'm working on right now -
#!/usr/bin/python
import subprocess
print 'Start'
proc = subprocess.Popen(['vzctl enter 123'],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True)
print proc.communicate('whoami')[0]
print 'Finished'
But the output I see everytime is -
Unable to get term attr: Invalid argument
Unable to restore term attr: Invalid argument
I really think this is a BASH error, can anyone give me a suggestion?
A:
Looks like vzctl expects stdin/stdout to be a terminal. You can find out which by experimenting (in bash):
$ echo whoami | vzctl enter 123 # stdin is not a tty
$ vzctl enter 123 | cat # stdout is not a tty
whoami
<ctrl-d>
You can use the pty module from the standard library to create pseudottys, but that module is very low-level.
There's a 3rd-party module called pexpect that might fit the bill.
| Virtuozzo and automating commands with Python's subprocesses | I'm dealing with a Virtuozzo server and want to automate logging into each container and issuing a few commands in Python by creating a subprocess for 'vzctl enter '.
Here is the snippet that I'm working on right now -
#!/usr/bin/python
import subprocess
print 'Start'
proc = subprocess.Popen(['vzctl enter 123'],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True)
print proc.communicate('whoami')[0]
print 'Finished'
But the output I see everytime is -
Unable to get term attr: Invalid argument
Unable to restore term attr: Invalid argument
I really think this is a BASH error, can anyone give me a suggestion?
| [
"Looks like vzctl expects stdin/stdout to be a terminal. You can find out which by experimenting (in bash):\n$ echo whoami | vzctl enter 123 # stdin is not a tty\n\n$ vzctl enter 123 | cat # stdout is not a tty\nwhoami\n<ctrl-d>\n\nYou can use the pty module from the standard library to create pseudottys... | [
2
] | [] | [] | [
"python",
"subprocess",
"virtuozzo"
] | stackoverflow_0003198617_python_subprocess_virtuozzo.txt |
Q:
A neat way of extending a class attribute in subclasses
Let's say I have the following class
class Parent(object):
Options = {
'option1': 'value1',
'option2': 'value2'
}
And a subclass called Child
class Child(Parent):
Options = Parent.Options.copy()
Options.update({
'option2': 'value2',
'option3': 'value3'
})
I want to be able to override or add options in the child class. The solution I'm using works. But I'm sure there is a better way of doing it.
EDIT
I don't want to add options as class attributes because I have other class attributes that aren't options and I prefer to keep all options in one place. This is just a simple example, the actual code is more complicated than that.
A:
Semantically equivalent to your code but arguably neater:
class Child(Parent):
Options = dict(Parent.Options,
option2='value2',
option3='value3')
Remember, "life is better without braces", and by calling dict explicitly you can often avoid braces (and extra quotes around keys that are constant identifier-like strings).
See http://docs.python.org/library/stdtypes.html#dict for more details -- the key bit is "If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained", i.e. keyword args override key-value associations in the positional arg, just like the update method lets you override them).
A:
One way would be to use keyword arguments to dict to specify additional keys:
Parent.options = dict(
option1='value1',
option2='value2',
)
Child.options = dict(Parent.options,
option2='value2a',
option3='value3',
)
If you want to get fancier, then using the descriptor protocol you can create a proxy object that will encapsulate the lookup. (just walk the owner.__mro__ from the owner attribute to the __get__(self, instance, owner) method). Or even fancier, crossing into the probably-not-a-good-idea territory, metaclasses/class decorators.
A:
After thinking more about it, and thanks to @SpliFF suggestion this is what I came up with:
class Parent(object):
class Options:
option1 = 'value1'
option2 = 'value2'
class Child(Parent):
class Options(Parent.Options):
option2 = 'value2'
option3 = 'value3'
I'm still open to better solutions though.
A:
Why not just use class attributes?
class Parent(object):
option1 = 'value1'
option2 = 'value2'
class Child(Parent):
option2 = 'value2'
option3 = 'value3'
A:
class ParentOptions:
option1 = 'value1'
option2 = 'value2'
class ChildOptions(ParentOptions):
option2 = 'value2'
option3 = 'value3'
class Parent(object):
options = ParentOptions()
class Child(Parent):
options = ChildOptions()
A:
Here is a way using a metaclass
class OptionMeta(type):
@property
def options(self):
result = {}
for d in self.__mro__[::-1]:
result.update(getattr(d,'_options',{}))
return result
class Parent(object):
__metaclass__ = OptionMeta
_options = dict(
option1='value1',
option2='value2',
)
class Child(Parent):
_options = dict(
option2='value2a',
option3='value3',
)
print Parent.options
print Child.options
| A neat way of extending a class attribute in subclasses | Let's say I have the following class
class Parent(object):
Options = {
'option1': 'value1',
'option2': 'value2'
}
And a subclass called Child
class Child(Parent):
Options = Parent.Options.copy()
Options.update({
'option2': 'value2',
'option3': 'value3'
})
I want to be able to override or add options in the child class. The solution I'm using works. But I'm sure there is a better way of doing it.
EDIT
I don't want to add options as class attributes because I have other class attributes that aren't options and I prefer to keep all options in one place. This is just a simple example, the actual code is more complicated than that.
| [
"Semantically equivalent to your code but arguably neater:\nclass Child(Parent):\n Options = dict(Parent.Options,\n option2='value2',\n option3='value3')\n\nRemember, \"life is better without braces\", and by calling dict explicitly you can often avoid braces (and extra quotes around keys that are const... | [
21,
8,
6,
4,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0000907324_python.txt |
Q:
how to use session without having to pass it [SqlAlchemy]
I want to check diferent values in the DB and create a new value, so i need to query and i don't know if i have to create a session in my SQLAlchemy class or how do i have to do it? using session like a global?, i didn't find in documentation.
Somethin like this:
class MyClass(Base):
__tablename__ = 'my_class'
__table_args__ = (UniqueConstraint('key', 'key2'),
{}
)
id = Column(Integer, Sequence('my_class_id'), primary_key=True)
key = Column(String(30), nullable= False) #unique together key2
key2 = Column(String(30), nullable = False)
value = Column(Integer, nullable=False)
def __init__(self, key, key2):
#check if exist key and key2
values = session.query(MyClass.value).filter(MyClass.key == self.key).\
filter(MyClass.key2 == self)
if values:
raise IntegrityError
#get biggest value
value = session.query(MyClass.value).filter(MyClass.key = self.key).order_by(asc(MyClass.value)) #I'm not shure if i need 'asc'
#no value new key and key2
if not value:
self.key = key
self.key2 = key2
self.value = '000'
return
#i used a single table beacuse is easier to understand
#in this example
self.key = key
self.key2 = key
self.value = increment(value.first())
I'm using SQLALchemy 6.2 and declarative
Thanks
A:
I found here that we can do Session.object_session(self):
def new_value(self):
#not really DRY
#the object has to be binded with some session first.
session = Session.object_session(self) # << this is the important stuff
#check if exist key and key2
values = session.query(MyClass.value).filter(MyClass.key == self.key).\
filter(MyClass.key2 == self)
if values:
return #None
#get biggest value
value = session.query(MyClass.value).\
filter(MyClass.key = self.key).\
order_by(desc(MyClass.value))
return increment(value.first())
A:
You will have to do your own session management -- e.g. define a module-global session object.
For example, Pylons applications define their session like this:
from sqlalchemy.orm import scoped_session, sessionmaker
Session = scoped_session(sessionmaker())
and then later bind it to an engine with
Session.configure(bind=engine)
Using scoped_session will mean that your code is thread-safe (each thread will use its own session).
| how to use session without having to pass it [SqlAlchemy] | I want to check diferent values in the DB and create a new value, so i need to query and i don't know if i have to create a session in my SQLAlchemy class or how do i have to do it? using session like a global?, i didn't find in documentation.
Somethin like this:
class MyClass(Base):
__tablename__ = 'my_class'
__table_args__ = (UniqueConstraint('key', 'key2'),
{}
)
id = Column(Integer, Sequence('my_class_id'), primary_key=True)
key = Column(String(30), nullable= False) #unique together key2
key2 = Column(String(30), nullable = False)
value = Column(Integer, nullable=False)
def __init__(self, key, key2):
#check if exist key and key2
values = session.query(MyClass.value).filter(MyClass.key == self.key).\
filter(MyClass.key2 == self)
if values:
raise IntegrityError
#get biggest value
value = session.query(MyClass.value).filter(MyClass.key = self.key).order_by(asc(MyClass.value)) #I'm not shure if i need 'asc'
#no value new key and key2
if not value:
self.key = key
self.key2 = key2
self.value = '000'
return
#i used a single table beacuse is easier to understand
#in this example
self.key = key
self.key2 = key
self.value = increment(value.first())
I'm using SQLALchemy 6.2 and declarative
Thanks
| [
"I found here that we can do Session.object_session(self):\ndef new_value(self):\n #not really DRY\n #the object has to be binded with some session first.\n session = Session.object_session(self) # << this is the important stuff\n\n #check if exist key and key2\n values = session.query(MyClass.valu... | [
1,
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003179108_python_sqlalchemy.txt |
Q:
sending raw bits to the terminal in python
As I understand it, files like /dev/urandom provide just a constant stream of bits. The terminal emulator then tries to interpret them as strings, which results in a mess of unrecognised characters.
How would I go about doing the same thing in python, send a string of ones and zeros to the terminal as "raw bits"?
edit
I may have to clarify:
Say for example the string I want to "print" is 1011100. On an ascii system, the output should be "\". If I cat /dev/urandom, it provides a constant stream of bits. Which get printed like this: "���c�g/�t]+__��-�;". That's what I want.
A:
Stephano: the key is the incomplete answer by "@you" above - the chr function :
import random, sys
for i in xrange(500):
sys.stdout.write(chr(random.randrange(256)))
A:
Use the chr function. I takes an input between 0 and 255 and returns a string containing the character corresponding to that value.
A:
import sys, random
while True:
sys.stdout.write(chr(random.getrandbits(8)))
sys.stdout.flush()
A:
And from another question on StackOverflow you can get a _bin function.
def _bin(x, width):
return ''.join(str((x>>i)&1) for i in xrange(width-1,-1,-1))
Then simply put call _bin(ord(x), 8) where x is a character (string of length one)
| sending raw bits to the terminal in python | As I understand it, files like /dev/urandom provide just a constant stream of bits. The terminal emulator then tries to interpret them as strings, which results in a mess of unrecognised characters.
How would I go about doing the same thing in python, send a string of ones and zeros to the terminal as "raw bits"?
edit
I may have to clarify:
Say for example the string I want to "print" is 1011100. On an ascii system, the output should be "\". If I cat /dev/urandom, it provides a constant stream of bits. Which get printed like this: "���c�g/�t]+__��-�;". That's what I want.
| [
"Stephano: the key is the incomplete answer by \"@you\" above - the chr function :\nimport random, sys\n\nfor i in xrange(500):\n sys.stdout.write(chr(random.randrange(256)))\n\n",
"Use the chr function. I takes an input between 0 and 255 and returns a string containing the character corresponding to that valu... | [
3,
1,
0,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0003219598_linux_python.txt |
Q:
Can i take package of cpython?
I used cpython api to load py from C/C++.
But, if i want not setup cpython in client, can I take package dll of cpython in my program?
How to do that?
A:
You don't need to setup Python to embed it in applications. The core of the Python interpreter is available as a shared library which you can dynamically load in your application and distribute with it.
Read on embedding Python in the official docs. Also, this article seems nice and comprehensive for Linux. For Windows, read the notes here.
Here's another SO question that discusses this issue.
A:
Installer-builders like PyInstaller (cross-platform) and py2exe (Windows only) basically do that job for you in a general way, except that the executable at the heart of the produced package is their own instead of yours.
But basically, you can imitate their behavior in terms of setting up a .zip file with all the Python library modules you need (or just zip up everything in the standard python library if you want to allow python code running form your app to import anything from there), and follow the simple advice in the Embedding Python in Another Application section of the Python docs.
Note that embedding Python equals extending Python plus a little bit of code to initialize and finalize the interpreter itself and a little bit of packaging as I just mentioned; if you've never writted Python extensions I would suggest practicing that first since it's the most substantial part of the task (not all that hard with helpers such as boost python, but more work if you choose to do it as the "bare C" level instead).
A:
The Python license is probably hard to understand for a non-lawyer, non-native English speaker. So yes, you can redistribute the unmodified DLL as it contains the copyright notice within it.
It would be polite to give credit like "This program contains the Python Language Interpreter version X.XX http://python.org for more information" or similar somewhere in the program or documentation.
| Can i take package of cpython? | I used cpython api to load py from C/C++.
But, if i want not setup cpython in client, can I take package dll of cpython in my program?
How to do that?
| [
"You don't need to setup Python to embed it in applications. The core of the Python interpreter is available as a shared library which you can dynamically load in your application and distribute with it. \nRead on embedding Python in the official docs. Also, this article seems nice and comprehensive for Linux. For... | [
1,
1,
0
] | [] | [] | [
"c",
"dll",
"installation",
"python"
] | stackoverflow_0003219699_c_dll_installation_python.txt |
Q:
Perceptual Hash Algorithms in Python or PHP?
I've been exposed via StackOverflow to pHash, a C++ perceptual hash library for audio, video, images, and text fingerprinting - recently with preliminary bindings for PHP, C# and Java.
I'm interested in studying these algorithms and I'm wondering if there are any open-source pure Python or PHP implementations of the same / similar algorithm? This would make my life a lot easier.
A:
I have been searching on Google, but not much has come up. Since it seems you want the code for academic purposes, I would suggest:
Hit Wikipedia - look up each algorithm and get a feel for how it works
Check the pHash site's mailing list - I doubt you are the first person to be curious.
Email the authors and ask what sources they used (books, papers, etc.)
Use bookstore, library, etc. to find your own sources
I personally find that studying code is very ineffective at teaching algorithms (at first anyway, until you have a feel for the overall process).
| Perceptual Hash Algorithms in Python or PHP? | I've been exposed via StackOverflow to pHash, a C++ perceptual hash library for audio, video, images, and text fingerprinting - recently with preliminary bindings for PHP, C# and Java.
I'm interested in studying these algorithms and I'm wondering if there are any open-source pure Python or PHP implementations of the same / similar algorithm? This would make my life a lot easier.
| [
"I have been searching on Google, but not much has come up. Since it seems you want the code for academic purposes, I would suggest:\n\nHit Wikipedia - look up each algorithm and get a feel for how it works\nCheck the pHash site's mailing list - I doubt you are the first person to be curious.\nEmail the authors an... | [
1
] | [] | [] | [
"algorithm",
"hash",
"perception",
"php",
"python"
] | stackoverflow_0003216901_algorithm_hash_perception_php_python.txt |
Q:
How can I pass map into py with API?
C/C++ can use python API to load py.
But, only simple type is supported.
How can I pass map into py to be a dict with API?
Or, which methods are better?
A:
Use SWIG, which has some ready-made templates for various STL types. See this, for example.
A:
The Python C API supports C-level functionality (not C++ level one) -- basically, you can easily expose to Python things you could put in an extern C block (which doesn't include std::map &c) -- for other stuff, you need a bit more work. The nature of that work depends on what you're using to wrap your C++ code for Python consumption -- there are many options, including the bare C API, SWIG, SIP, Boost Python, Cython, ...
In the bare C API (which I assume is what you're using, judging from your question and tags), I would recommend making a custom object type -- maybe, these days, one subclassing collections.Mapping (MutableMapping if mutable, of course), as you would when implementing a mapping in Python -- and implementing the Mapping Object Structures plus the needed bits of a general type structure such as tp_iter and tp_iternext slots.
Of course, the key idea is that you'll implement item setting and getting, as well as iteration, by simply delegating to your chosen std::map and performing the needed type conversion and low-level fiddling (object allocation, reference counting) -- the latter is the part that higher-level frameworks for extending Python save you from having to do, essentially, but the "wrap and delegate" underlying architecture won't change by much.
| How can I pass map into py with API? | C/C++ can use python API to load py.
But, only simple type is supported.
How can I pass map into py to be a dict with API?
Or, which methods are better?
| [
"Use SWIG, which has some ready-made templates for various STL types. See this, for example.\n",
"The Python C API supports C-level functionality (not C++ level one) -- basically, you can easily expose to Python things you could put in an extern C block (which doesn't include std::map &c) -- for other stuff, you ... | [
1,
0
] | [] | [] | [
"api",
"c",
"c++",
"cpython",
"python"
] | stackoverflow_0003219611_api_c_c++_cpython_python.txt |
Q:
Scale legend box border, dashed and dotted lines when the figure size is changed with matplotlib
I'm trying to use matplotlib to prepare some figures for publication. In order to make the font sizes match the text of the manuscript I'm trying to create the figure in the final size to begin with, so that I avoid scaling the figure when inserting it into the manuscript.
The problem I'm having is that as the figure is then pretty small, I can scale font sizes, axis sizes, line widths etc., but what I've been unable to figure out is how to scale dashed or dotted lines, as well as the thickness of the legend border box. For a simplified and somewhat exaggerated example, consider
#!/usr/bin/python
small = True
from matplotlib import use
use('pdf')
from matplotlib import rc
rc('ps', usedistiller='xpdf')
rc('text', usetex=True)
if small:
figsize = (1.0, 0.5)
rc('font', size=2)
rc('axes', labelsize=2, linewidth=0.2)
rc('legend', fontsize=2, handlelength=10)
rc('xtick', labelsize=2)
rc('ytick', labelsize=2)
rc('lines', lw=0.2, mew=0.2)
rc('grid', linewidth=0.2)
else:
figsize = (8,8)
import numpy as np
x = np.arange(0, 10, 0.001)
y = np.sin(x)
import matplotlib.pyplot as plt
f = plt.figure(figsize=figsize)
a = f.add_subplot(111)
a.plot(x, y, '--', label='foo bar')
a.legend()
f.savefig('mplt.pdf')
If you change the first executable line to small = False you can see how it should look in "normal" size. Compared to the normal size, the small plot suffers from a legend box with too thick borders, and the dashed line is too coarse, i.e. too long dashes and too long distance between the dashes.
So my question is, is there a way to fix these two problems?
The matplotlib version I'm using is 0.99.1.2.
A:
To adjust the dashes, use
a.plot(x, y, '--', label='foo bar', dashes=(2,2))
and the legend box line width,
lg = a.legend()
fr = lg.get_frame()
fr.set_lw(0.2)
| Scale legend box border, dashed and dotted lines when the figure size is changed with matplotlib | I'm trying to use matplotlib to prepare some figures for publication. In order to make the font sizes match the text of the manuscript I'm trying to create the figure in the final size to begin with, so that I avoid scaling the figure when inserting it into the manuscript.
The problem I'm having is that as the figure is then pretty small, I can scale font sizes, axis sizes, line widths etc., but what I've been unable to figure out is how to scale dashed or dotted lines, as well as the thickness of the legend border box. For a simplified and somewhat exaggerated example, consider
#!/usr/bin/python
small = True
from matplotlib import use
use('pdf')
from matplotlib import rc
rc('ps', usedistiller='xpdf')
rc('text', usetex=True)
if small:
figsize = (1.0, 0.5)
rc('font', size=2)
rc('axes', labelsize=2, linewidth=0.2)
rc('legend', fontsize=2, handlelength=10)
rc('xtick', labelsize=2)
rc('ytick', labelsize=2)
rc('lines', lw=0.2, mew=0.2)
rc('grid', linewidth=0.2)
else:
figsize = (8,8)
import numpy as np
x = np.arange(0, 10, 0.001)
y = np.sin(x)
import matplotlib.pyplot as plt
f = plt.figure(figsize=figsize)
a = f.add_subplot(111)
a.plot(x, y, '--', label='foo bar')
a.legend()
f.savefig('mplt.pdf')
If you change the first executable line to small = False you can see how it should look in "normal" size. Compared to the normal size, the small plot suffers from a legend box with too thick borders, and the dashed line is too coarse, i.e. too long dashes and too long distance between the dashes.
So my question is, is there a way to fix these two problems?
The matplotlib version I'm using is 0.99.1.2.
| [
"To adjust the dashes, use\na.plot(x, y, '--', label='foo bar', dashes=(2,2))\n\nand the legend box line width,\nlg = a.legend()\nfr = lg.get_frame()\nfr.set_lw(0.2)\n\n"
] | [
9
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0003190798_matplotlib_plot_python.txt |
Q:
Updating my program, using a diff-based patch approach
Currently my program updates itself by downloading the latest .tar.gz file containing the source code, and extracting it over the current directory where the program lives. There are 2 "modes" of update - one for users running the Python source, and one if the user is running the program as a Windows exe.
Over time my program's filesize is becoming larger with each release, due to new images, libraries, documentation and code. However, sometimes only code changes occur from one release to another, so the user ends up re-downloading all the images, documentation etc over and over, when only there are only small code changes.
I was thinking that a more efficient approach would be to use a patch/diff based system where the program incrementally updates itself from one version to another by only downloading small change sets.
However, how should I do this? If the user is running version 0.38, and there is a 0.42 available, do they download 0.38->39; 0.39->40; 0.40->41, 0.41->42? How would I handle differences in binary files? (images, in my case).
I'd also have to maintain some repository containing all the patches, which isn't too bad. I'd just generate the diffs with each new release. But I guess it would be harder to do this to executables than to pure python code?
Any input is appreciated. Many thanks.
A:
I suggest that rather than reinventing your own update management system, you take a look at open source options, such as google updater (which was open sourced over a year ago as Omaha) -- I imagine the Windows focus is OK since you do specifically refer to Windows, but if you also need Mac support a similar functionality is offered in update engine (for Linux you probably want to work with the specific distribution's package management system rather than using any add-on one).
As you'll see in the omaha overview, the focus is not specifically on determining and applying "deltas" rather than full updates, but on automating the process for the user's convenience (and security, when updates address potential security issues). As for the differences, I would suggest behaving similar to version control systems like subversion (indeed, you can no doubt reuse much of svn's code) -- only text files are differenced, binary files' "differences" are all-or-nothing (for most binary file formats there's just too little gain -- if any -- in trying to send less than the whole new file, if changed at all; for images in particular, and more generally compressed files of all kinds, it's typical that a tiny change in the underlying content can produce huge changes in the resulting file).
If you think some or all of your binary files might actually benefit from the approach of using differences and incremental patches, rather than all or nothing file-by-file replacement, I would suggest you first experiment with a specialized utility such as jojodiff to verify -- and if that is indeed the case (perhaps only for some files, while others might as well be replaced entirely), you might package the patch part of it with your updater (and run it as a subprocess from Python, etc).
As for maintaining deltas on your server, a mixed approach should work: i.e., you'd try to keep all the (quadratic numbers of) updates (from A → A+1, A → A+2, A+1 → A+2, etc) but "cut off" each branch (in favor of a total-replacement approach) when the advantage of doing things incrementally becomes too small to warrant the cost of taking up storage on your server and processing time at the client (of course, there's nothing but heuristics, aka try/experiment and see, for determining the threshold for "too small";-).
A:
Your update manager can know which version the current app is, and which version is the most recent one and apply only the relevant patches.
Suppose the user runs 0.38, and currently there is 0.42 available. The update for 0.42 contains patches for 0.39, 0.40, 0.41 and 0.42 (and probably farther down the history). The update manager downloads the 0.42 update, knows it's at 0.38 and applies all the relevant patches. If it currently runs 0.41, it only applies the latest patch, and so on.
| Updating my program, using a diff-based patch approach | Currently my program updates itself by downloading the latest .tar.gz file containing the source code, and extracting it over the current directory where the program lives. There are 2 "modes" of update - one for users running the Python source, and one if the user is running the program as a Windows exe.
Over time my program's filesize is becoming larger with each release, due to new images, libraries, documentation and code. However, sometimes only code changes occur from one release to another, so the user ends up re-downloading all the images, documentation etc over and over, when only there are only small code changes.
I was thinking that a more efficient approach would be to use a patch/diff based system where the program incrementally updates itself from one version to another by only downloading small change sets.
However, how should I do this? If the user is running version 0.38, and there is a 0.42 available, do they download 0.38->39; 0.39->40; 0.40->41, 0.41->42? How would I handle differences in binary files? (images, in my case).
I'd also have to maintain some repository containing all the patches, which isn't too bad. I'd just generate the diffs with each new release. But I guess it would be harder to do this to executables than to pure python code?
Any input is appreciated. Many thanks.
| [
"I suggest that rather than reinventing your own update management system, you take a look at open source options, such as google updater (which was open sourced over a year ago as Omaha) -- I imagine the Windows focus is OK since you do specifically refer to Windows, but if you also need Mac support a similar func... | [
3,
1
] | [] | [] | [
"diff",
"patch",
"python"
] | stackoverflow_0003219772_diff_patch_python.txt |
Q:
Converting videos for iPhone - ffmpeg
I'm using the following command in order to convert .avi video files
ffmpeg -i -f mpegts -acodec libmp3lame -ar 48000 -ab 64k -s 320×240 -vcodec libx264 -b 96k -flags +loop -cmp +chroma -partitions +parti4×4+partp8×8+partb8×8 -subq 5 -trellis 1 -refs 1 -coder 0 -me_range 16 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -bt 200k -maxrate 96k -bufsize 96k -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -level 30 -aspect 320:240 -g 30 -async 2
The video converts, but when I try and open it from the iPhone's Safari I am greeted with
This movie format is not supported
Any ideas? Help would be awesome!
Also if there are any python scripts/apps that are available, it would be very useful.
A:
As far as I know, you need to use AAC for the audio format and MP4 for the container.
VBITRATE=700
ABITRATE=96
ffmpeg -i inputfile.avi -vcodec mpeg4 -b $VBITRATE -qmin 3 -qmax 5 \
-bufsize 4096 -g 300 -acodec aac -ab $ABITRATE \
-f mp4 -size 320x240 -r 25 outputfile.mp4
I think it would support both libx264 and mpeg4 for the video codec.
| Converting videos for iPhone - ffmpeg | I'm using the following command in order to convert .avi video files
ffmpeg -i -f mpegts -acodec libmp3lame -ar 48000 -ab 64k -s 320×240 -vcodec libx264 -b 96k -flags +loop -cmp +chroma -partitions +parti4×4+partp8×8+partb8×8 -subq 5 -trellis 1 -refs 1 -coder 0 -me_range 16 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -bt 200k -maxrate 96k -bufsize 96k -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -level 30 -aspect 320:240 -g 30 -async 2
The video converts, but when I try and open it from the iPhone's Safari I am greeted with
This movie format is not supported
Any ideas? Help would be awesome!
Also if there are any python scripts/apps that are available, it would be very useful.
| [
"As far as I know, you need to use AAC for the audio format and MP4 for the container.\nVBITRATE=700\nABITRATE=96\nffmpeg -i inputfile.avi -vcodec mpeg4 -b $VBITRATE -qmin 3 -qmax 5 \\\n -bufsize 4096 -g 300 -acodec aac -ab $ABITRATE \\\n -f mp4 -size 320x240 -r 25 outputfile.mp4\n\nI think it would support... | [
2
] | [] | [] | [
"ffmpeg",
"iphone",
"python",
"ubuntu",
"video_encoding"
] | stackoverflow_0003219757_ffmpeg_iphone_python_ubuntu_video_encoding.txt |
Q:
Check if python int is too large to convert to float
Is there any way to check if a long integer is too large to convert to a float in python?
A:
>>> import sys
>>> sys.float_info.max
1.7976931348623157e+308
Actually, if you try to convert an integer too big to a float, an exception will be raised.
>>> float(2 * 10**308)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C double
| Check if python int is too large to convert to float | Is there any way to check if a long integer is too large to convert to a float in python?
| [
">>> import sys\n>>> sys.float_info.max\n1.7976931348623157e+308\n\nActually, if you try to convert an integer too big to a float, an exception will be raised.\n>>> float(2 * 10**308)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nOverflowError: Python int too large to convert to C do... | [
13
] | [] | [] | [
"floating_point",
"integer",
"python"
] | stackoverflow_0003220074_floating_point_integer_python.txt |
Q:
Attaching additional information to form fields
I'm trying to pass on additional information to fields of a Django form to be displayed in a template. I tried to override the constructor and add another property to the field like this:
self.fields['field_name'].foo = 'bar'
but in the template this:
{{ form.field_name.foo }}
didn't print anything. Does anyone know how to add additional information to a field without rewriting/inheriting the forms field classes?
A:
According to django.forms.forms, the __getitem__() method of a Form creates something called a BoundField out of the Field before returning it, thus stripping it of whatever changes you made. If you really want to insert more functionality into that, override that method to do stuff to the bound field before returning it:
class MyForm(forms.Form):
def __getitem__(self, name):
boundfield = super(forms.Form,self).__getitem__(name)
boundfield.foo = "bar"
return boundfield
Then, "bar" will appear for all fields in that form. You can also make a function and call that instead, to make it more than just a hard-coded string.
While it's more standard to add more fields, or to add properties to the form itself, if you have a whole new class of info that every field needs to contain, this may do it for you.
Another way to get the same thing is to edit an attribute of the field, then access it via the BoundField's "field" attribute:
class MyForm(forms.Form):
def __init__(self, *args, **kwargs)
super(forms.Form, self).__init__(*args, **kwargs)
self.fields['field_name'].foo = "bar"
Then, to access foo in a template:
{{ form.field_name.field.foo }}
| Attaching additional information to form fields | I'm trying to pass on additional information to fields of a Django form to be displayed in a template. I tried to override the constructor and add another property to the field like this:
self.fields['field_name'].foo = 'bar'
but in the template this:
{{ form.field_name.foo }}
didn't print anything. Does anyone know how to add additional information to a field without rewriting/inheriting the forms field classes?
| [
"According to django.forms.forms, the __getitem__() method of a Form creates something called a BoundField out of the Field before returning it, thus stripping it of whatever changes you made. If you really want to insert more functionality into that, override that method to do stuff to the bound field before retur... | [
7
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003219576_django_django_forms_python.txt |
Q:
Using ExecuteBatch from Python on Google Calendars API
I'm trying to figure out how to add a series of events to a non-default calendar (and remove some) as a batch, but there's no hint of how to do it in Google's frankly awful documentation.
Has anyone cracked this nut or does anyone know where there is actually useful documentation on using the Google Calendar API?
A:
Figured it out in the end. The key is using the right batch URL in ExecuteBatch:
uri = self.calendar.GetAlternateLink().href
batch_uri = uri + u'/batch'
calendar_service.ExecuteBatch(request_feed, batch_uri)
| Using ExecuteBatch from Python on Google Calendars API | I'm trying to figure out how to add a series of events to a non-default calendar (and remove some) as a batch, but there's no hint of how to do it in Google's frankly awful documentation.
Has anyone cracked this nut or does anyone know where there is actually useful documentation on using the Google Calendar API?
| [
"Figured it out in the end. The key is using the right batch URL in ExecuteBatch:\nuri = self.calendar.GetAlternateLink().href\nbatch_uri = uri + u'/batch'\ncalendar_service.ExecuteBatch(request_feed, batch_uri)\n\n"
] | [
0
] | [] | [] | [
"batch_file",
"google_calendar_api",
"python"
] | stackoverflow_0003207883_batch_file_google_calendar_api_python.txt |
Q:
Drawing a polygon in pygame
i am jaison i like to build an application for land survey process. for that i need to plot points in a canvas for a given gsi file. for example
the points be
a. .b
c. .d .e
these are the 5 points and i need to develop a tool to connect these points by line. while closing a boundry by like connecting points acdba. give it a parcel_id and other details like land owner, tax payment etc. save these details for feature query.
in real time the points will be more than 100000. and i need the canvas should have pan and zoom property.
friends i like to do this project in python using pygame. is it possible to do.
i am a newbie to python.
please need help.
A:
Pygame is absolutely a good tool for this.
Look into using a pygame.surface object, and the pygame.draw module.
http://www.pygame.org/docs/ref/
If you need anything more complicated than dots, pygame.sprite is a relatively well developed module as well.
A:
http://www.pygame.org/docs/ref/draw.html#pygame.draw.polygon
This is the function for drawing polygons in pygame. You can draw straight to screen or to a separate surface. I am not sure how fast it is with lots of points, you might want to split up what your drawing into smaller segments and just display what you need.
If you do need to show the whole polygon I would look into some way of compressing the amount of points to only get the general shape
| Drawing a polygon in pygame | i am jaison i like to build an application for land survey process. for that i need to plot points in a canvas for a given gsi file. for example
the points be
a. .b
c. .d .e
these are the 5 points and i need to develop a tool to connect these points by line. while closing a boundry by like connecting points acdba. give it a parcel_id and other details like land owner, tax payment etc. save these details for feature query.
in real time the points will be more than 100000. and i need the canvas should have pan and zoom property.
friends i like to do this project in python using pygame. is it possible to do.
i am a newbie to python.
please need help.
| [
"Pygame is absolutely a good tool for this.\nLook into using a pygame.surface object, and the pygame.draw module.\nhttp://www.pygame.org/docs/ref/\nIf you need anything more complicated than dots, pygame.sprite is a relatively well developed module as well.\n",
"http://www.pygame.org/docs/ref/draw.html#pygame.dra... | [
0,
0
] | [] | [] | [
"gis",
"pygame",
"python"
] | stackoverflow_0003115467_gis_pygame_python.txt |
Q:
How to optimize a recursive algorithm to not repeat itself?
After finding the difflib.SequenceMatcher class in Python's standard library to be unsuitable for my needs, a generic "diff"-ing module was written to solve a problem space. After having several months to think more about what it is doing, the recursive algorithm appears to be searching more than in needs to by re-searching the same areas in a sequence that a separate "search thread" may have also examined.
The purpose of the diff module is to compute the difference and similarities between a pair of sequences (list, tuple, string, bytes, bytearray, et cetera). The initial version was much slower than the code's current form, having seen a speed increase by a factor of ten. Does anyone have a suggestion for implementing a method of pruning search spaces in recursive algorithms to improve performance?
A:
The technique you are looking for is called memoization.
A:
If you have any expensive method that you are likely to call multiple times with the same parameters then you can just cache the result of the method, using the parameters as a key.
| How to optimize a recursive algorithm to not repeat itself? | After finding the difflib.SequenceMatcher class in Python's standard library to be unsuitable for my needs, a generic "diff"-ing module was written to solve a problem space. After having several months to think more about what it is doing, the recursive algorithm appears to be searching more than in needs to by re-searching the same areas in a sequence that a separate "search thread" may have also examined.
The purpose of the diff module is to compute the difference and similarities between a pair of sequences (list, tuple, string, bytes, bytearray, et cetera). The initial version was much slower than the code's current form, having seen a speed increase by a factor of ten. Does anyone have a suggestion for implementing a method of pruning search spaces in recursive algorithms to improve performance?
| [
"The technique you are looking for is called memoization.\n",
"If you have any expensive method that you are likely to call multiple times with the same parameters then you can just cache the result of the method, using the parameters as a key. \n"
] | [
6,
0
] | [] | [] | [
"diff",
"optimization",
"python",
"recursion"
] | stackoverflow_0003220433_diff_optimization_python_recursion.txt |
Q:
Using Python to scrape DataSet and Query data from RDL
I set out today with the intent to parse an SSRS RDL file (XML) using Python in order to gather the DataSet and Query data. A recent project has me back tracking on a variety of reports and data sources with the intention of consolidating and cleaning up what we have published.
I was able to use this script to create a CSV file with the following columns:
system path|report file name|command type|command text|
It's not very elegant, but it works.
What I'm hoping to be able to do with this post is solicit for any of you experts out there who have either tried this already or are experienced in XML parsing with Python to take a shot at cleaning it up and provided the ability to:
Include Headers, which would be XML tags
Include DataSet name in the column
Deliver results into single file
Here is the full code in my "rdlparser.py" file:
import sys, os
from xml.dom import minidom
xmldoc = minidom.parse(sys.argv[1])
content = ""
TargetFile = sys.argv[1].split(".", 1)[0] + ".csv"
numberOfQueryNodes = 0
queryNodes = xmldoc.getElementsByTagName('Query')
numberOfQueryNodes = queryNodes.length -1
while (numberOfQueryNodes > -1):
content = content + os.path.abspath(sys.argv[1])+ '|'+ sys.argv[1].split(".", 1)[0]+ '|'
outputNode = queryNodes.__getitem__(numberOfQueryNodes)
children = [child for child in outputNode.childNodes if child.nodeType==1]
numberOfQueryNodes = numberOfQueryNodes - 1
for node in children:
if node.firstChild.nodeValue != '\n ':
if node.firstChild.nodeValue != 'true':
content = content + node.firstChild.nodeValue + '|'
content = content + '\n'
fp = open(TargetFile, 'wb')
fp.write(content)
fp.close()
A:
I know you asked for Python; but I figured Powershell's built in xml handling capabilities would make this fairly simple. While I'm sure it is not guru level, I think it came out pretty nicely (the lines starting with # are comments):
# The directory to search
$searchpath = "C:\"
# List all rdl files from the given search path recusrivley searching sub folders, store results into a variable
$files = gci $searchpath -recurse -filter "*.rdl" | SELECT FullName, DirectoryName, Name
# for each of the found files pass the folder and file name and the xml content
$files | % {$Directory = $_.DirectoryName; $Name = $_.Name; [xml](gc $_.FullName)}
# in the xml content navigate to the the DataSets Element
| % {$_.Report.DataSets}
# for each query retrieve the Report directory , File Name, DataSource Name, Command Type, Command Text output thwese to a csv file
| % {$_.DataSet.Query} | SELECT @{N="Path";E={$Directory}}, @{N="File";E={$Name}}, DataSourceName, CommandType, CommandText | Export-Csv Test.csv -notype
| Using Python to scrape DataSet and Query data from RDL | I set out today with the intent to parse an SSRS RDL file (XML) using Python in order to gather the DataSet and Query data. A recent project has me back tracking on a variety of reports and data sources with the intention of consolidating and cleaning up what we have published.
I was able to use this script to create a CSV file with the following columns:
system path|report file name|command type|command text|
It's not very elegant, but it works.
What I'm hoping to be able to do with this post is solicit for any of you experts out there who have either tried this already or are experienced in XML parsing with Python to take a shot at cleaning it up and provided the ability to:
Include Headers, which would be XML tags
Include DataSet name in the column
Deliver results into single file
Here is the full code in my "rdlparser.py" file:
import sys, os
from xml.dom import minidom
xmldoc = minidom.parse(sys.argv[1])
content = ""
TargetFile = sys.argv[1].split(".", 1)[0] + ".csv"
numberOfQueryNodes = 0
queryNodes = xmldoc.getElementsByTagName('Query')
numberOfQueryNodes = queryNodes.length -1
while (numberOfQueryNodes > -1):
content = content + os.path.abspath(sys.argv[1])+ '|'+ sys.argv[1].split(".", 1)[0]+ '|'
outputNode = queryNodes.__getitem__(numberOfQueryNodes)
children = [child for child in outputNode.childNodes if child.nodeType==1]
numberOfQueryNodes = numberOfQueryNodes - 1
for node in children:
if node.firstChild.nodeValue != '\n ':
if node.firstChild.nodeValue != 'true':
content = content + node.firstChild.nodeValue + '|'
content = content + '\n'
fp = open(TargetFile, 'wb')
fp.write(content)
fp.close()
| [
"I know you asked for Python; but I figured Powershell's built in xml handling capabilities would make this fairly simple. While I'm sure it is not guru level, I think it came out pretty nicely (the lines starting with # are comments):\n# The directory to search \n$searchpath = \"C:\\\"\n\n# List all rdl files f... | [
0
] | [] | [] | [
"minidom",
"python",
"rdl",
"reporting_services",
"xml"
] | stackoverflow_0003206993_minidom_python_rdl_reporting_services_xml.txt |
Q:
Django iterating - calculating a sum
I'm trying to iterate through some values, and calculate a rank. I have a calculate_rank function where I calculate a sum of values. The problem is at the second function. I want that a user's rank to be the sum of all the user that in a follow relation with him.
I am doing an iteration in the second function here where I try to add the rank of all the users that are in a follow relation with the user sent as a parameter.
My problem is that the returned value is zero (0).
I am sure I am mistaking in the second function, but I don't see: where?
def calculate_rank(user):
rank = calculate_questions_vote(user) + calculate_votes(user) + calculate_replies(user)
return rank
def calculate_followers_rank(user):
follower = Relations.objects.filter(follow = user)
follower_rank= 0
for a in follower:
follower_rank += calculate_rank(follower)
return follower_rank
A:
You're passing follower - ie the full list of followers - into the calculate_rank function. I think you either want a (the current follower in the iteration) or user (the original user being followed) here.
These things would be easier to spot if you gave your variables more accurate names. If you'd called the list of followers followers, in the plural, then you'd see it wouldn't make sense to pass it into calculate_rank.
| Django iterating - calculating a sum | I'm trying to iterate through some values, and calculate a rank. I have a calculate_rank function where I calculate a sum of values. The problem is at the second function. I want that a user's rank to be the sum of all the user that in a follow relation with him.
I am doing an iteration in the second function here where I try to add the rank of all the users that are in a follow relation with the user sent as a parameter.
My problem is that the returned value is zero (0).
I am sure I am mistaking in the second function, but I don't see: where?
def calculate_rank(user):
rank = calculate_questions_vote(user) + calculate_votes(user) + calculate_replies(user)
return rank
def calculate_followers_rank(user):
follower = Relations.objects.filter(follow = user)
follower_rank= 0
for a in follower:
follower_rank += calculate_rank(follower)
return follower_rank
| [
"You're passing follower - ie the full list of followers - into the calculate_rank function. I think you either want a (the current follower in the iteration) or user (the original user being followed) here.\nThese things would be easier to spot if you gave your variables more accurate names. If you'd called the li... | [
4
] | [] | [] | [
"django",
"function",
"loops",
"python"
] | stackoverflow_0003221025_django_function_loops_python.txt |
Q:
python form handle
How can I handle html form input (array) like the one below in Python:
<input type='hidden' name='a[]' value='some_value'>
The following doesn't work:
a_value = form["a"].value
Please help. Many thanks in advance.
A:
take a look at http://formencode.org/Validator.html#http-html-form-input
input name / value
names-1.fname John
names-1.lname Doe
names-2.fname Jane
names-2.lname Brown
will be parsed into
{'names': [
{'fname': "John", 'lname': "Doe"},
{'fname': "Jane", 'lname': 'Brown'},
UPDATE:
In your case <input type="hidden" name="item.a" value="5" /> will be parsed into item['a'] = 5
| python form handle | How can I handle html form input (array) like the one below in Python:
<input type='hidden' name='a[]' value='some_value'>
The following doesn't work:
a_value = form["a"].value
Please help. Many thanks in advance.
| [
"take a look at http://formencode.org/Validator.html#http-html-form-input\ninput name / value\nnames-1.fname John\nnames-1.lname Doe\nnames-2.fname Jane\nnames-2.lname Brown\n\nwill be parsed into\n{'names': [\n {'fname': \"John\", 'lname': \"Doe\"},\n {'fname': \"Jane\", 'lname': 'Brown'},\n\nU... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003221211_python.txt |
Q:
Issue with installing mod_wsgi
Trying, to figure out why make fails while installing mod_wsgi and getting following errors.
Can anyone help me out with to figure out what is wrong ?
mod_wsgi.c:13910: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13910: warning: data definition has no type or storage class
mod_wsgi.c:13915: error: redefinition of 'status'
mod_wsgi.c:8742: error: previous definition of 'status' was here
mod_wsgi.c:13915: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:13915: warning: data definition has no type or storage class
mod_wsgi.c:13919: error: syntax error before "if"
mod_wsgi.c:13921: error: conflicting types for 'object'
mod_wsgi.c:8778: error: previous definition of 'object' was here
mod_wsgi.c:13921: error: conflicting types for 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:13921: warning: data definition has no type or storage class
mod_wsgi.c:13923: error: redefinition of 'module_dict'
mod_wsgi.c:8509: error: previous definition of 'module_dict' was here
mod_wsgi.c:13923: error: redefinition of 'module_dict'
mod_wsgi.c:8509: error: previous definition of 'module_dict' was here
mod_wsgi.c:13923: error: syntax error before "module"
mod_wsgi.c:13924: error: conflicting types for 'object'
mod_wsgi.c:13921: error: previous definition of 'object' was here
mod_wsgi.c:13924: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:13924: error: initializer element is not constant
mod_wsgi.c:13924: warning: data definition has no type or storage class
mod_wsgi.c:13926: error: syntax error before "if"
mod_wsgi.c:13928: error: conflicting types for 'args'
mod_wsgi.c:8688: error: previous definition of 'args' was here
mod_wsgi.c:13928: error: redefinition of 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:13928: warning: data definition has no type or storage class
mod_wsgi.c:13929: error: syntax error before '*' token
mod_wsgi.c:13929: warning: data definition has no type or storage class
mod_wsgi.c:13930: error: syntax error before '*' token
mod_wsgi.c:13930: error: conflicting types for 'method'
mod_wsgi.c:8769: error: previous definition of 'method' was here
mod_wsgi.c:13930: error: redefinition of 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:13930: warning: data definition has no type or storage class
mod_wsgi.c:13932: error: syntax error before '*' token
mod_wsgi.c:13932: error: conflicting types for 'adapter'
mod_wsgi.c:8511: error: previous definition of 'adapter' was here
mod_wsgi.c:13932: error: redefinition of 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:13932: warning: data definition has no type or storage class
mod_wsgi.c:13934: error: conflicting types for 'adapter'
mod_wsgi.c:13932: error: previous definition of 'adapter' was here
mod_wsgi.c:13934: error: conflicting types for 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:13934: warning: initialization makes integer from pointer without a c ast
mod_wsgi.c:13934: error: initializer element is not constant
mod_wsgi.c:13934: warning: data definition has no type or storage class
mod_wsgi.c:13936: error: syntax error before "if"
mod_wsgi.c:13939: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13939: warning: data definition has no type or storage class
mod_wsgi.c:13940: error: conflicting types for 'args'
mod_wsgi.c:13928: error: previous definition of 'args' was here
mod_wsgi.c:13940: error: conflicting types for 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:13940: error: initializer element is not constant
mod_wsgi.c:13940: warning: data definition has no type or storage class
mod_wsgi.c:13941: error: conflicting types for 'sequence'
mod_wsgi.c:13929: error: previous definition of 'sequence' was here
mod_wsgi.c:13941: error: initializer element is not constant
mod_wsgi.c:13941: warning: data definition has no type or storage class
mod_wsgi.c:13942: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13942: warning: data definition has no type or storage class
mod_wsgi.c:13943: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13943: warning: data definition has no type or storage class
mod_wsgi.c:13944: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13944: warning: data definition has no type or storage class
mod_wsgi.c:13946: error: syntax error before "if"
mod_wsgi.c:13949: error: initializer element is not constant
mod_wsgi.c:13949: warning: data definition has no type or storage class
mod_wsgi.c:13951: error: syntax error before "if"
mod_wsgi.c:13955: error: redefinition of 'status'
mod_wsgi.c:13915: error: previous definition of 'status' was here
mod_wsgi.c:13955: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:13955: warning: data definition has no type or storage class
mod_wsgi.c:13957: error: syntax error before "while"
mod_wsgi.c:13998: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13998: warning: data definition has no type or storage class
mod_wsgi.c:14000: error: redefinition of 'status'
mod_wsgi.c:13955: error: previous definition of 'status' was here
mod_wsgi.c:14000: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:14000: warning: data definition has no type or storage class
mod_wsgi.c:14002: error: syntax error before "break"
mod_wsgi.c:14005: error: conflicting types for 'name'
mod_wsgi.c:13953: error: previous declaration of 'name' was here
mod_wsgi.c:14005: error: initializer element is not constant
mod_wsgi.c:14005: warning: data definition has no type or storage class
mod_wsgi.c:14007: error: syntax error before '(' token
mod_wsgi.c:14010: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14010: warning: data definition has no type or storage class
mod_wsgi.c:14011: error: syntax error before '}' token
mod_wsgi.c:14013: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14013: warning: data definition has no type or storage class
mod_wsgi.c:14014: error: syntax error before '}' token
mod_wsgi.c:14040: error: conflicting types for 'method'
mod_wsgi.c:13930: error: previous definition of 'method' was here
mod_wsgi.c:14040: error: conflicting types for 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:14040: error: invalid type argument of `->'
mod_wsgi.c:14040: error: initializer element is not constant
mod_wsgi.c:14040: warning: data definition has no type or storage class
mod_wsgi.c:14042: error: syntax error before "if"
mod_wsgi.c:14049: error: redefinition of 'object'
mod_wsgi.c:13924: error: previous definition of 'object' was here
mod_wsgi.c:14049: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14049: error: initializer element is not constant
mod_wsgi.c:14049: warning: data definition has no type or storage class
mod_wsgi.c:14050: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14050: warning: data definition has no type or storage class
mod_wsgi.c:14051: error: syntax error before '}' token
mod_wsgi.c:14053: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14053: warning: data definition has no type or storage class
mod_wsgi.c:14054: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14054: warning: data definition has no type or storage class
mod_wsgi.c:14058: error: syntax error before '(' token
mod_wsgi.c:14080: warning: data definition has no type or storage class
mod_wsgi.c:14082: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14082: warning: data definition has no type or storage class
mod_wsgi.c:14084: error: syntax error before "if"
mod_wsgi.c: In function `wsgi_allow_access':
mod_wsgi.c:14093: error: invalid operands to binary *
mod_wsgi.c:14095: error: syntax error before "module"
mod_wsgi.c:14143: error: `Py_BEGIN_ALLOW_THREADS' undeclared (first use in this function)
mod_wsgi.c:14143: error: syntax error before "apr_thread_mutex_lock"
mod_wsgi.c:14147: error: `Py_END_ALLOW_THREADS' undeclared (first use in this fu nction)
mod_wsgi.c:14150: error: syntax error before "module"
mod_wsgi.c:14152: error: syntax error before "module"
mod_wsgi.c:14161: error: syntax error before "module"
mod_wsgi.c: At top level:
mod_wsgi.c:14178: error: syntax error before '}' token
mod_wsgi.c:14187: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14187: warning: data definition has no type or storage class
mod_wsgi.c:14192: error: redefinition of 'result'
mod_wsgi.c:8689: error: previous definition of 'result' was here
mod_wsgi.c:14192: error: redefinition of 'result'
mod_wsgi.c:2274: error: previous definition of 'result' was here
mod_wsgi.c:14192: warning: data definition has no type or storage class
mod_wsgi.c:14196: error: syntax error before "if"
mod_wsgi.c:14198: error: conflicting types for 'object'
mod_wsgi.c:14049: error: previous definition of 'object' was here
mod_wsgi.c:14198: error: conflicting types for 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14198: warning: data definition has no type or storage class
mod_wsgi.c:14200: error: redefinition of 'module_dict'
mod_wsgi.c:13923: error: previous definition of 'module_dict' was here
mod_wsgi.c:14200: error: redefinition of 'module_dict'
mod_wsgi.c:8509: error: previous definition of 'module_dict' was here
mod_wsgi.c:14200: error: syntax error before "module"
mod_wsgi.c:14201: error: conflicting types for 'object'
mod_wsgi.c:14198: error: previous definition of 'object' was here
mod_wsgi.c:14201: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14201: error: initializer element is not constant
mod_wsgi.c:14201: warning: data definition has no type or storage class
mod_wsgi.c:14203: error: syntax error before "if"
mod_wsgi.c:14205: error: conflicting types for 'args'
mod_wsgi.c:13940: error: previous definition of 'args' was here
mod_wsgi.c:14205: error: redefinition of 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:14205: warning: data definition has no type or storage class
mod_wsgi.c:14206: error: syntax error before '*' token
mod_wsgi.c:14206: warning: data definition has no type or storage class
mod_wsgi.c:14207: error: syntax error before '*' token
mod_wsgi.c:14207: error: conflicting types for 'method'
mod_wsgi.c:14040: error: previous definition of 'method' was here
mod_wsgi.c:14207: error: redefinition of 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:14207: warning: data definition has no type or storage class
mod_wsgi.c:14209: error: syntax error before '*' token
mod_wsgi.c:14209: error: conflicting types for 'adapter'
mod_wsgi.c:13934: error: previous definition of 'adapter' was here
mod_wsgi.c:14209: error: redefinition of 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:14209: warning: data definition has no type or storage class
mod_wsgi.c:14211: error: conflicting types for 'adapter'
mod_wsgi.c:14209: error: previous definition of 'adapter' was here
mod_wsgi.c:14211: error: conflicting types for 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:14211: warning: initialization makes integer from pointer without a c ast
mod_wsgi.c:14211: error: initializer element is not constant
mod_wsgi.c:14211: warning: data definition has no type or storage class
mod_wsgi.c:14213: error: syntax error before "if"
mod_wsgi.c:14216: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14216: warning: data definition has no type or storage class
mod_wsgi.c:14217: error: conflicting types for 'args'
mod_wsgi.c:14205: error: previous definition of 'args' was here
mod_wsgi.c:14217: error: conflicting types for 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:14217: error: `host' undeclared here (not in a function)
mod_wsgi.c:14217: error: initializer element is not constant
mod_wsgi.c:14217: warning: data definition has no type or storage class
mod_wsgi.c:14218: error: conflicting types for 'flag'
mod_wsgi.c:14206: error: previous definition of 'flag' was here
mod_wsgi.c:14218: error: initializer element is not constant
mod_wsgi.c:14218: warning: data definition has no type or storage class
mod_wsgi.c:14219: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14219: warning: data definition has no type or storage class
mod_wsgi.c:14220: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14220: warning: data definition has no type or storage class
mod_wsgi.c:14221: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14221: warning: data definition has no type or storage class
mod_wsgi.c:14223: error: syntax error before "if"
mod_wsgi.c:14256: error: conflicting types for 'method'
mod_wsgi.c:14207: error: previous definition of 'method' was here
mod_wsgi.c:14256: error: conflicting types for 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:14256: error: invalid type argument of `->'
mod_wsgi.c:14256: error: initializer element is not constant
mod_wsgi.c:14256: warning: data definition has no type or storage class
mod_wsgi.c:14258: error: syntax error before "if"
mod_wsgi.c:14265: error: redefinition of 'object'
mod_wsgi.c:14201: error: previous definition of 'object' was here
mod_wsgi.c:14265: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14265: error: initializer element is not constant
mod_wsgi.c:14265: warning: data definition has no type or storage class
mod_wsgi.c:14266: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14266: warning: data definition has no type or storage class
mod_wsgi.c:14267: error: syntax error before '}' token
mod_wsgi.c:14269: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14269: warning: data definition has no type or storage class
mod_wsgi.c:14270: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14270: warning: data definition has no type or storage class
mod_wsgi.c:14274: error: syntax error before '(' token
mod_wsgi.c:14296: warning: data definition has no type or storage class
mod_wsgi.c:14298: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14298: warning: data definition has no type or storage class
mod_wsgi.c:14300: error: syntax error before "return"
mod_wsgi.c: In function `wsgi_hook_check_user_id':
mod_wsgi.c:14345: error: invalid operands to binary *
mod_wsgi.c:14347: error: syntax error before "module"
mod_wsgi.c:14393: error: `Py_BEGIN_ALLOW_THREADS' undeclared (first use in this function)
mod_wsgi.c:14393: error: syntax error before "apr_thread_mutex_lock"
mod_wsgi.c:14397: error: `Py_END_ALLOW_THREADS' undeclared (first use in this fu nction)
mod_wsgi.c:14400: error: syntax error before "module"
mod_wsgi.c:14402: error: syntax error before "module"
mod_wsgi.c:14411: error: syntax error before "module"
mod_wsgi.c: At top level:
mod_wsgi.c:14428: error: syntax error before '}' token
mod_wsgi.c:14437: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14437: warning: data definition has no type or storage class
mod_wsgi.c:14442: error: redefinition of 'status'
mod_wsgi.c:14000: error: previous definition of 'status' was here
mod_wsgi.c:14442: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:14442: warning: data definition has no type or storage class
mod_wsgi.c:14446: error: syntax error before "if"
mod_wsgi.c:14448: error: conflicting types for 'object'
mod_wsgi.c:14265: error: previous definition of 'object' was here
mod_wsgi.c:14448: error: conflicting types for 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14448: warning: data definition has no type or storage class
mod_wsgi.c:14450: error: redefinition of 'module_dict'
mod_wsgi.c:14200: error: previous definition of 'module_dict' was here
mod_wsgi.c:14450: error: redefinition of 'module_dict'
mod_wsgi.c:8509: error: previous definition of 'module_dict' was here
mod_wsgi.c:14450: error: syntax error before "module"
mod_wsgi.c:14451: error: conflicting types for 'object'
mod_wsgi.c:14448: error: previous definition of 'object' was here
mod_wsgi.c:14451: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14451: error: initializer element is not constant
mod_wsgi.c:14451: warning: data definition has no type or storage class
mod_wsgi.c:14453: error: syntax error before "if"
mod_wsgi.c:14455: error: conflicting types for 'args'
mod_wsgi.c:14217: error: previous definition of 'args' was here
mod_wsgi.c:14455: error: redefinition of 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:14455: warning: data definition has no type or storage class
mod_wsgi.c:14456: error: syntax error before '*' token
mod_wsgi.c:14456: error: conflicting types for 'result'
mod_wsgi.c:14192: error: previous definition of 'result' was here
mod_wsgi.c:14456: error: conflicting types for 'result'
mod_wsgi.c:2274: error: previous definition of 'result' was here
mod_wsgi.c:14456: warning: data definition has no type or storage class
mod_wsgi.c:14457: error: syntax error before '*' token
mod_wsgi.c:14457: error: conflicting types for 'method'
mod_wsgi.c:14256: error: previous definition of 'method' was here
mod_wsgi.c:14457: error: redefinition of 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:14457: warning: data definition has no type or storage class
mod_wsgi.c:14459: error: syntax error before '*' token
mod_wsgi.c:14459: error: conflicting types for 'adapter'
mod_wsgi.c:14211: error: previous definition of 'adapter' was here
mod_wsgi.c:14459: error: redefinition of 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:14459: warning: data definition has no type or storage class
mod_wsgi.c:14461: error: conflicting types for 'adapter'
mod_wsgi.c:14459: error: previous definition of 'adapter' was here
mod_wsgi.c:14461: error: conflicting types for 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:14461: warning: initialization makes integer from pointer without a c ast
mod_wsgi.c:14461: error: initializer element is not constant
mod_wsgi.c:14461: warning: data definition has no type or storage class
mod_wsgi.c:14463: error: syntax error before "if"
mod_wsgi.c:14466: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14466: warning: data definition has no type or storage class
mod_wsgi.c:14467: error: conflicting types for 'args'
mod_wsgi.c:14455: error: previous definition of 'args' was here
mod_wsgi.c:14467: error: conflicting types for 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:14467: error: `password' undeclared here (not in a function)
mod_wsgi.c:14467: error: initializer element is not constant
mod_wsgi.c:14467: warning: data definition has no type or storage class
mod_wsgi.c:14468: error: conflicting types for 'result'
mod_wsgi.c:14456: error: previous definition of 'result' was here
mod_wsgi.c:14468: error: redefinition of 'result'
mod_wsgi.c:2274: error: previous definition of 'result' was here
mod_wsgi.c:14468: error: initializer element is not constant
mod_wsgi.c:14468: warning: data definition has no type or storage class
mod_wsgi.c:14469: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14469: warning: data definition has no type or storage class
mod_wsgi.c:14470: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14470: warning: data definition has no type or storage class
mod_wsgi.c:14471: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14471: warning: data definition has no type or storage class
mod_wsgi.c:14473: error: syntax error before "if"
mod_wsgi.c:14477: error: redefinition of 'status'
mod_wsgi.c:14442: error: previous definition of 'status' was here
mod_wsgi.c:14477: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:14477: warning: data definition has no type or storage class
mod_wsgi.c:14479: error: syntax error before string constant
mod_wsgi.c:14483: error: conflicting types for 'ap_log_rerror'
/usr/include/httpd/http_log.h:202: error: previous declaration of 'ap_log_rerror ' was here
mod_wsgi.c:14483: error: conflicting types for 'ap_log_rerror'
/usr/include/httpd/http_log.h:202: error: previous declaration of 'ap_log_rerror ' was here
mod_wsgi.c:14483: error: conflicting types for 'r'
mod_wsgi.c:2824: error: previous declaration of 'r' was here
mod_wsgi.c:14483: error: syntax error before '->' token
mod_wsgi.c:14493: error: redefinition of 'status'
mod_wsgi.c:14477: error: previous definition of 'status' was here
mod_wsgi.c:14493: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:14493: warning: data definition has no type or storage class
mod_wsgi.c:14495: error: syntax error before string constant
mod_wsgi.c:14499: error: syntax error before '->' token
mod_wsgi.c:14508: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14508: warning: data definition has no type or storage class
mod_wsgi.c:14509: error: syntax error before '}' token
mod_wsgi.c:14523: error: conflicting types for 'method'
mod_wsgi.c:14457: error: previous definition of 'method' was here
mod_wsgi.c:14523: error: conflicting types for 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:14523: error: invalid type argument of `->'
mod_wsgi.c:14523: error: initializer element is not constant
mod_wsgi.c:14523: warning: data definition has no type or storage class
mod_wsgi.c:14525: error: syntax error before "if"
mod_wsgi.c:14532: error: redefinition of 'object'
mod_wsgi.c:14451: error: previous definition of 'object' was here
mod_wsgi.c:14532: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14532: error: initializer element is not constant
mod_wsgi.c:14532: warning: data definition has no type or storage class
mod_wsgi.c:14533: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14533: warning: data definition has no type or storage class
mod_wsgi.c:14534: error: syntax error before '}' token
mod_wsgi.c:14536: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14536: warning: data definition has no type or storage class
mod_wsgi.c:14537: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14537: warning: data definition has no type or storage class
mod_wsgi.c:14541: error: syntax error before '(' token
mod_wsgi.c:14563: warning: data definition has no type or storage class
mod_wsgi.c:14565: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14565: warning: data definition has no type or storage class
mod_wsgi.c:14567: error: syntax error before "return"
apxs:Error: Command failed with rc=65536
.
make: *** [mod_wsgi.la] Error 1
A:
You likely haven't go either python-dev or httpd-dev package installed and so compilation cant find their header files. Read requirements for what needs to be installed in the README of the mod_wsgi source code.
| Issue with installing mod_wsgi | Trying, to figure out why make fails while installing mod_wsgi and getting following errors.
Can anyone help me out with to figure out what is wrong ?
mod_wsgi.c:13910: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13910: warning: data definition has no type or storage class
mod_wsgi.c:13915: error: redefinition of 'status'
mod_wsgi.c:8742: error: previous definition of 'status' was here
mod_wsgi.c:13915: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:13915: warning: data definition has no type or storage class
mod_wsgi.c:13919: error: syntax error before "if"
mod_wsgi.c:13921: error: conflicting types for 'object'
mod_wsgi.c:8778: error: previous definition of 'object' was here
mod_wsgi.c:13921: error: conflicting types for 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:13921: warning: data definition has no type or storage class
mod_wsgi.c:13923: error: redefinition of 'module_dict'
mod_wsgi.c:8509: error: previous definition of 'module_dict' was here
mod_wsgi.c:13923: error: redefinition of 'module_dict'
mod_wsgi.c:8509: error: previous definition of 'module_dict' was here
mod_wsgi.c:13923: error: syntax error before "module"
mod_wsgi.c:13924: error: conflicting types for 'object'
mod_wsgi.c:13921: error: previous definition of 'object' was here
mod_wsgi.c:13924: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:13924: error: initializer element is not constant
mod_wsgi.c:13924: warning: data definition has no type or storage class
mod_wsgi.c:13926: error: syntax error before "if"
mod_wsgi.c:13928: error: conflicting types for 'args'
mod_wsgi.c:8688: error: previous definition of 'args' was here
mod_wsgi.c:13928: error: redefinition of 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:13928: warning: data definition has no type or storage class
mod_wsgi.c:13929: error: syntax error before '*' token
mod_wsgi.c:13929: warning: data definition has no type or storage class
mod_wsgi.c:13930: error: syntax error before '*' token
mod_wsgi.c:13930: error: conflicting types for 'method'
mod_wsgi.c:8769: error: previous definition of 'method' was here
mod_wsgi.c:13930: error: redefinition of 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:13930: warning: data definition has no type or storage class
mod_wsgi.c:13932: error: syntax error before '*' token
mod_wsgi.c:13932: error: conflicting types for 'adapter'
mod_wsgi.c:8511: error: previous definition of 'adapter' was here
mod_wsgi.c:13932: error: redefinition of 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:13932: warning: data definition has no type or storage class
mod_wsgi.c:13934: error: conflicting types for 'adapter'
mod_wsgi.c:13932: error: previous definition of 'adapter' was here
mod_wsgi.c:13934: error: conflicting types for 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:13934: warning: initialization makes integer from pointer without a c ast
mod_wsgi.c:13934: error: initializer element is not constant
mod_wsgi.c:13934: warning: data definition has no type or storage class
mod_wsgi.c:13936: error: syntax error before "if"
mod_wsgi.c:13939: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13939: warning: data definition has no type or storage class
mod_wsgi.c:13940: error: conflicting types for 'args'
mod_wsgi.c:13928: error: previous definition of 'args' was here
mod_wsgi.c:13940: error: conflicting types for 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:13940: error: initializer element is not constant
mod_wsgi.c:13940: warning: data definition has no type or storage class
mod_wsgi.c:13941: error: conflicting types for 'sequence'
mod_wsgi.c:13929: error: previous definition of 'sequence' was here
mod_wsgi.c:13941: error: initializer element is not constant
mod_wsgi.c:13941: warning: data definition has no type or storage class
mod_wsgi.c:13942: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13942: warning: data definition has no type or storage class
mod_wsgi.c:13943: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13943: warning: data definition has no type or storage class
mod_wsgi.c:13944: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13944: warning: data definition has no type or storage class
mod_wsgi.c:13946: error: syntax error before "if"
mod_wsgi.c:13949: error: initializer element is not constant
mod_wsgi.c:13949: warning: data definition has no type or storage class
mod_wsgi.c:13951: error: syntax error before "if"
mod_wsgi.c:13955: error: redefinition of 'status'
mod_wsgi.c:13915: error: previous definition of 'status' was here
mod_wsgi.c:13955: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:13955: warning: data definition has no type or storage class
mod_wsgi.c:13957: error: syntax error before "while"
mod_wsgi.c:13998: warning: parameter names (without types) in function declarati on
mod_wsgi.c:13998: warning: data definition has no type or storage class
mod_wsgi.c:14000: error: redefinition of 'status'
mod_wsgi.c:13955: error: previous definition of 'status' was here
mod_wsgi.c:14000: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:14000: warning: data definition has no type or storage class
mod_wsgi.c:14002: error: syntax error before "break"
mod_wsgi.c:14005: error: conflicting types for 'name'
mod_wsgi.c:13953: error: previous declaration of 'name' was here
mod_wsgi.c:14005: error: initializer element is not constant
mod_wsgi.c:14005: warning: data definition has no type or storage class
mod_wsgi.c:14007: error: syntax error before '(' token
mod_wsgi.c:14010: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14010: warning: data definition has no type or storage class
mod_wsgi.c:14011: error: syntax error before '}' token
mod_wsgi.c:14013: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14013: warning: data definition has no type or storage class
mod_wsgi.c:14014: error: syntax error before '}' token
mod_wsgi.c:14040: error: conflicting types for 'method'
mod_wsgi.c:13930: error: previous definition of 'method' was here
mod_wsgi.c:14040: error: conflicting types for 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:14040: error: invalid type argument of `->'
mod_wsgi.c:14040: error: initializer element is not constant
mod_wsgi.c:14040: warning: data definition has no type or storage class
mod_wsgi.c:14042: error: syntax error before "if"
mod_wsgi.c:14049: error: redefinition of 'object'
mod_wsgi.c:13924: error: previous definition of 'object' was here
mod_wsgi.c:14049: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14049: error: initializer element is not constant
mod_wsgi.c:14049: warning: data definition has no type or storage class
mod_wsgi.c:14050: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14050: warning: data definition has no type or storage class
mod_wsgi.c:14051: error: syntax error before '}' token
mod_wsgi.c:14053: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14053: warning: data definition has no type or storage class
mod_wsgi.c:14054: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14054: warning: data definition has no type or storage class
mod_wsgi.c:14058: error: syntax error before '(' token
mod_wsgi.c:14080: warning: data definition has no type or storage class
mod_wsgi.c:14082: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14082: warning: data definition has no type or storage class
mod_wsgi.c:14084: error: syntax error before "if"
mod_wsgi.c: In function `wsgi_allow_access':
mod_wsgi.c:14093: error: invalid operands to binary *
mod_wsgi.c:14095: error: syntax error before "module"
mod_wsgi.c:14143: error: `Py_BEGIN_ALLOW_THREADS' undeclared (first use in this function)
mod_wsgi.c:14143: error: syntax error before "apr_thread_mutex_lock"
mod_wsgi.c:14147: error: `Py_END_ALLOW_THREADS' undeclared (first use in this fu nction)
mod_wsgi.c:14150: error: syntax error before "module"
mod_wsgi.c:14152: error: syntax error before "module"
mod_wsgi.c:14161: error: syntax error before "module"
mod_wsgi.c: At top level:
mod_wsgi.c:14178: error: syntax error before '}' token
mod_wsgi.c:14187: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14187: warning: data definition has no type or storage class
mod_wsgi.c:14192: error: redefinition of 'result'
mod_wsgi.c:8689: error: previous definition of 'result' was here
mod_wsgi.c:14192: error: redefinition of 'result'
mod_wsgi.c:2274: error: previous definition of 'result' was here
mod_wsgi.c:14192: warning: data definition has no type or storage class
mod_wsgi.c:14196: error: syntax error before "if"
mod_wsgi.c:14198: error: conflicting types for 'object'
mod_wsgi.c:14049: error: previous definition of 'object' was here
mod_wsgi.c:14198: error: conflicting types for 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14198: warning: data definition has no type or storage class
mod_wsgi.c:14200: error: redefinition of 'module_dict'
mod_wsgi.c:13923: error: previous definition of 'module_dict' was here
mod_wsgi.c:14200: error: redefinition of 'module_dict'
mod_wsgi.c:8509: error: previous definition of 'module_dict' was here
mod_wsgi.c:14200: error: syntax error before "module"
mod_wsgi.c:14201: error: conflicting types for 'object'
mod_wsgi.c:14198: error: previous definition of 'object' was here
mod_wsgi.c:14201: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14201: error: initializer element is not constant
mod_wsgi.c:14201: warning: data definition has no type or storage class
mod_wsgi.c:14203: error: syntax error before "if"
mod_wsgi.c:14205: error: conflicting types for 'args'
mod_wsgi.c:13940: error: previous definition of 'args' was here
mod_wsgi.c:14205: error: redefinition of 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:14205: warning: data definition has no type or storage class
mod_wsgi.c:14206: error: syntax error before '*' token
mod_wsgi.c:14206: warning: data definition has no type or storage class
mod_wsgi.c:14207: error: syntax error before '*' token
mod_wsgi.c:14207: error: conflicting types for 'method'
mod_wsgi.c:14040: error: previous definition of 'method' was here
mod_wsgi.c:14207: error: redefinition of 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:14207: warning: data definition has no type or storage class
mod_wsgi.c:14209: error: syntax error before '*' token
mod_wsgi.c:14209: error: conflicting types for 'adapter'
mod_wsgi.c:13934: error: previous definition of 'adapter' was here
mod_wsgi.c:14209: error: redefinition of 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:14209: warning: data definition has no type or storage class
mod_wsgi.c:14211: error: conflicting types for 'adapter'
mod_wsgi.c:14209: error: previous definition of 'adapter' was here
mod_wsgi.c:14211: error: conflicting types for 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:14211: warning: initialization makes integer from pointer without a c ast
mod_wsgi.c:14211: error: initializer element is not constant
mod_wsgi.c:14211: warning: data definition has no type or storage class
mod_wsgi.c:14213: error: syntax error before "if"
mod_wsgi.c:14216: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14216: warning: data definition has no type or storage class
mod_wsgi.c:14217: error: conflicting types for 'args'
mod_wsgi.c:14205: error: previous definition of 'args' was here
mod_wsgi.c:14217: error: conflicting types for 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:14217: error: `host' undeclared here (not in a function)
mod_wsgi.c:14217: error: initializer element is not constant
mod_wsgi.c:14217: warning: data definition has no type or storage class
mod_wsgi.c:14218: error: conflicting types for 'flag'
mod_wsgi.c:14206: error: previous definition of 'flag' was here
mod_wsgi.c:14218: error: initializer element is not constant
mod_wsgi.c:14218: warning: data definition has no type or storage class
mod_wsgi.c:14219: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14219: warning: data definition has no type or storage class
mod_wsgi.c:14220: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14220: warning: data definition has no type or storage class
mod_wsgi.c:14221: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14221: warning: data definition has no type or storage class
mod_wsgi.c:14223: error: syntax error before "if"
mod_wsgi.c:14256: error: conflicting types for 'method'
mod_wsgi.c:14207: error: previous definition of 'method' was here
mod_wsgi.c:14256: error: conflicting types for 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:14256: error: invalid type argument of `->'
mod_wsgi.c:14256: error: initializer element is not constant
mod_wsgi.c:14256: warning: data definition has no type or storage class
mod_wsgi.c:14258: error: syntax error before "if"
mod_wsgi.c:14265: error: redefinition of 'object'
mod_wsgi.c:14201: error: previous definition of 'object' was here
mod_wsgi.c:14265: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14265: error: initializer element is not constant
mod_wsgi.c:14265: warning: data definition has no type or storage class
mod_wsgi.c:14266: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14266: warning: data definition has no type or storage class
mod_wsgi.c:14267: error: syntax error before '}' token
mod_wsgi.c:14269: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14269: warning: data definition has no type or storage class
mod_wsgi.c:14270: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14270: warning: data definition has no type or storage class
mod_wsgi.c:14274: error: syntax error before '(' token
mod_wsgi.c:14296: warning: data definition has no type or storage class
mod_wsgi.c:14298: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14298: warning: data definition has no type or storage class
mod_wsgi.c:14300: error: syntax error before "return"
mod_wsgi.c: In function `wsgi_hook_check_user_id':
mod_wsgi.c:14345: error: invalid operands to binary *
mod_wsgi.c:14347: error: syntax error before "module"
mod_wsgi.c:14393: error: `Py_BEGIN_ALLOW_THREADS' undeclared (first use in this function)
mod_wsgi.c:14393: error: syntax error before "apr_thread_mutex_lock"
mod_wsgi.c:14397: error: `Py_END_ALLOW_THREADS' undeclared (first use in this fu nction)
mod_wsgi.c:14400: error: syntax error before "module"
mod_wsgi.c:14402: error: syntax error before "module"
mod_wsgi.c:14411: error: syntax error before "module"
mod_wsgi.c: At top level:
mod_wsgi.c:14428: error: syntax error before '}' token
mod_wsgi.c:14437: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14437: warning: data definition has no type or storage class
mod_wsgi.c:14442: error: redefinition of 'status'
mod_wsgi.c:14000: error: previous definition of 'status' was here
mod_wsgi.c:14442: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:14442: warning: data definition has no type or storage class
mod_wsgi.c:14446: error: syntax error before "if"
mod_wsgi.c:14448: error: conflicting types for 'object'
mod_wsgi.c:14265: error: previous definition of 'object' was here
mod_wsgi.c:14448: error: conflicting types for 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14448: warning: data definition has no type or storage class
mod_wsgi.c:14450: error: redefinition of 'module_dict'
mod_wsgi.c:14200: error: previous definition of 'module_dict' was here
mod_wsgi.c:14450: error: redefinition of 'module_dict'
mod_wsgi.c:8509: error: previous definition of 'module_dict' was here
mod_wsgi.c:14450: error: syntax error before "module"
mod_wsgi.c:14451: error: conflicting types for 'object'
mod_wsgi.c:14448: error: previous definition of 'object' was here
mod_wsgi.c:14451: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14451: error: initializer element is not constant
mod_wsgi.c:14451: warning: data definition has no type or storage class
mod_wsgi.c:14453: error: syntax error before "if"
mod_wsgi.c:14455: error: conflicting types for 'args'
mod_wsgi.c:14217: error: previous definition of 'args' was here
mod_wsgi.c:14455: error: redefinition of 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:14455: warning: data definition has no type or storage class
mod_wsgi.c:14456: error: syntax error before '*' token
mod_wsgi.c:14456: error: conflicting types for 'result'
mod_wsgi.c:14192: error: previous definition of 'result' was here
mod_wsgi.c:14456: error: conflicting types for 'result'
mod_wsgi.c:2274: error: previous definition of 'result' was here
mod_wsgi.c:14456: warning: data definition has no type or storage class
mod_wsgi.c:14457: error: syntax error before '*' token
mod_wsgi.c:14457: error: conflicting types for 'method'
mod_wsgi.c:14256: error: previous definition of 'method' was here
mod_wsgi.c:14457: error: redefinition of 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:14457: warning: data definition has no type or storage class
mod_wsgi.c:14459: error: syntax error before '*' token
mod_wsgi.c:14459: error: conflicting types for 'adapter'
mod_wsgi.c:14211: error: previous definition of 'adapter' was here
mod_wsgi.c:14459: error: redefinition of 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:14459: warning: data definition has no type or storage class
mod_wsgi.c:14461: error: conflicting types for 'adapter'
mod_wsgi.c:14459: error: previous definition of 'adapter' was here
mod_wsgi.c:14461: error: conflicting types for 'adapter'
mod_wsgi.c:8507: error: previous definition of 'adapter' was here
mod_wsgi.c:14461: warning: initialization makes integer from pointer without a c ast
mod_wsgi.c:14461: error: initializer element is not constant
mod_wsgi.c:14461: warning: data definition has no type or storage class
mod_wsgi.c:14463: error: syntax error before "if"
mod_wsgi.c:14466: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14466: warning: data definition has no type or storage class
mod_wsgi.c:14467: error: conflicting types for 'args'
mod_wsgi.c:14455: error: previous definition of 'args' was here
mod_wsgi.c:14467: error: conflicting types for 'args'
mod_wsgi.c:5299: error: previous definition of 'args' was here
mod_wsgi.c:14467: error: `password' undeclared here (not in a function)
mod_wsgi.c:14467: error: initializer element is not constant
mod_wsgi.c:14467: warning: data definition has no type or storage class
mod_wsgi.c:14468: error: conflicting types for 'result'
mod_wsgi.c:14456: error: previous definition of 'result' was here
mod_wsgi.c:14468: error: redefinition of 'result'
mod_wsgi.c:2274: error: previous definition of 'result' was here
mod_wsgi.c:14468: error: initializer element is not constant
mod_wsgi.c:14468: warning: data definition has no type or storage class
mod_wsgi.c:14469: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14469: warning: data definition has no type or storage class
mod_wsgi.c:14470: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14470: warning: data definition has no type or storage class
mod_wsgi.c:14471: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14471: warning: data definition has no type or storage class
mod_wsgi.c:14473: error: syntax error before "if"
mod_wsgi.c:14477: error: redefinition of 'status'
mod_wsgi.c:14442: error: previous definition of 'status' was here
mod_wsgi.c:14477: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:14477: warning: data definition has no type or storage class
mod_wsgi.c:14479: error: syntax error before string constant
mod_wsgi.c:14483: error: conflicting types for 'ap_log_rerror'
/usr/include/httpd/http_log.h:202: error: previous declaration of 'ap_log_rerror ' was here
mod_wsgi.c:14483: error: conflicting types for 'ap_log_rerror'
/usr/include/httpd/http_log.h:202: error: previous declaration of 'ap_log_rerror ' was here
mod_wsgi.c:14483: error: conflicting types for 'r'
mod_wsgi.c:2824: error: previous declaration of 'r' was here
mod_wsgi.c:14483: error: syntax error before '->' token
mod_wsgi.c:14493: error: redefinition of 'status'
mod_wsgi.c:14477: error: previous definition of 'status' was here
mod_wsgi.c:14493: error: redefinition of 'status'
mod_wsgi.c:6515: error: previous definition of 'status' was here
mod_wsgi.c:14493: warning: data definition has no type or storage class
mod_wsgi.c:14495: error: syntax error before string constant
mod_wsgi.c:14499: error: syntax error before '->' token
mod_wsgi.c:14508: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14508: warning: data definition has no type or storage class
mod_wsgi.c:14509: error: syntax error before '}' token
mod_wsgi.c:14523: error: conflicting types for 'method'
mod_wsgi.c:14457: error: previous definition of 'method' was here
mod_wsgi.c:14523: error: conflicting types for 'method'
mod_wsgi.c:8516: error: previous definition of 'method' was here
mod_wsgi.c:14523: error: invalid type argument of `->'
mod_wsgi.c:14523: error: initializer element is not constant
mod_wsgi.c:14523: warning: data definition has no type or storage class
mod_wsgi.c:14525: error: syntax error before "if"
mod_wsgi.c:14532: error: redefinition of 'object'
mod_wsgi.c:14451: error: previous definition of 'object' was here
mod_wsgi.c:14532: error: redefinition of 'object'
mod_wsgi.c:4717: error: previous definition of 'object' was here
mod_wsgi.c:14532: error: initializer element is not constant
mod_wsgi.c:14532: warning: data definition has no type or storage class
mod_wsgi.c:14533: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14533: warning: data definition has no type or storage class
mod_wsgi.c:14534: error: syntax error before '}' token
mod_wsgi.c:14536: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14536: warning: data definition has no type or storage class
mod_wsgi.c:14537: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14537: warning: data definition has no type or storage class
mod_wsgi.c:14541: error: syntax error before '(' token
mod_wsgi.c:14563: warning: data definition has no type or storage class
mod_wsgi.c:14565: warning: parameter names (without types) in function declarati on
mod_wsgi.c:14565: warning: data definition has no type or storage class
mod_wsgi.c:14567: error: syntax error before "return"
apxs:Error: Command failed with rc=65536
.
make: *** [mod_wsgi.la] Error 1
| [
"You likely haven't go either python-dev or httpd-dev package installed and so compilation cant find their header files. Read requirements for what needs to be installed in the README of the mod_wsgi source code.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003218865_django_python.txt |
Q:
Python UTF8 string confusion
Been banging my head on this for a while and I've read a bunch of articles and the issue isn't any clearer. I have a bunch of strings stored in my database, imagine the following:
x = '\xd0\xa4'
y = '\x92'
At the Python shell I get the following:
print x
Ф
print y
?
Which is exactly what I want to see. However then there is the following:
print unicode(x, 'utf8')
Ф
But not this:
unicode(y, 'utf8')
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 0: unexpected code byte
My feeling is that our strings are getting mangled because Django tries to convert them to unicode, but I'm just guessing at this point. Any insights or workarounds appreciated.
UPDATE: When I look at the database at the row that contains the '\x92' value, I see this character as ’. An apostrophe. I'm viewing the contents of the database using a Unicode UTF-8 encoding.
A:
Looks like you have a typo; should be x = '\xd0\xa4'. It helps very much if you use copy paste of what you actually ran and what appeared on the output.
"\x92" is not a valid UTF-8 string. This explains the exception that you got.
More of a puzzle is why print y produced ?. What are you calling "the Python console"?? It appears to be operating in "replace" mode and substituting "?" ... are you sure that it's a plain "?" and not a white "?" inside a black diamond? Why do you say that "?" is exactly what you expect to see?
UPDATE: You now say """When I look at the database at the row that contains the '\x92' value, I see this character as ’. An apostrophe. I'm viewing the contents of the database using a Unicode UTF-8 encoding."""
That's not an apostrophe. It seems that that piece of data has been encoded using one of the cp125X (aka windows-125X) encodings. Illustrating using cp1252 (the usual suspect):
IDLE 2.6.4
>>> import unicodedata
>>> uc = '\x92'.decode('cp1252')
>>> print repr(uc)
u'\u2019'
>>> print uc
’
>>> unicodedata.name(uc)
'RIGHT SINGLE QUOTATION MARK'
>>>
Instead of "viewing the contents of the database using a Unicode UTF-8 encoding" (whatever that means), try writing a small snippet of Python code to extract the offending string and then do print repr(bad_string). Show us the code that you ran, plus the output of the repr(). Also tell us which version of Python, what platform (Windows or unix-based), and what version of what database software. And the part of the CREATE TABLE statement relevant to the column in question.
Also please read this and this.
A:
\x92 is not a valid utf-8 encoded character.
You don't notice that because you use simple (non-unicode) strings for x and y until you try to decode them into unicode strings. When you then print them, they are simple dumped to the terminal "as is" and the terminal itself interprets the bytes according to its encoding setting.
There is a third parameter to unicode() that tells python what to do in case of encoding (decoding) errors:
>>> unicode('\x92', 'utf8', 'replace')
u'\ufffd'
>>> print _
�
A:
I thought any unicode character other than the ASCII subset had a multi-byte representation in UTF-8. Your y makes sense as a single-byte-per-char string, but not as a UTF-8 string. Because the single byte is outside the 0x00 to 0x7F ASCII range, the codec will expect an extra byte or more for the conversion to a "real" unicode character.
I'm not as familiar with Python as I once was, though, and I'm not confident about this answer.
EDIT hops is the better answer IMO.
A:
I see now where you're confused. Let's look at this:
x = '\xd0\xa4'
y = '\x92'
If I print x, I get Ф. This is because my terminal is using UTF-8 as its character encoding. Thus, when it gets D0 A4, it attempts to decode it as UTF-8, and gets a "Ф". If I change my terminal to use, say, ISO-8859-1 ("latin1"), and I say print x, my terminal will attempt to decode D0 A4 using ISO-8859-1, and since D0 A4 is also a valid ISO-8859-1 string, it will decode, but this time, to "Ф".
Now, for print y. This isn't a UTF-8 string, so my terminal can't decode this. It shows me this error, in my case, by printing "�". I'm wondering if you see "�" or "?" - you should probably see the former, but it depends on what your terminal does in the face of bad output.
Your terminal's encoding should match whatever $LANG says, and your program should output data in whatever encoding $LANG specifies. Nowadays, $LANG is typically ???.UTF-8, where the ??? varies. (Mine is en_US.UTF-8)
Now, when you say unicode(y, 'utf8'), Python attempts to decode this as UTF-8, and appropriately throws an exception.
I'm using Gnome Terminal, and can change my character encoding by going to Terminal → Set Character Encoding
A:
0x92 (hex) = 10 010010 (binary)
As UTF-8 can represent 010010 in one byte, the "header" must be 0 (--> 00010010) instead of 10 (which can never be the header of the first byte). Characters may not be represented with more bytes than needed, so "\x92" is not a valid UTF-8 encoded string.
I guess your database uses some one-byte-per-character encoding (such as latin-1). If you're coding the database queries yourself, you must ensure that the connection encoding is correct or that strings are decoded correctly. With Django models, everything should work automatically.
| Python UTF8 string confusion | Been banging my head on this for a while and I've read a bunch of articles and the issue isn't any clearer. I have a bunch of strings stored in my database, imagine the following:
x = '\xd0\xa4'
y = '\x92'
At the Python shell I get the following:
print x
Ф
print y
?
Which is exactly what I want to see. However then there is the following:
print unicode(x, 'utf8')
Ф
But not this:
unicode(y, 'utf8')
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 0: unexpected code byte
My feeling is that our strings are getting mangled because Django tries to convert them to unicode, but I'm just guessing at this point. Any insights or workarounds appreciated.
UPDATE: When I look at the database at the row that contains the '\x92' value, I see this character as ’. An apostrophe. I'm viewing the contents of the database using a Unicode UTF-8 encoding.
| [
"Looks like you have a typo; should be x = '\\xd0\\xa4'. It helps very much if you use copy paste of what you actually ran and what appeared on the output.\n\"\\x92\" is not a valid UTF-8 string. This explains the exception that you got.\nMore of a puzzle is why print y produced ?. What are you calling \"the Python... | [
7,
5,
4,
2,
1
] | [] | [] | [
"django",
"python",
"unicode"
] | stackoverflow_0003220957_django_python_unicode.txt |
Q:
Python Textwrap - forcing 'hard' breaks
I am trying to use textwrap to format an import file that is quite particular in how it is formatted. Basically, it is as follows (line length shortened for simplicity):
abcdef <- Ok line
abcdef
ghijk <- Note leading space to indicate wrapped line
lm
Now, I have got code to work as follows:
wrapper = TextWrapper(width=80, subsequent_indent=' ', break_long_words=True, break_on_hyphens=False)
for l in lines:
wrapline=wrapper.wrap(l)
This works nearly perfectly, however, the text wrapping code doesn't do a hard break at the 80 character mark, it tries to be smart and break on a space (at approx 20 chars in).
I have got round this by replacing all spaces in the string list with a unique character (#), wrapping them and then removing the character, but surely there must be a cleaner way?
N.B Any possible answers need to work on Python 2.4 - sorry!
A:
It sounds like you are disabling most of the functionality of TextWrapper, and then trying to add a little of your own. I think you'd be better off writing your own function or class. If I understand you right, you're simply looking for lines longer than 80 chars, and breaking them at the 80-char mark, and indenting the remainder by one space.
For example, this:
s = """\
This line is fine.
This line is very long and should wrap, It'll end up on a few lines.
A short line.
"""
def hard_wrap(s, n, indent):
wrapped = ""
n_next = n - len(indent)
for l in s.split('\n'):
first, rest = l[:n], l[n:]
wrapped += first + "\n"
while rest:
next, rest = rest[:n_next], rest[n_next:]
wrapped += indent + next + "\n"
return wrapped
print hard_wrap(s, 20, " ")
produces:
This line is fine.
This line is very lo
ng and should wrap,
It'll end up on a
few lines.
A short line.
A:
A generator-based version might be a better solution for you, since it wouldn't need to load the entire string in memory at once:
def hard_wrap(input, width, indent=' '):
for line in input:
indent_width = width - len(indent)
yield line[:width]
line = line[width:]
while line:
yield '\n' + indent + line[:indent_width]
line = line[indent_width:]
Use it like this:
from StringIO import StringIO # Makes strings look like files
s = """abcdefg
abcdefghijklmnopqrstuvwxyz"""
for line in hard_wrap(StringIO(s), 12):
print line,
Which prints:
abcdefg
abcdefghijkl
mnopqrstuvw
xyz
| Python Textwrap - forcing 'hard' breaks | I am trying to use textwrap to format an import file that is quite particular in how it is formatted. Basically, it is as follows (line length shortened for simplicity):
abcdef <- Ok line
abcdef
ghijk <- Note leading space to indicate wrapped line
lm
Now, I have got code to work as follows:
wrapper = TextWrapper(width=80, subsequent_indent=' ', break_long_words=True, break_on_hyphens=False)
for l in lines:
wrapline=wrapper.wrap(l)
This works nearly perfectly, however, the text wrapping code doesn't do a hard break at the 80 character mark, it tries to be smart and break on a space (at approx 20 chars in).
I have got round this by replacing all spaces in the string list with a unique character (#), wrapping them and then removing the character, but surely there must be a cleaner way?
N.B Any possible answers need to work on Python 2.4 - sorry!
| [
"It sounds like you are disabling most of the functionality of TextWrapper, and then trying to add a little of your own. I think you'd be better off writing your own function or class. If I understand you right, you're simply looking for lines longer than 80 chars, and breaking them at the 80-char mark, and inden... | [
1,
1
] | [] | [] | [
"python",
"python_2.4",
"python_2.x",
"word_wrap"
] | stackoverflow_0002865250_python_python_2.4_python_2.x_word_wrap.txt |
Q:
Transforming deeply nested dictionary to 1D dictionary with Python
I have some deeply randomly nested dictionary as follows.
{'CompilationStatistics': {'CodeGeneration': {'EndTime': '2010-04-21T14:03:11',
'StartTime': '2010-04-21T14:03:11',
'StepList': {'EliminatingDuplicates': {'EndTime': '2010-04-21T14:03:11',
'NumberOfFilesEliminated': '14',
'StartTime': '2010-04-21T14:03:11'},
'ModuleGenerator': {'EndTime': '2010-04-21T14:03:11',
'StartTime': '2010-04-21T14:03:11'},
'Munger': {'EndTime': '2010-04-21T14:03:11',
...
How can I transform this into 1D dictionary as follows.
dict["CompilationStatistics_CodeGeneration_EndTime"] = '2010-04-21T14:03:11'
dict["CompilationStatistics_CodeGeneration_StartTime"] = '2010-04-21T14:03:11'
...
dict["CompilationStatistics_directory] = "/abc"
A:
Simplest is to do it recursively:
import collections
def flattendict(d, prefix=()):
r = {}
for k, v in d.iteritems():
pk = prefix + (k,)
if isinstance(v, collections.Mapping):
r.update(flattendict(v, pk))
else:
r['_'.join(pk)] = v
return r
Here's an example use:
d = {'foo': 'bar',
'baz': {'fie': 'foo', 'zip': 'zap'},
'bam': {'fie': 'foo', 'zip': {'zap': 'zup', 'mep': 'mop'}},
}
print flattendict(d)
producing (possibly, of course, in different order)
{'baz_zip': 'zap', 'bam_fie': 'foo', 'foo': 'bar', 'bam_zip_mep': 'mop',
'baz_fie': 'foo', 'bam_zip_zap': 'zup'}
A:
Hmmm, interesting...
This is a perfect opportunity for a recursive function. Here's one that, according to my preliminary tests, will do the job:
def convert(dct_in, dct_out=None, prefix='', sep='_'):
if dct_out is None:
dct_out = {}
if prefix:
prefix += sep
for k, v in dct_in.iteritems():
k_str = prefix + k
if isinstance(v, dict):
convert(v, dct_out, k_str, sep)
else:
dct_out[k_str] = v
return dct_out
A:
Recursively:
def flatten_dict(d):
subdicts = (([(k+"_"+k2, v2) for k2,v2 in flatten_dict(v).iteritems()]
if isinstance(v, dict)
else [(k,v)])
for k,v in d.iteritems())
return dict((k,v) for sd in subdicts for k,v in sd)
| Transforming deeply nested dictionary to 1D dictionary with Python | I have some deeply randomly nested dictionary as follows.
{'CompilationStatistics': {'CodeGeneration': {'EndTime': '2010-04-21T14:03:11',
'StartTime': '2010-04-21T14:03:11',
'StepList': {'EliminatingDuplicates': {'EndTime': '2010-04-21T14:03:11',
'NumberOfFilesEliminated': '14',
'StartTime': '2010-04-21T14:03:11'},
'ModuleGenerator': {'EndTime': '2010-04-21T14:03:11',
'StartTime': '2010-04-21T14:03:11'},
'Munger': {'EndTime': '2010-04-21T14:03:11',
...
How can I transform this into 1D dictionary as follows.
dict["CompilationStatistics_CodeGeneration_EndTime"] = '2010-04-21T14:03:11'
dict["CompilationStatistics_CodeGeneration_StartTime"] = '2010-04-21T14:03:11'
...
dict["CompilationStatistics_directory] = "/abc"
| [
"Simplest is to do it recursively:\nimport collections\n\ndef flattendict(d, prefix=()):\n r = {}\n for k, v in d.iteritems():\n pk = prefix + (k,)\n if isinstance(v, collections.Mapping):\n r.update(flattendict(v, pk))\n else:\n r['_'.join(pk)] = v\n return r\n\nHere's an example use:\nd = {'... | [
3,
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003221396_dictionary_python.txt |
Q:
How to copy last X bits?
Let's say I have two integers with the following binary representations:
01101010
00110101
And now I want to copy the last 3 bits from the first integer over the second one so that it becomes
00110010
What's the easiest way to do that?
(Actually, my goal is to shift the all the X+1 bits to the right one, essentially deleting the Xth bit, and keeping the X-1 bits the same -- in this case, X is 4)
The "why?":
You have a bunch of flags,
1 = 'permission x'
2 = 'permission y'
4 = 'permission z'
8 = 'permission w'
You decide that that "permission y" is no longer needed in your program, and thus shift z and w up a position (making them 2 and 4 respectively). However, now you need to update all the values in your database.... (what formula do you use?)
A:
Depending on your version of python, the way you express binary literals changes, see this question for the details.
I'm using 2.5.2, so I used this:
>>> a = int('01101010', 2)
>>> b = int('00110101', 2)
>>> mask = 07 # Mask out the last 3 bits.
>>> (b & ~mask) | (a & mask)
50
>>> int('00110010', 2)
50
Details:
(b & ~mask) <- This keeps the first n-3 bits. (By negating the 3bit mask).
(a & mask) <- This keeps the last 3 bits.
If you '|' (bitwise OR) them together, you get your desired result.
I didn't understand your goal in the last sentence, so I don't know how to address that :)
A:
Based on Stephen's answer (upvote him), the solution is:
def f(pos, val):
"""
@pos: the position of the bit to remove
@val: the value to remove it from
"""
mask = (1<<(pos-1))-1
return ((val>>1) & ~mask) | (val & mask)
print f(4, int('01101010', 2)) == int('00110010', 2)
| How to copy last X bits? | Let's say I have two integers with the following binary representations:
01101010
00110101
And now I want to copy the last 3 bits from the first integer over the second one so that it becomes
00110010
What's the easiest way to do that?
(Actually, my goal is to shift the all the X+1 bits to the right one, essentially deleting the Xth bit, and keeping the X-1 bits the same -- in this case, X is 4)
The "why?":
You have a bunch of flags,
1 = 'permission x'
2 = 'permission y'
4 = 'permission z'
8 = 'permission w'
You decide that that "permission y" is no longer needed in your program, and thus shift z and w up a position (making them 2 and 4 respectively). However, now you need to update all the values in your database.... (what formula do you use?)
| [
"Depending on your version of python, the way you express binary literals changes, see this question for the details.\nI'm using 2.5.2, so I used this:\n>>> a = int('01101010', 2)\n>>> b = int('00110101', 2)\n>>> mask = 07 # Mask out the last 3 bits.\n>>> (b & ~mask) | (a & mask)\n50\n>>> int('00110010', 2)\n50\n\... | [
8,
2
] | [] | [] | [
"binary",
"bit_manipulation",
"python"
] | stackoverflow_0003221387_binary_bit_manipulation_python.txt |
Q:
reverse mapping of dictionary with Python
Possible Duplicate:
Inverse dictionary lookup - Python
If I have a dictionary named ref as follows
ref = {}
ref["abc"] = "def"
I can get "def" from "abc"
def mapper(from):
return ref[from]
But, how can I get from "def" to "abc"?
def revmapper(to):
??????
A:
If you do this often, you'll want to build a reverse dictionary:
>>> rev_ref = dict((v,k) for k,v in ref.iteritems())
>>> rev_ref
{'def': 'abc'}
>>> def revmapper(to):
... return rev_ref[to]
If it's rare, and you don't care if it's inefficient, do this:
>>> def revmapper(to):
... for k,v in ref.iteritems():
... if v == to: return k
A:
You can make a reverse dictionary:
revdict = dict((v,k) for k,v in ref.items())
then look up what you want:
assert revdict["def"] == "abc"
Note this won't work if two keys map to the same value.
A:
dict(map( lambda a:[a[1],a[0]], d.iteritems() ))
| reverse mapping of dictionary with Python |
Possible Duplicate:
Inverse dictionary lookup - Python
If I have a dictionary named ref as follows
ref = {}
ref["abc"] = "def"
I can get "def" from "abc"
def mapper(from):
return ref[from]
But, how can I get from "def" to "abc"?
def revmapper(to):
??????
| [
"If you do this often, you'll want to build a reverse dictionary:\n>>> rev_ref = dict((v,k) for k,v in ref.iteritems())\n>>> rev_ref\n{'def': 'abc'}\n\n>>> def revmapper(to):\n... return rev_ref[to]\n\nIf it's rare, and you don't care if it's inefficient, do this:\n>>> def revmapper(to):\n... for k,v in ref.i... | [
22,
6,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003221475_dictionary_python.txt |
Q:
Writing a socket-based server in Python, recommended strategies?
I was recently reading this document which lists a number of strategies that could be employed to implement a socket server. Namely, they are:
Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification
Serve many clients with each thread, and use nonblocking I/O and readiness change notification
Serve many clients with each server thread, and use asynchronous I/O
serve one client with each server thread, and use blocking I/O
Build the server code into the kernel
Now, I would appreciate a hint on which should be used in CPython, which we know has some good points, and some bad points. I am mostly interested in performance under high concurrency, and yes a number of the current implementations are too slow.
So if I may start with the easy one, "5" is out, as I am not going to be hacking anything into the kernel.
"4" Also looks like it must be out because of the GIL. Of course, you could use multiprocessing in place of threads here, and that does give a significant boost. Blocking IO also has the advantage of being easier to understand.
And here my knowledge wanes a bit:
"1" is traditional select or poll which could be trivially combined with multiprocessing.
"2" is the readiness-change notification, used by the newer epoll and kqueue
"3" I am not sure there are any kernel implementations for this that have Python wrappers.
So, in Python we have a bag of great tools like Twisted. Perhaps they are a better approach, though I have benchmarked Twisted and found it too slow on a multiple processor machine. Perhaps having 4 twisteds with a load balancer might do it, I don't know. Any advice would be appreciated.
A:
asyncore is basically "1" - It uses select internally, and you just have one thread handling all requests. According to the docs it can also use poll. (EDIT: Removed Twisted reference, I thought it used asyncore, but I was wrong).
"2" might be implemented with python-epoll (Just googled it - never seen it before).
EDIT: (from the comments) In python 2.6 the select module has epoll, kqueue and kevent build-in (on supported platforms). So you don't need any external libraries to do edge-triggered serving.
Don't rule out "4", as the GIL will be dropped when a thread is actually doing or waiting for IO-operations (most of the time probably). It doesn't make sense if you've got huge numbers of connections of course. If you've got lots of processing to do, then python may not make sense with any of these schemes.
For flexibility maybe look at Twisted?
In practice your problem boils down to how much processing you are going to do for requests. If you've got a lot of processing, and need to take advantage of multi-core parallel operation, then you'll probably need multiple processes. On the other hand if you just need to listen on lots of connections, then select or epoll, with a small number of threads should work.
A:
How about "fork"? (I assume that is what the ForkingMixIn does) If the requests are handled in a "shared nothing" (other than DB or file system) architecture, fork() starts pretty quickly on most *nixes, and you don't have to worry about all the silly bugs and complications from threading.
Threads are a design illness forced on us by OSes with too-heavy-weight processes, IMHO. Cloning a page table with copy-on-write attributes seems a small price, especially if you are running an interpreter anyway.
Sorry I can't be more specific, but I'm more of a Perl-transitioning-to-Ruby programmer (when I'm not slaving over masses of Java at work)
Update: I finally did some timings on thread vs fork in my "spare time". Check it out:
http://roboprogs.com/devel/2009.04.html
Expanded:
http://roboprogs.com/devel/2009.12.html
A:
One sollution is gevent. Gevent maries a libevent based event polling with lightweight cooperative task switching implemented by greenlet.
What you get is all the performance and scalability of an event system with the elegance and straightforward model of blocking IO programing.
(I don't know what the SO convention about answering to realy old questions is, but decided I'd still add my 2 cents)
A:
Can I suggest additional links?
cogen is a crossplatform library for network oriented, coroutine based programming using the enhanced generators from python 2.5. On the main page of cogen project there're links to several projects with similar purpose.
A:
http://docs.python.org/library/socketserver.html#asynchronous-mixins
As for multi-processor (multi-core) machines. With CPython due to GIL you'll need at least one process per core, to scale. As you say that you need CPython, you might try to benchmark that with ForkingMixIn. With Linux 2.6 might give some interesting results.
Other way is to use Stackless Python. That's how EVE solved it. But I understand that it's not always possible.
A:
I like Douglas' answer, but as an aside...
You could use a centralized dispatch thread/process that listens for readiness notifications using select and delegates to a pool of worker threads/processes to help accomplish your parallelism goals.
As Douglas mentioned, however, the GIL won't be held during most lengthy I/O operations (since no Python-API things are happening), so if it's response latency you're concerned about you can try moving the critical portions of your code to CPython API.
| Writing a socket-based server in Python, recommended strategies? | I was recently reading this document which lists a number of strategies that could be employed to implement a socket server. Namely, they are:
Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification
Serve many clients with each thread, and use nonblocking I/O and readiness change notification
Serve many clients with each server thread, and use asynchronous I/O
serve one client with each server thread, and use blocking I/O
Build the server code into the kernel
Now, I would appreciate a hint on which should be used in CPython, which we know has some good points, and some bad points. I am mostly interested in performance under high concurrency, and yes a number of the current implementations are too slow.
So if I may start with the easy one, "5" is out, as I am not going to be hacking anything into the kernel.
"4" Also looks like it must be out because of the GIL. Of course, you could use multiprocessing in place of threads here, and that does give a significant boost. Blocking IO also has the advantage of being easier to understand.
And here my knowledge wanes a bit:
"1" is traditional select or poll which could be trivially combined with multiprocessing.
"2" is the readiness-change notification, used by the newer epoll and kqueue
"3" I am not sure there are any kernel implementations for this that have Python wrappers.
So, in Python we have a bag of great tools like Twisted. Perhaps they are a better approach, though I have benchmarked Twisted and found it too slow on a multiple processor machine. Perhaps having 4 twisteds with a load balancer might do it, I don't know. Any advice would be appreciated.
| [
"asyncore is basically \"1\" - It uses select internally, and you just have one thread handling all requests. According to the docs it can also use poll. (EDIT: Removed Twisted reference, I thought it used asyncore, but I was wrong).\n\"2\" might be implemented with python-epoll (Just googled it - never seen it bef... | [
7,
3,
3,
2,
1,
1
] | [] | [] | [
"asynchronous",
"c10k",
"network_programming",
"python",
"sockets"
] | stackoverflow_0000634107_asynchronous_c10k_network_programming_python_sockets.txt |
Q:
Difference between LoopingCall and callInThread in Python's Twisted
I'm trying to figure out the differences between a task.LoopingCall and a reactor.callInThread in Twisted.
All my self.sendLine's in the LoopingCall are performed immediately.
The ones in the callInThread are not. They're only sent after the one in the LoopingCall has finished. Even though I'm sending the right delimiter.
Why is that? What's the difference? Aren't they both threads?
This is the server:
from twisted.internet import reactor, protocol, task
from twisted.protocols import basic
from twisted.python import log
import sys
import time
import threading
import Queue
class ServerProtocol(basic.LineOnlyReceiver):
delimiter = '\0'
clientReady = 1
def __init__(self):
print 'New client has logged on. Waiting for initialization'
def lineReceived(self, line):
if line.startswith('I'):
print 'Data started with I: '+line
user = dict(uid=line[1:6], x=line[6:9], y=line[9:12])
self.factory.users[user['uid']] = user
log.msg(repr(self.factory.users))
self.startUpdateClient(user)
reactor.callInThread(self.transferToClient)
self.sendLine(user['uid'] + ' - Beginning - Initialized')
print user['uid'] + ' - Beginning - Initialized'
elif line.startswith('P'):
print 'Ping!'
elif line[0:3] == 'ACK':
print 'Received ACK'
self.clientReady = 1
#else:
#self.transport.loseConnection()
def _updateClient(self, user):
if self._running == 0:
self._looper.stop()
return
self._running -= 1
self._test += 1
print user['uid'] + ' Sending test data' + str(self._test)
self.sendLine(user['uid'] + ' Test Queue Data #%d' % (self._test,) + '\0')
def startUpdateClient(self, user):
self._running, self._test = 25, 0
self._looper = task.LoopingCall(self._updateClient, user)
self._looper.start(1, now=False)
print user['uid'] + ' - Startupdateclient'
def transferToClient(self):
test = 20
while test > 0:
if self.clientReady == 1:
test = test-1
print 'Reactor test ' + str(test) + ' - ' + str(time.time())
self.clientReady = 0
self.sendLine('This is reactortest ' + str(test) + ' - ' + str(time.time()) +' \0')
class Server(protocol.ServerFactory):
protocol = ServerProtocol
def __init__(self):
self.users = {}
if __name__ == '__main__':
log.startLogging(sys.stderr)
reactor.listenTCP(2000, Server())
reactor.run()
This is the client:
#!/usr/bin/env python
import socket
import time
host = 'localhost'
port = 2000
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send('I12345070060\0')
running = 1
while running:
s.send('ACK\0')
data = s.recv(size)
if data:
print 'Received:', data
else:
print 'Closing'
s.close()
running=0
A:
Why is that? What's the difference? Aren't they both threads?
No. LoopingCall uses callLater; it runs the calls in the reactor.
All my self.sendLine's in the LoopingCall are performed immediately.
Yep, as they should be.
The ones in the callInThread are not.
It's not so much that they're not performed, it's that because you called a reactor API from a thread, which you are never ever ever allowed to do, you have put your program into a state where everything is completely broken, forever. Every future API call may produce bizarre, broken results, or no results, or random, inexplicable crashes.
You know, the normal way multithreaded programs work ;-).
To repeat: every API in twisted, with the sole exception of callFromThread (and by extension things which call callFromThread, like blockingCallFromThread), is not thread safe. Unfortunately, putting in warnings for every single API would be both a code maintenance nightmare, so several users have discovered this constraint in the same way that you have, by calling an API and noticing something weird.
If you have some code which runs in a thread that needs to call a reactor API, use callFromThread or blockingCallFromThread and it will dispatch the call to the reactor thread, where everything should work smoothly. However, for stuff like timed calls, there's really no need to use threads at all, and they would needlessly complicate your program.
A:
Have you looked at the docs for LoopingCall? No thread involved -- it runs (every second, the way you're calling its start method) on the main thread, i.e., typically, the thread of the reactor. callInThread is the only one of the two that causes the function to be run on a separate thread.
| Difference between LoopingCall and callInThread in Python's Twisted | I'm trying to figure out the differences between a task.LoopingCall and a reactor.callInThread in Twisted.
All my self.sendLine's in the LoopingCall are performed immediately.
The ones in the callInThread are not. They're only sent after the one in the LoopingCall has finished. Even though I'm sending the right delimiter.
Why is that? What's the difference? Aren't they both threads?
This is the server:
from twisted.internet import reactor, protocol, task
from twisted.protocols import basic
from twisted.python import log
import sys
import time
import threading
import Queue
class ServerProtocol(basic.LineOnlyReceiver):
delimiter = '\0'
clientReady = 1
def __init__(self):
print 'New client has logged on. Waiting for initialization'
def lineReceived(self, line):
if line.startswith('I'):
print 'Data started with I: '+line
user = dict(uid=line[1:6], x=line[6:9], y=line[9:12])
self.factory.users[user['uid']] = user
log.msg(repr(self.factory.users))
self.startUpdateClient(user)
reactor.callInThread(self.transferToClient)
self.sendLine(user['uid'] + ' - Beginning - Initialized')
print user['uid'] + ' - Beginning - Initialized'
elif line.startswith('P'):
print 'Ping!'
elif line[0:3] == 'ACK':
print 'Received ACK'
self.clientReady = 1
#else:
#self.transport.loseConnection()
def _updateClient(self, user):
if self._running == 0:
self._looper.stop()
return
self._running -= 1
self._test += 1
print user['uid'] + ' Sending test data' + str(self._test)
self.sendLine(user['uid'] + ' Test Queue Data #%d' % (self._test,) + '\0')
def startUpdateClient(self, user):
self._running, self._test = 25, 0
self._looper = task.LoopingCall(self._updateClient, user)
self._looper.start(1, now=False)
print user['uid'] + ' - Startupdateclient'
def transferToClient(self):
test = 20
while test > 0:
if self.clientReady == 1:
test = test-1
print 'Reactor test ' + str(test) + ' - ' + str(time.time())
self.clientReady = 0
self.sendLine('This is reactortest ' + str(test) + ' - ' + str(time.time()) +' \0')
class Server(protocol.ServerFactory):
protocol = ServerProtocol
def __init__(self):
self.users = {}
if __name__ == '__main__':
log.startLogging(sys.stderr)
reactor.listenTCP(2000, Server())
reactor.run()
This is the client:
#!/usr/bin/env python
import socket
import time
host = 'localhost'
port = 2000
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send('I12345070060\0')
running = 1
while running:
s.send('ACK\0')
data = s.recv(size)
if data:
print 'Received:', data
else:
print 'Closing'
s.close()
running=0
| [
"\nWhy is that? What's the difference? Aren't they both threads?\n\nNo. LoopingCall uses callLater; it runs the calls in the reactor.\n\nAll my self.sendLine's in the LoopingCall are performed immediately.\n\nYep, as they should be.\n\nThe ones in the callInThread are not.\n\nIt's not so much that they're not perf... | [
4,
1
] | [] | [] | [
"multithreading",
"python",
"sockets",
"twisted"
] | stackoverflow_0003220991_multithreading_python_sockets_twisted.txt |
Q:
How big can variable be, in python?
I get an response in Python program from SQL server. How big can this response be? What is the maximum? Coult it be as much as about 100 mb?
A:
See sys.maxsize: http://docs.python.org/library/sys.html
The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.
On my MacBook Pro with a 64-bit build of CPython, it's quite sensibly 263-1 bytes:
>>> import sys
>>> sys.maxsize
9223372036854775807
>>>
While on my 32-bit Linux box, it's 2^31-1:
>>> import sys
>>> sys.maxsize
2147483647
>>>
In practice, of course, you're unlikely to be able to actually make use of objects this large, but you can expect to run into serious practical problems (like, say, being out of memory or taking forever to load/save objects from storage) before you hit the theoretical limits.
A:
There's no reason you can't hold 100 MB of data in Python, system memory permitting. But you should try to use an iterator, rather than reading the whole result set into a list.
| How big can variable be, in python? | I get an response in Python program from SQL server. How big can this response be? What is the maximum? Coult it be as much as about 100 mb?
| [
"See sys.maxsize: http://docs.python.org/library/sys.html\n\nThe largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.\n\nOn my MacBook Pro with a 64-bit build of CPython, it's quite sensibly 263-1 bytes:\n>>> impor... | [
7,
5
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0003221739_python_variables.txt |
Q:
How to debug a Jquery Dialog
I have a fairly basic dialog maker for jquery that works in 2 out of 3 places. In the 3rd instance where I try to use it, the fields in the form are disabled once the dialog is displayed.
The general concept behind the code is that the form is on a different page of the website, and for convenience, when javascript is enabled, you can click on the link, get a dialog, and perform the task "on page". The 'rel' attribute has the selector to be used in the jquery .load method, the title of the becomes the dialog title, the page at the 'href' loads and becomes the dialog contents. If Javascript is off, you just get the same form, but with all the header/footer/menu stuff.
How can I figure out what is going on when the dialog displays? Firefox becomes sluggish (right click menu is slow to pop up) and the form fields are disabled. I'm just at a loss for how to debug this, to figure out what is going on at that point. TAB wil select the dialog "close" button, and will select the field that already has a value in it, but that is where it ends. ESC will still close the dialog, so the keyboard is working. I found one other person reporting a similar problem CkEditor Bug, and they appear to have fixed it, but I don't know how they did.
Before I forget: JQuery 1.4.2 JQueryUI 1.8.2
The url looks like:
<a class='dialog' href='/messages/compose/fsm92766/' rel = ' #compose-message' title='Send Message to'>Send Message To</a>
The setup code looks like:
<script lanaguage='javascript'>
$(document).ready(function() {
$('a.dialog').each(function() {
var $link = $(this);
var $dialog = $('<div></div>')
.dialog({
autoOpen: false,
title: $link.attr('title'),
modal: true,
resizable: false,
width: 'auto',
position: 'center'
});
$link.click(function() {
var $url = $link.attr('href') + $link.attr('rel');
$dialog.html($url + "<br/>" +"<img src='http://ender.intomec.com/static/images/loading.gif'></img>");
$dialog.load($url)
$dialog.dialog('open');
return false;
})
})
});
</script>
And the dialog html looks like:
<html>blah blah blah
<body>blah blah blah
-------------- JQuery Selector extracts this part from the page ----------------
<div id='compose-message'>
<form action="" method="post" class="uniForm">
<div style='display:none'>
<input type='hidden' name='csrfmiddlewaretoken' value='3c55a464683748b20a0e6abbcd22225d' />
</div>
<fieldset class="inlineLabels">
<div id="div_id_recipient" class="ctrlHolder ">
<label for="id_recipient">Recipient<span>*</span></label>
<input id="id_recipient" type="text" class="commaseparateduserinput" value="fsm92766" name="recipient" />
</div>
<div id="div_id_subject" class="ctrlHolder ">
<label for="id_subject">Subject<span>*</span></label>
<input id="id_subject" type="text" class="textinput textInput" name="subject" />
</div>
<div id="div_id_body" class="ctrlHolder ">
<label for="id_body">Body<span>*</span></label>
<textarea id="id_body" rows="12" cols="55" name="body" class="textarea"></textarea>
</div>
<div class="form_block">
<input type="submit" value="Send »"/>
</div>
</fieldset>
</form>
</div>
----------------------------------
blah blah blah
</body>
</html>
A:
The Firebug extension for Firefox is great for debugging javascript.
A:
Just to make sure, are you using Firebug?
https://addons.mozilla.org/en-US/firefox/addon/1843/
Its a boon for debugging javascript especially if you're using firefox, they have 'lite' versions for other browsers as well. Its the de-facto javascript debugger as far as I know.
Firebug has an add on FireQuery to enhance debugging for jQuery https://addons.mozilla.org/en-US/firefox/addon/12632/
| How to debug a Jquery Dialog | I have a fairly basic dialog maker for jquery that works in 2 out of 3 places. In the 3rd instance where I try to use it, the fields in the form are disabled once the dialog is displayed.
The general concept behind the code is that the form is on a different page of the website, and for convenience, when javascript is enabled, you can click on the link, get a dialog, and perform the task "on page". The 'rel' attribute has the selector to be used in the jquery .load method, the title of the becomes the dialog title, the page at the 'href' loads and becomes the dialog contents. If Javascript is off, you just get the same form, but with all the header/footer/menu stuff.
How can I figure out what is going on when the dialog displays? Firefox becomes sluggish (right click menu is slow to pop up) and the form fields are disabled. I'm just at a loss for how to debug this, to figure out what is going on at that point. TAB wil select the dialog "close" button, and will select the field that already has a value in it, but that is where it ends. ESC will still close the dialog, so the keyboard is working. I found one other person reporting a similar problem CkEditor Bug, and they appear to have fixed it, but I don't know how they did.
Before I forget: JQuery 1.4.2 JQueryUI 1.8.2
The url looks like:
<a class='dialog' href='/messages/compose/fsm92766/' rel = ' #compose-message' title='Send Message to'>Send Message To</a>
The setup code looks like:
<script lanaguage='javascript'>
$(document).ready(function() {
$('a.dialog').each(function() {
var $link = $(this);
var $dialog = $('<div></div>')
.dialog({
autoOpen: false,
title: $link.attr('title'),
modal: true,
resizable: false,
width: 'auto',
position: 'center'
});
$link.click(function() {
var $url = $link.attr('href') + $link.attr('rel');
$dialog.html($url + "<br/>" +"<img src='http://ender.intomec.com/static/images/loading.gif'></img>");
$dialog.load($url)
$dialog.dialog('open');
return false;
})
})
});
</script>
And the dialog html looks like:
<html>blah blah blah
<body>blah blah blah
-------------- JQuery Selector extracts this part from the page ----------------
<div id='compose-message'>
<form action="" method="post" class="uniForm">
<div style='display:none'>
<input type='hidden' name='csrfmiddlewaretoken' value='3c55a464683748b20a0e6abbcd22225d' />
</div>
<fieldset class="inlineLabels">
<div id="div_id_recipient" class="ctrlHolder ">
<label for="id_recipient">Recipient<span>*</span></label>
<input id="id_recipient" type="text" class="commaseparateduserinput" value="fsm92766" name="recipient" />
</div>
<div id="div_id_subject" class="ctrlHolder ">
<label for="id_subject">Subject<span>*</span></label>
<input id="id_subject" type="text" class="textinput textInput" name="subject" />
</div>
<div id="div_id_body" class="ctrlHolder ">
<label for="id_body">Body<span>*</span></label>
<textarea id="id_body" rows="12" cols="55" name="body" class="textarea"></textarea>
</div>
<div class="form_block">
<input type="submit" value="Send »"/>
</div>
</fieldset>
</form>
</div>
----------------------------------
blah blah blah
</body>
</html>
| [
"The Firebug extension for Firefox is great for debugging javascript.\n",
"Just to make sure, are you using Firebug?\nhttps://addons.mozilla.org/en-US/firefox/addon/1843/\nIts a boon for debugging javascript especially if you're using firefox, they have 'lite' versions for other browsers as well. Its the de-fact... | [
1,
1
] | [] | [] | [
"django",
"jquery",
"jquery_ui",
"python"
] | stackoverflow_0003221792_django_jquery_jquery_ui_python.txt |
Q:
Why are session methods unbound in sqlalchemy using sqlite?
Code replicating the error:
from sqlalchemy import create_engine, Table, Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Message(Base):
__tablename__ = 'messages'
id = Column(Integer, primary_key=True)
message = Column(Integer)
engine = create_engine('sqlite:///' + filename_of_your_choice)
session = sessionmaker(bind=engine)
newmessage = Message()
newmessage.message = "Hello"
messages = session.query(Message).all()
Running this code yields:
Traceback (most recent call last):
File "C:/aaron/test.py", line 20, in <module>
session.commit()
TypeError: unbound method commit() must be called with Session instance as first argument (got nothing instead)
I'm 95% positive that the filename isn't the issue as I can connect to it from the shell
any ideas?
A:
The return value from sessionmaker() is a class. You need to instantiate it before using methods on the instance.
| Why are session methods unbound in sqlalchemy using sqlite? | Code replicating the error:
from sqlalchemy import create_engine, Table, Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Message(Base):
__tablename__ = 'messages'
id = Column(Integer, primary_key=True)
message = Column(Integer)
engine = create_engine('sqlite:///' + filename_of_your_choice)
session = sessionmaker(bind=engine)
newmessage = Message()
newmessage.message = "Hello"
messages = session.query(Message).all()
Running this code yields:
Traceback (most recent call last):
File "C:/aaron/test.py", line 20, in <module>
session.commit()
TypeError: unbound method commit() must be called with Session instance as first argument (got nothing instead)
I'm 95% positive that the filename isn't the issue as I can connect to it from the shell
any ideas?
| [
"The return value from sessionmaker() is a class. You need to instantiate it before using methods on the instance.\n"
] | [
11
] | [] | [] | [
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0003221814_python_sqlalchemy_sqlite.txt |
Q:
What's the best way to dump a MYSQL table to CSV?
Possible Duplicate:
Dump a mysql database to a plaintext (CSV) backup from the command line.
I prefer python, but if mysqldump works...then how can I do that?
A:
SELECT ... INTO OUTFILE ...
| What's the best way to dump a MYSQL table to CSV? |
Possible Duplicate:
Dump a mysql database to a plaintext (CSV) backup from the command line.
I prefer python, but if mysqldump works...then how can I do that?
| [
"SELECT ... INTO OUTFILE ...\n"
] | [
3
] | [] | [] | [
"csv",
"database",
"mysql",
"python"
] | stackoverflow_0003222060_csv_database_mysql_python.txt |
Q:
PIL with Python 2.6.5 on Snow Leopard Install Issues
I am at wit's end. I have a working install of python 2.6.5 with numpy and scipy. I want to use it to do some simple PCA which requires importing images. Well, I figured PIL was the way to go for this. So, following a guide, I downloaded and installed libjpeg6-b. I then used the following commands
tar zxvf jpegsrc.v6b.tar.gz
cd jpeg-6b
cp /usr/share/libtool/config/config.sub .
cp /usr/share/libtool/config/config.guess .
./configure --enable-shared --enable-static
make
I moved over to where I downloaded PIL 1.1.7 and did the following:
tar zxvf Imaging-1.1.7.tar.gz
cd Imaging-1.1.7
(edit the setup.py file to find libjpeg)
python setup.py build
python setup.py install
I then try to import _imaging and I get the famous ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL-1.1.7-py2.6-macosx-10.3-fat.egg/_imaging.so, 2): Symbol not found: _jpeg_resync_to_restart
Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL-1.1.7-py2.6-macosx-10.3-fat.egg/_imaging.so
Expected in: dynamic lookup error.
I tried most/all of the solutions out there already and haven't found much success. I ran otool on my _imaging.so after I restricted my architecture to i386 and got:
Thomas$ otool -L /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/_imaging.so
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/_imaging.so:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
Furthermore, when I ran pip and got this output
--------------------------------------------------------------------
PIL 1.1.6 BUILD SUMMARY
--------------------------------------------------------------------
version 1.1.6
platform darwin 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)]
--------------------------------------------------------------------
--- TKINTER support ok
--- JPEG support ok
--- ZLIB (PNG/ZIP) support ok
--- FREETYPE2 support ok
--------------------------------------------------------------------
To check the build, run the selftest.py script.
for PIL 1.1.6.
I have tried switching to gcc 4.0 and compiling both libjpeg and PIL also.
Any help would be very much appreciated. Also, if you need any more information, please do not hesitate to ask.
A:
Do you know Macports (or Fink)? The easiest way to install software and packages is via Macports. Alternatively you could have a look at the Portfiles of Macports and see how they are compiling those libs.
A:
You can also use pip to install imaging
user easy_install to install pip
easy_install pip
pip install http://effbot.org/downloads/Imaging-1.1.6.tar.gz
Alternatively if this does not help you, I wrote an article on how to get PIL, libjpeg, _imaging to work with python 2.6 and snow leopard
http://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-_jpeg_resync_to_restart/
| PIL with Python 2.6.5 on Snow Leopard Install Issues | I am at wit's end. I have a working install of python 2.6.5 with numpy and scipy. I want to use it to do some simple PCA which requires importing images. Well, I figured PIL was the way to go for this. So, following a guide, I downloaded and installed libjpeg6-b. I then used the following commands
tar zxvf jpegsrc.v6b.tar.gz
cd jpeg-6b
cp /usr/share/libtool/config/config.sub .
cp /usr/share/libtool/config/config.guess .
./configure --enable-shared --enable-static
make
I moved over to where I downloaded PIL 1.1.7 and did the following:
tar zxvf Imaging-1.1.7.tar.gz
cd Imaging-1.1.7
(edit the setup.py file to find libjpeg)
python setup.py build
python setup.py install
I then try to import _imaging and I get the famous ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL-1.1.7-py2.6-macosx-10.3-fat.egg/_imaging.so, 2): Symbol not found: _jpeg_resync_to_restart
Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL-1.1.7-py2.6-macosx-10.3-fat.egg/_imaging.so
Expected in: dynamic lookup error.
I tried most/all of the solutions out there already and haven't found much success. I ran otool on my _imaging.so after I restricted my architecture to i386 and got:
Thomas$ otool -L /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/_imaging.so
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/_imaging.so:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)
Furthermore, when I ran pip and got this output
--------------------------------------------------------------------
PIL 1.1.6 BUILD SUMMARY
--------------------------------------------------------------------
version 1.1.6
platform darwin 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)]
--------------------------------------------------------------------
--- TKINTER support ok
--- JPEG support ok
--- ZLIB (PNG/ZIP) support ok
--- FREETYPE2 support ok
--------------------------------------------------------------------
To check the build, run the selftest.py script.
for PIL 1.1.6.
I have tried switching to gcc 4.0 and compiling both libjpeg and PIL also.
Any help would be very much appreciated. Also, if you need any more information, please do not hesitate to ask.
| [
"Do you know Macports (or Fink)? The easiest way to install software and packages is via Macports. Alternatively you could have a look at the Portfiles of Macports and see how they are compiling those libs.\n",
"You can also use pip to install imaging\nuser easy_install to install pip\n\neasy_install pip\n pip i... | [
1,
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0003106893_python_python_imaging_library.txt |
Q:
Tkinter grid() Manager
I am having a bit of trouble with the Tkinter grid() manager. It is spacing the rows too far apart. I have two entry widgets to place, and I need one almost directly under the other. When I place them both on the same row and column, but change the pady option, it places them directly on top of each other. I know there has to be a way to fix this, never had this problem before.
I am using Python 2.6 on Windows XP.
A:
Are these the only 2 widgets? Or is there another widget,in another column, that ismore than one row in height? If so, it should add to it the "rowspan" attribute.
If that is not the case, I suggesttaht for this cell alone (aply to it "row3span 2), you add a Tkinter.Frame widget, and within this Frame, you simply add your desired widgets with the "pack" manager.
So, instead of:
entr1.grid(my_window, row=1, column=1)
entr2.grid(my_window, row=1, column=1)
you do:
frame = Tkinter.Frame(my_window)
entr1 = Tkinter.<Whatever-widget>(Frame, ...)
entr1.pack()
entr2 = Tkinter.<Whatever-widget>(Frame, ...)
entr2.pack()
A:
Don't place them in the same row and column; place the upper in a row, and the lower in row+1, both in the same column. That does the trick.
Note that the grid manager does not need to have all rows and columns filled with widgets; it ignores empty rows and columns.
| Tkinter grid() Manager | I am having a bit of trouble with the Tkinter grid() manager. It is spacing the rows too far apart. I have two entry widgets to place, and I need one almost directly under the other. When I place them both on the same row and column, but change the pady option, it places them directly on top of each other. I know there has to be a way to fix this, never had this problem before.
I am using Python 2.6 on Windows XP.
| [
"Are these the only 2 widgets? Or is there another widget,in another column, that ismore than one row in height? If so, it should add to it the \"rowspan\" attribute.\nIf that is not the case, I suggesttaht for this cell alone (aply to it \"row3span 2), you add a Tkinter.Frame widget, and within this Frame, you si... | [
2,
2
] | [] | [] | [
"grid",
"python",
"tkinter",
"tkinter_entry"
] | stackoverflow_0003219765_grid_python_tkinter_tkinter_entry.txt |
Q:
How do I extract the names from a simple function?
I've got this piece of code:
import inspect
import ast
def func(foo):
return foo.bar - foo.baz
s = inspect.getsource(func)
xx = ast.parse(s)
class VisitCalls(ast.NodeVisitor):
def visit_Name(self, what):
if what.id == 'foo':
print ast.dump(what.ctx)
VisitCalls().visit(xx)
From function 'func' I'd like to extract:
['foo.bar', 'foo.baz']
or something like:
(('foo', 'bar'), ('foo', 'baz))
edited
Some background to explain why I think I need to do this
I want to convert the code of a trivial python function to a spreadsheet formula.
So I need to convert:
foo.bar - foo.baz
to:
=A1-B1
sample spreadsheet http://img441.imageshack.us/img441/1451/84516405.png
**edited again*
What I've got so far.
The program below outputs:
('A1', 5)
('B1', 3)
('C1', '= A1 - B1')
The code:
import ast, inspect
import codegen # by Armin Ronacher
from collections import OrderedDict
class SpreadSheetFormulaTransformer(ast.NodeTransformer):
def __init__(self, sym):
self.sym = sym
def visit_Attribute(self, node):
name = self.sym[id(eval(codegen.to_source(node)))]
return ast.Name(id=name, ctx=ast.Load())
def create(**kwargs):
class Foo(object): pass
x = Foo()
x.__dict__.update(kwargs)
return x
def register(x,y):
cell[y] = x
sym[id(x)] = y
def func(foo):
return foo.bar - foo.baz
foo = create(bar=5, baz=3)
cell = OrderedDict()
sym = {}
register(foo.bar, 'A1')
register(foo.baz, 'B1')
source = inspect.getsource(func)
tree = ast.parse(source)
guts = tree.body[0].body[0].value
SpreadSheetFormulaTransformer(sym).visit(guts)
code = '= ' + codegen.to_source(guts)
cell['C1'] = code
for x in cell.iteritems():
print x
I found some resources here: Python internals: Working with Python ASTs
I grabbed a working codegen module here.
A:
import ast, inspect
import codegen # by Armin Ronacher
def func(foo):
return foo.bar - foo.baz
names = []
class CollectAttributes(ast.NodeVisitor):
def visit_Attribute(self, node):
names.append(codegen.to_source(node))
source = inspect.getsource(func)
tree = ast.parse(source)
guts = tree.body[0].body[0].value
CollectAttributes().visit(guts)
print names
output:
['foo.bar', 'foo.baz']
A:
I am not sure why you need to retirieve names, a very crude way to get all names and dots in function is
import inspect
import parser
import symbol
import token
import pprint
def func(foo):
return foo.bar - foo.baz
s = inspect.getsource(func)
st = parser.suite(s)
def search(st):
if not isinstance(st, list):
return
if st[0] in [token.NAME, token.DOT]:
print st[1],
else:
for s in st[1:]:
search(s)
search(parser.ast2list(st))
output:
def func foo return foo . bar foo . baz
May be you can improve upon that by reading syntax tree more elegantly, I am using parser instead of ast module because i am on python 2.5
A:
I haven't used the new ast module yet, but I've working code that uses the older compiler.ast to achieve something similar:
def visitGetattr(self, node):
full_name = [node.attrname]
parent = node.expr
while isinstance(parent, compiler.ast.Getattr):
full_name.append(parent.attrname)
parent = parent.expr
if isinstance(parent, compiler.ast.Name):
full_name.append(parent.name)
full_name = ".".join(reversed(full_name))
# do something with full_name
for c in node.getChildNodes():
self.visit(c)
Code slightly paraphrased, I may have introduced inadvertent bugs. I hope this gives you the general idea: you need to visit both Name and Getattr nodes and construct dotted names, and also deal with the fact that you'll see all the intermediate values too (e.g. 'foo' and 'foo.bar').
| How do I extract the names from a simple function? | I've got this piece of code:
import inspect
import ast
def func(foo):
return foo.bar - foo.baz
s = inspect.getsource(func)
xx = ast.parse(s)
class VisitCalls(ast.NodeVisitor):
def visit_Name(self, what):
if what.id == 'foo':
print ast.dump(what.ctx)
VisitCalls().visit(xx)
From function 'func' I'd like to extract:
['foo.bar', 'foo.baz']
or something like:
(('foo', 'bar'), ('foo', 'baz))
edited
Some background to explain why I think I need to do this
I want to convert the code of a trivial python function to a spreadsheet formula.
So I need to convert:
foo.bar - foo.baz
to:
=A1-B1
sample spreadsheet http://img441.imageshack.us/img441/1451/84516405.png
**edited again*
What I've got so far.
The program below outputs:
('A1', 5)
('B1', 3)
('C1', '= A1 - B1')
The code:
import ast, inspect
import codegen # by Armin Ronacher
from collections import OrderedDict
class SpreadSheetFormulaTransformer(ast.NodeTransformer):
def __init__(self, sym):
self.sym = sym
def visit_Attribute(self, node):
name = self.sym[id(eval(codegen.to_source(node)))]
return ast.Name(id=name, ctx=ast.Load())
def create(**kwargs):
class Foo(object): pass
x = Foo()
x.__dict__.update(kwargs)
return x
def register(x,y):
cell[y] = x
sym[id(x)] = y
def func(foo):
return foo.bar - foo.baz
foo = create(bar=5, baz=3)
cell = OrderedDict()
sym = {}
register(foo.bar, 'A1')
register(foo.baz, 'B1')
source = inspect.getsource(func)
tree = ast.parse(source)
guts = tree.body[0].body[0].value
SpreadSheetFormulaTransformer(sym).visit(guts)
code = '= ' + codegen.to_source(guts)
cell['C1'] = code
for x in cell.iteritems():
print x
I found some resources here: Python internals: Working with Python ASTs
I grabbed a working codegen module here.
| [
"import ast, inspect\nimport codegen # by Armin Ronacher\n\ndef func(foo):\n return foo.bar - foo.baz\n\nnames = []\n\nclass CollectAttributes(ast.NodeVisitor):\n def visit_Attribute(self, node):\n names.append(codegen.to_source(node))\n\nsource = inspect.getsource(func)\n\ntree = ast.parse(source)\ngu... | [
6,
1,
0
] | [] | [] | [
"abstract_syntax_tree",
"codegen",
"python"
] | stackoverflow_0003212851_abstract_syntax_tree_codegen_python.txt |
Q:
How to Connect Python to MySQL DataBase ...?
A question about connecting Python To MySQL DB:
How Can I Do That ?!
Link, If You Have References or ...
A:
Here's a simple example:
import MySQLdb
conn = MySQLdb.connect(host="localhost",
user="myusername",
passwd="mypassword",
db="mydb")
c = conn.cursor()
c.execute("SELECT mycolumn FROM mytable WHERE id = %s;", (1,))
c.fetchone()
c.close()
conn.close()
Note that MySQLdb uses %s as the parameter placeholder.
A:
Why not google it?
The connect() method works nearly the same as with _mysql:
import MySQLdb
db=MySQLdb.connect(passwd="moonpie",db="thangs")
To perform a query, you first need a cursor, and then you can execute queries on it:
c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""", (max_price,))
A:
If you want higher level functionality, take a look at http://www.sqlalchemy.org/. It's an awesome piece of work.
| How to Connect Python to MySQL DataBase ...? | A question about connecting Python To MySQL DB:
How Can I Do That ?!
Link, If You Have References or ...
| [
"Here's a simple example:\nimport MySQLdb\nconn = MySQLdb.connect(host=\"localhost\",\n user=\"myusername\",\n passwd=\"mypassword\",\n db=\"mydb\")\nc = conn.cursor()\nc.execute(\"SELECT mycolumn FROM mytable WHERE id = %s;\", (1,))\nc.fetchone()\nc... | [
1,
0,
0
] | [] | [] | [
"database",
"mysql",
"python"
] | stackoverflow_0003222693_database_mysql_python.txt |
Q:
General guidelines for developing a web application
As a programmer used to developing native applications, I'm expanding my horizons and developing my first web app. I'm intermediate to expert with Linux and C, intermediate with Python and HTML and beginner to intermediate with MySQL and Java.
I'm developing a web app that is more or less a resource allocator for a friend of mine. To put it simply, I want this program to help him manage jobs, assigning technicians and equipment. The main screen will be an embedded Google Calendar frame that can be updated dynamically via. their API.
Now, certain jobs require technicians to hold certain certificates, and equipment must be calibrated on a specific schedule. I would also like to track extra data, such as phone numbers, e-mail addresses, job information, etc. To top it all off, I want it to look nice!
I've spent quite some time familiarizing myself with PHP, JavaScript and the DOM and I've developed some functionality and a neat UI.
So far I've been coding server-side w/ PHP to deliver dynamic HTML via. MySQL and then JavaScript to manipulate the DOM. I have tables for technicians, certificates, jobs, phone numbers, etc.
My questions are:
Is there anything missing to my general approach for developing a web app? (Server-side scripting interacts with database to produce dynamic HTML which is then manipulated client-side via. the DOM/client-side scripting).
I chose PHP because it is commonly associated with web development. What are the alternatives? As a beginner I would like to know the "best" server-side language to learn (and I am up for a challenge), or at least be aware of the alternatives.
As far as client-side goes it seems that JavaScript is IT. Is it?
I've heard alot about AJAX but know little to nothing at all about it. Is it an alternative to generating HTML server-side via. a database? What is it/advantages/disadvantages.
I've read that frames are being deprecated. Should I move away from frames and more towards DOM manipulation?
If this application is to be available over the internet I will need to setup a login system of some sort. What are common ways of setting up authentication using hosted or private services?
(Getting a little off topic) Any free hosting suggestions? I'm a student, and hosting the server myself would be unreliable for my friend.
I would really love to implement as much of this project via. Python as possible. What can Python do in terms of programming for the browser and what would it require?
A:
Is there anything missing to my general approach for developing a web app? (Server-side scripting interacts with database to produce dynamic HTML which is then manipulated client-side via. the DOM/client-side scripting).
No - that's the usual setup. Actually, client-side scripting is quite often missing, and web-page is completely refreshed on any interaction. Your description is perfectly fine.
I chose PHP because it is commonly associated with web development. What are the alternatives? As a beginner I would like to know the "best" server-side language to learn (and I am up for a challenge), or at least be aware of the alternatives.
This is a debatable topic, subject to different tastes, thus usually more suited to community wiki; besides, there's bunch of such questions already.
Very quickly, PHP is most common because it is the easiest to configure, but it has bunch of cruft. Perl is old-school, and rather unreadable. Python and Ruby are currently the hottest, owing to amazing dynamic frameworks (CherryPy and Django vs. Sinatra and Rails), but the rivalry is strong, and everyone has picked a side. I'll tell you Ruby is nicer to work with, but someone else will say the same for Python. However, configuring them is a bit more difficult (i.e. not usually standard option on majority of hosting providers).
As far as client-side goes it seems that JavaScript is IT. Is it?
That's it, if you're talking about HTML. The alternatives died off.
I've heard alot about AJAX but know little to nothing at all about it. Is it an alternative to generating HTML server-side via. a database? What is it/advantages/disadvantages.
AJAX is a fancy name for making a HTTP request from JavaScript without reloading the page. The requested content can be executable JS, or parsable XML, or ready-to-insert HTML... and it is the only method to get some data client-side without refreshing the whole page.
I've read that frames are being deprecated. Should I move away from frames and more towards DOM manipulation?
An emphatic yes. However, iframes have their (limited) uses. You most likely do not need them.
If this application is to be available over the internet I will need to setup a login system of some sort. What are common ways of setting up authentication using hosted or private services?
Username + encrypted password in database, when user enters username + password, encrypt password and check both against the database. If successful, record username in session.
Another way is OpenID, but it requires a third-party OpenID provider.
(Getting a little off topic) Any free hosting suggestions? I'm a student, and hosting the server myself would be unreliable for my friend.
Not too knowledgeable. I know about comyr (general purpose) and heroku (Ruby), both free for non-commercial use, AFAICR, but a bit of research can get you more.
I would really love to implement as much of this project via. Python as possible. What can Python do in terms of programming for the browser and what would it require?
It can do everything in terms of server-side programming, just like any other Turing-complete language. It can do it pretty easily, being a dynamic language with lots of nice libraries targeted for web development. It will not do anything at all for the browser, though. Check out CherryPy for lightweight, and Django for heavyweight web app framework.
But I thought you chose PHP?...
A:
Is there anything missing to my general approach for developing a web app? (Server-side scripting interacts with database to produce dynamic HTML which is then manipulated client-side via. the DOM/client-side scripting).
You'll need a scheduler like cron to enforce things on the server side beyond the calendar. A calendar is great for recording the events (such as maintenance of equipment or calls for engineers) but in order to enforce this you may want to put calls on hold for an engineer if their equipment has missed a maintenance, etc.
I chose PHP because it is commonly associated with web development. What are the alternatives? As a beginner I would like to know the "best" server-side language to learn (and I am up for a challenge), or at least be aware of the alternatives.
There are many alternatives, Pylons or Google App Engine may be good alternatives for you from a Python background.
As far as client-side goes it seems that JavaScript is IT. Is it?
There is Flash, Silverlight, etc. jQuery (a JavaScript framework) seems to be a popular choice.
I've heard alot about AJAX but know little to nothing at all about it. Is it an alternative to generating HTML server-side via. a database? What is it/advantages/disadvantages.
AJAX boils down to dynamically updating the page viewed instead of making a new page every time.
I've read that frames are being deprecated. Should I move away from frames and more towards DOM manipulation?
It depends if you are moving to AJAX or not really. iframes are likely to remain, even if traditional frames are removed from browsers.
If this application is to be available over the internet I will need to setup a login system of some sort. What are common ways of setting up authentication using hosted or private services?
OpenID seems to be popular and with the availability of libraries it should remove much of the effort required in maintaining your own authentication.
(Getting a little off topic) Any free hosting suggestions? I'm a student, and hosting the server myself would be unreliable for my friend.
Google App Engine is free for up to 5 million page views a month (approx). If you set up billing for $0 a day you'll get even more resources for free.
I would really love to implement as much of this project via. Python as possible. What can Python do in terms of programming for the browser and what would it require?
If you are coding for use Internet Explorer you can call Python using an activex object, but then things get messy.
As an added bonus Google App Engine support schedules, has built in libraries for talking to Google Calendar, supports OpenID (referred to as Federated Login) and provides free hosting for smaller use.
The type of application you are describing is generally called 'Field Service'. Other things you may want to look at are ViaPost for sending out paperwork, Lone Worker for ensuring the safety of engineers on site (may be a regulation), schedulers (there are many patterns and systems including some that use triangulation to make engineers more effective) and automated voice systems (some of them have an API) combined with vehicle tracking to inform clients that the engineer will be late (this can be automated).
You may also consider using mobile devices for dynamic call dispatching, collecting client signatures and printing off paperwork at site.
A:
I'd like to suggest ditching PHP as soon as possible. Searching 'php wtf' here should be illuminating. While it is possible to write secure, safe, reliable applications in PHP, I think it is despite the best efforts of the PHP team to make The Most Exciting And Surprisin Language EVAR. With lots of funny side-effects. And pretend-security-options. If most of what PHP looks like is appealing to you, I think I'd suggest using Perl instead. It should be much less surprising.
So, with my rant against PHP out of the way, you have a LOT of much better options. Python has Django, Zope, and Twisted Matrix. They each solve different problems, allowing you to write applications at different levels: Django imposes some Model-View-Controller structure on your code, Zope is a much larger CMS framework, and Twisted Matrix provides a lot of super-keen programming primitives if you want to write things pretty close to the wire. (You're something like five lines of code away from a very-simple-yet-neat web server with Twisted that runs your application code..)
If you really want to learn another language in the process, Ruby on Rails is getting a lot of the hype, and for mostly good reasons. I've really enjoyed coding Ruby on Rails, the imposed structure is fantastic for anything beyond trivial applications, and it mostly gets out of your way with reasonable assumptions.
Perl is 'the old standby'. I'd take it over PHP any day, but I can't stand Perl's OO or modules system. So it's hard for me to really endorse it.
I'd like to suggest against Flash and Silverlight on the client-side: First, Flash is a giant resource hog and security disaster, and Silverlight, while probably better than Flash on both fronts, is even less portable than Flash. (I strongly recommend trying your site on a handful of mobile browsers; it doesn't have to look pretty, but everything ought to work. :)
| General guidelines for developing a web application | As a programmer used to developing native applications, I'm expanding my horizons and developing my first web app. I'm intermediate to expert with Linux and C, intermediate with Python and HTML and beginner to intermediate with MySQL and Java.
I'm developing a web app that is more or less a resource allocator for a friend of mine. To put it simply, I want this program to help him manage jobs, assigning technicians and equipment. The main screen will be an embedded Google Calendar frame that can be updated dynamically via. their API.
Now, certain jobs require technicians to hold certain certificates, and equipment must be calibrated on a specific schedule. I would also like to track extra data, such as phone numbers, e-mail addresses, job information, etc. To top it all off, I want it to look nice!
I've spent quite some time familiarizing myself with PHP, JavaScript and the DOM and I've developed some functionality and a neat UI.
So far I've been coding server-side w/ PHP to deliver dynamic HTML via. MySQL and then JavaScript to manipulate the DOM. I have tables for technicians, certificates, jobs, phone numbers, etc.
My questions are:
Is there anything missing to my general approach for developing a web app? (Server-side scripting interacts with database to produce dynamic HTML which is then manipulated client-side via. the DOM/client-side scripting).
I chose PHP because it is commonly associated with web development. What are the alternatives? As a beginner I would like to know the "best" server-side language to learn (and I am up for a challenge), or at least be aware of the alternatives.
As far as client-side goes it seems that JavaScript is IT. Is it?
I've heard alot about AJAX but know little to nothing at all about it. Is it an alternative to generating HTML server-side via. a database? What is it/advantages/disadvantages.
I've read that frames are being deprecated. Should I move away from frames and more towards DOM manipulation?
If this application is to be available over the internet I will need to setup a login system of some sort. What are common ways of setting up authentication using hosted or private services?
(Getting a little off topic) Any free hosting suggestions? I'm a student, and hosting the server myself would be unreliable for my friend.
I would really love to implement as much of this project via. Python as possible. What can Python do in terms of programming for the browser and what would it require?
| [
"\n\nIs there anything missing to my general approach for developing a web app? (Server-side scripting interacts with database to produce dynamic HTML which is then manipulated client-side via. the DOM/client-side scripting).\n\n\nNo - that's the usual setup. Actually, client-side scripting is quite often missing, ... | [
3,
2,
1
] | [] | [] | [
"database",
"dom",
"python"
] | stackoverflow_0003222654_database_dom_python.txt |
Q:
Why is Python 3.1 slower than 2.6 for this code?
Consider the following code (from here, with the number of tests increased):
from timeit import Timer
def find_invpow(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
high = 1
while high ** n < x:
high *= 2
low = high/2
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
def find_invpowAlt(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
low = 10 ** (len(str(x)) / n)
high = low * 10
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
x = 237734537465873465
n = 5
tests = 1000000
print "Norm", Timer('find_invpow(x,n)', 'from __main__ import find_invpow, x,n').timeit(number=tests)
print "Alt", Timer('find_invpowAlt(x,n)', 'from __main__ import find_invpowAlt, x,n').timeit(number=tests)
Using Python 2.6 (Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2), the times reported are:
Norm 9.73663210869
Alt 9.53973197937
However, on the same machine using Python 3.1 (Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48) [GCC 4.4.3] on linux2), the times are:
Norm 28.4206559658
Alt 26.8007400036
Does anyone know why this code runs three times slower on Python 3.1?
A:
I got steadily decreasing times from 2.5, 2.6, 2.7 and 3.1 (Windows XP SP2) ... with the "/" version. With the //, the 3.1 times were dramatically smaller than the 2.X times e.g. "Norm" dropped from 6.35 (py2.7) to 3.62 (py3.1).
Note that in 2.x, there are ints (machine word, 32 or 64 bits) and longs (variable length). In 3.x, long has been renamed int, and int went away. My guess is that converting from long to float may cause the extra time with /.
In any case, a much better "Alt" version would start off with this code:
high = 1
highpown = 1
while highpown < x:
high <<= 1
highpown <<= n
A:
The // operator performs integer division (or floor division) in both python 2 and 3, whereas the / operator performs floor division in python 2 given integer operands and true division in python 3 given any operands.
Try replacing the / operator with the // operator.
| Why is Python 3.1 slower than 2.6 for this code? | Consider the following code (from here, with the number of tests increased):
from timeit import Timer
def find_invpow(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
high = 1
while high ** n < x:
high *= 2
low = high/2
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
def find_invpowAlt(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
low = 10 ** (len(str(x)) / n)
high = low * 10
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
x = 237734537465873465
n = 5
tests = 1000000
print "Norm", Timer('find_invpow(x,n)', 'from __main__ import find_invpow, x,n').timeit(number=tests)
print "Alt", Timer('find_invpowAlt(x,n)', 'from __main__ import find_invpowAlt, x,n').timeit(number=tests)
Using Python 2.6 (Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2), the times reported are:
Norm 9.73663210869
Alt 9.53973197937
However, on the same machine using Python 3.1 (Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48) [GCC 4.4.3] on linux2), the times are:
Norm 28.4206559658
Alt 26.8007400036
Does anyone know why this code runs three times slower on Python 3.1?
| [
"I got steadily decreasing times from 2.5, 2.6, 2.7 and 3.1 (Windows XP SP2) ... with the \"/\" version. With the //, the 3.1 times were dramatically smaller than the 2.X times e.g. \"Norm\" dropped from 6.35 (py2.7) to 3.62 (py3.1).\nNote that in 2.x, there are ints (machine word, 32 or 64 bits) and longs (variabl... | [
3,
2
] | [] | [] | [
"performance",
"python",
"python_3.x"
] | stackoverflow_0003222554_performance_python_python_3.x.txt |
Q:
csv file column reading and extracting using python
i have the following code...
reader=csv.DictReader(open("test1.csv","r"))
allrows = list(reader)
keepcols = [c for c in allrows[0] if all(r[c] != '0' for r in allrows)]
print keepcols
writer=csv.DictWriter(open("output1.csv","w"),fieldnames='keepcols',extrasaction='ignore')
writer.writerows(allrows)
i have a csv file which has about 45 cols..
the first column has some names..
except the first column, all others have only 0's and 1's...
and of course, the whole table has some titles as well..
i m trying to read columns from csv file and i need to extract only those cols with 1's
the problem is the output file is empty even though there are a few columns in the table with 1's..
could somebody please help me out.... :( i m stuck terribly..
Title 3003_contact 3003_backbone 3003_sidechain 3003_polar 3003_hydrophobic 3003_acceptor 3003_donor 3003_aromatic
l1 1 1 0 1 1 0 0 0
l1 1 0 1 0 0 0 1 0
l1 1 0 0 0 0 0 0 0
l1 1 0 0 0 1 0 0 1
l1 1 0 0 0 0 0 0 0
l2 1 0 0 0 1 0 0 0
l2 1 0 0 0 0 1 0 0
l3 1 0 0 0 0 0 0 0
l3 1 0 0 0 0 0 1 0
l3 1 0 0 0 0 0 0 1
l3 1 0 0 0 0 0 0 0
l3 1 0 0 0 0 0 0 0
l4 1 0 0 0 0 0 0 0
l4 1 0 0 0 0 0 0 0
l4 1 0 0 0 0 0 0 0
it returns only column 1... I've tried changing 'keepcols' to keepcols... and I get column2 first and then column1 as output
A:
Edit: If the input file is a comma-separated values file, then
to maintain the order of the keys, use reader.fieldnames instead of the keys in allrows[0].
So the solution would be:
keepcols = [c for c in reader.fieldnames if any(r[c] != '0' for r in allrows)]
The input file posted above looks like it has space-separated columns. In this case, I don't think csv is the right tool for parsing it. Instead, you can use split:
import csv
with open("test1.csv","r") as f:
fields=next(f).split()
# print(fields)
allrows=[]
for line in f:
line=line.split()
row=dict(zip(fields,line))
allrows.append(row)
# print(row)
keepcols = [c for c in fields if any(row[c] != '0' for row in allrows)]
print keepcols
writer=csv.DictWriter(open("output1.csv","w"),fieldnames=keepcols,extrasaction='ignore')
writer.writerows(allrows)
Edit2: The reason why the column order was changing is because for c in allrows[0] returns the keys of allrows[0] in an unspecified order. dict keys are not ordered by default. The above code works around this by defining fields to be a list, not a dict.
Original answer:
Change fieldnames='keepcols' to fieldnames=keepcols.
fieldnames needs to be a sequence of keys, such as ['fieldA','fieldB',...].
A potential pitfall to be aware of in Python is that strings are sequences. When you iterate over a string, you get the characters of the string. So when you say fieldnames='keepcols', you are setting fieldnames to be the sequence of characters ['k','e','e','p','c','o','l','s']. You don't get an error because this is a valid sequence of keys. But your list of dicts, allrows doesn't happen to have these keys. writer.writerows blithely ignores this since extrasaction='ignore'.
| csv file column reading and extracting using python | i have the following code...
reader=csv.DictReader(open("test1.csv","r"))
allrows = list(reader)
keepcols = [c for c in allrows[0] if all(r[c] != '0' for r in allrows)]
print keepcols
writer=csv.DictWriter(open("output1.csv","w"),fieldnames='keepcols',extrasaction='ignore')
writer.writerows(allrows)
i have a csv file which has about 45 cols..
the first column has some names..
except the first column, all others have only 0's and 1's...
and of course, the whole table has some titles as well..
i m trying to read columns from csv file and i need to extract only those cols with 1's
the problem is the output file is empty even though there are a few columns in the table with 1's..
could somebody please help me out.... :( i m stuck terribly..
Title 3003_contact 3003_backbone 3003_sidechain 3003_polar 3003_hydrophobic 3003_acceptor 3003_donor 3003_aromatic
l1 1 1 0 1 1 0 0 0
l1 1 0 1 0 0 0 1 0
l1 1 0 0 0 0 0 0 0
l1 1 0 0 0 1 0 0 1
l1 1 0 0 0 0 0 0 0
l2 1 0 0 0 1 0 0 0
l2 1 0 0 0 0 1 0 0
l3 1 0 0 0 0 0 0 0
l3 1 0 0 0 0 0 1 0
l3 1 0 0 0 0 0 0 1
l3 1 0 0 0 0 0 0 0
l3 1 0 0 0 0 0 0 0
l4 1 0 0 0 0 0 0 0
l4 1 0 0 0 0 0 0 0
l4 1 0 0 0 0 0 0 0
it returns only column 1... I've tried changing 'keepcols' to keepcols... and I get column2 first and then column1 as output
| [
"Edit: If the input file is a comma-separated values file, then \nto maintain the order of the keys, use reader.fieldnames instead of the keys in allrows[0].\nSo the solution would be:\nkeepcols = [c for c in reader.fieldnames if any(r[c] != '0' for r in allrows)]\n\nThe input file posted above looks like it has sp... | [
4
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003222831_csv_python.txt |
Q:
Save an email.Message object into a file
I am trying to modify emails stored as text files. I first import a message like this :
import email
f = open('filename')
msg = email.message_from_file(f)
Then, I make all the modifications I want, using the features of the email module.
The last step is to save the Message object (msg) in a file. What is the piece of code that does this ? There seems not to be any simple function like "message_to_file()"...
Many thanks.
A:
The Messsage.as_string method should give you a flattened version of the message that you can write out just as you would any other string:
msg.as_string()
If this doesn't provide exactly the format you want, consider trying the email.generator module? If I read things correctly, you should be able to do something like this:
generator = email.generator.Generator(out_file)
generator.flatten(msg)
Assuming out_file is an open and writable file and msg is your message.
| Save an email.Message object into a file | I am trying to modify emails stored as text files. I first import a message like this :
import email
f = open('filename')
msg = email.message_from_file(f)
Then, I make all the modifications I want, using the features of the email module.
The last step is to save the Message object (msg) in a file. What is the piece of code that does this ? There seems not to be any simple function like "message_to_file()"...
Many thanks.
| [
"The Messsage.as_string method should give you a flattened version of the message that you can write out just as you would any other string:\nmsg.as_string()\nIf this doesn't provide exactly the format you want, consider trying the email.generator module? If I read things correctly, you should be able to do somethi... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0003222921_python.txt |
Q:
Some advices for creating a WMS service and a desktop client?
I'm learning to create a WMS service using MapServer and after that I want to develop a PyQt desktop application which will access it. I don't know what is the best way to do that because I have seen a lot of web solutions but it's not what I'm looking for. Neither I know if there are libraries that can help me. Can you give me some advices?
Thanks in advance!
A:
I'm assuming you have no trouble setting up a WMS service on MapServer. Test this is working with a GIS desktop client, or a simple OpenLayers web page.
To develop a WMS client I'd build on top of the GDAL library. This is also included in MapServer.
GDAL has the ability to read images
from a remote WMS server, and treat
them as it does any other data source:
which means that it can take the
images, and convert them to any other
format, from JPEG2000 to GeoTIFF.
http://crschmidt.net/blog/archives/285/producing-a-large-image-from-openaerialmap/
As an added bonus GDAL includes Python bindings which will help with scripting.
http://pypi.python.org/pypi/GDAL/
You will also need libcurl to access URLs. libcurl too has Python bindings - http://curl.haxx.se/libcurl/python/
libcurl is also included in MapServer, which itself can be both a WMS server and client. You can also check out the C++ source code for how the MapServer client works - https://trac.osgeo.org/mapserver/browser/branches/branch-5-6/mapserver/mapwmslayer.c
A WMS service returns an image (apart from a few extra meta services), so the custom development will be based around building the correct WMS requests based on user actions.
If you want to have fast performance then have a look at TileCache which will cache the WMS results on the server for quicker use (and also cache locally).
| Some advices for creating a WMS service and a desktop client? | I'm learning to create a WMS service using MapServer and after that I want to develop a PyQt desktop application which will access it. I don't know what is the best way to do that because I have seen a lot of web solutions but it's not what I'm looking for. Neither I know if there are libraries that can help me. Can you give me some advices?
Thanks in advance!
| [
"I'm assuming you have no trouble setting up a WMS service on MapServer. Test this is working with a GIS desktop client, or a simple OpenLayers web page. \nTo develop a WMS client I'd build on top of the GDAL library. This is also included in MapServer. \n\nGDAL has the ability to read images\n from a remote WMS s... | [
1
] | [] | [] | [
"gis",
"pyqt",
"python",
"wms"
] | stackoverflow_0003222954_gis_pyqt_python_wms.txt |
Q:
geo name database (city, points of interest)
I am building a travel website with django. When a user is typing in the destination city name (or points of interest, like yellow stone), I want to do ajax auto suggestion. The question is how I could get the suggestion database? Is there any web service? Best if it could also support foreign cities. Thanks a lot.
A:
What you want is called a gazetteer database.
The official USGS gazetteer for the USA is available for download.
Two global geocoded databases include:
Geonames has a free list of cities and POI. It includes the USGS gazetteer and lots of other info. You might have to subset their database however, as it might return too many results for you.
Maxmind also have a free database of cities.
A:
take a look at OpenStreetMap there are a lot of cities, pois both in chinease and english
| geo name database (city, points of interest) | I am building a travel website with django. When a user is typing in the destination city name (or points of interest, like yellow stone), I want to do ajax auto suggestion. The question is how I could get the suggestion database? Is there any web service? Best if it could also support foreign cities. Thanks a lot.
| [
"What you want is called a gazetteer database.\nThe official USGS gazetteer for the USA is available for download.\nTwo global geocoded databases include:\nGeonames has a free list of cities and POI. It includes the USGS gazetteer and lots of other info. You might have to subset their database however, as it migh... | [
6,
1
] | [] | [] | [
"autosuggest",
"django",
"geography",
"gis",
"python"
] | stackoverflow_0002970830_autosuggest_django_geography_gis_python.txt |
Q:
Problems regarding Boost::Python and Boost::Threads
Me and a friend are developing an application which uses Boost::Python. I have defined an interface in C++ (well a pure virtual class), exposed through Boost::Python to the users, who have to inherit from it and create a class, which the application takes and uses for some callback mechanism.
Everything that far goes pretty well. Now, the function callback may take some time (the user may have programmed some heavy stuff)... but we need to repaint the window, so it doesn't look "stuck".We wanted to use Boost::Thread for this. Only one callback will be running at a time (no other threads will call python at the same time), so we thought it wouldn't be such a great deal... since we don't use threads inside python, nor in the C++ code wrapped for python.
What we do is calling PyEval_InitThreads() just after Py_Initialize(), then, before calling the function callback inside it's own boost thread, we use the macro PY_BEGIN_ALLOW_THREADS and, and the macro PY_END_ALLOW_THREADS when the thread has ended.
I think I don't need to say the execution never reaches the second macro. It shows several errors everytime it runs... but t's always while calling the actual callback. I have googled a lot, even read some of the PEP docs regarding threads, but they all talk about threading inside the python module (which I don't sice it's just a pure virtual class exposed) or threading inside python, not about the main application calling Python from several threads.
Please help, this has been frustrating me for several hours.
Ps. help!
A:
Python can be called from multiple threads serially, I don't think that's a problem. It sounds to me like your errors are just coming from bad C++ code, as you said the errors happened after PY_BEGIN_ALLOW_THREADS and before PY_END_ALLOW_THREADS.
If you know that's not true, can you post a little more of your actual code and show exactly where its erroring and exactly what errors its giving?
| Problems regarding Boost::Python and Boost::Threads | Me and a friend are developing an application which uses Boost::Python. I have defined an interface in C++ (well a pure virtual class), exposed through Boost::Python to the users, who have to inherit from it and create a class, which the application takes and uses for some callback mechanism.
Everything that far goes pretty well. Now, the function callback may take some time (the user may have programmed some heavy stuff)... but we need to repaint the window, so it doesn't look "stuck".We wanted to use Boost::Thread for this. Only one callback will be running at a time (no other threads will call python at the same time), so we thought it wouldn't be such a great deal... since we don't use threads inside python, nor in the C++ code wrapped for python.
What we do is calling PyEval_InitThreads() just after Py_Initialize(), then, before calling the function callback inside it's own boost thread, we use the macro PY_BEGIN_ALLOW_THREADS and, and the macro PY_END_ALLOW_THREADS when the thread has ended.
I think I don't need to say the execution never reaches the second macro. It shows several errors everytime it runs... but t's always while calling the actual callback. I have googled a lot, even read some of the PEP docs regarding threads, but they all talk about threading inside the python module (which I don't sice it's just a pure virtual class exposed) or threading inside python, not about the main application calling Python from several threads.
Please help, this has been frustrating me for several hours.
Ps. help!
| [
"Python can be called from multiple threads serially, I don't think that's a problem. It sounds to me like your errors are just coming from bad C++ code, as you said the errors happened after PY_BEGIN_ALLOW_THREADS and before PY_END_ALLOW_THREADS.\nIf you know that's not true, can you post a little more of your ac... | [
1
] | [] | [] | [
"boost_python",
"boost_thread",
"c++",
"python"
] | stackoverflow_0003197236_boost_python_boost_thread_c++_python.txt |
Q:
How to use nose with IronPython?
I installed nose using the 'setup.py install' on the command line , I am able to run 'nosetests' and any python file matching testMatch regular expression is picked up and tests are automated in the %python home%\Scripts directory. Now I want nose to work with my iron Python files , how do I install nose on the %Iron Python home% directory ? i noticed my Iron Python Home directory does not even have a Scripts folder.
If i try running 'nosetests' with iron python code , it throws all sorts of exception
for eg. no module named clr.
Is anybody using nose with iron python ? if yes , please guide me. I have been struggling with this since an entire day,
currently my only workaround has been adding the following in my IronPython code:
import nose
nose.main(argv=['<arguments>'])
is this is the only way to go about using nose in iron python files ?
if there is no other way , then I wanted to know how to use the several plugins that nose has ? especially the coverage plugin ? i installed it for python2.6 , but how to make it work for ironpython ?
The reason I am asking is because with python , it gets easy to use the plugins just by calling the command line , but with IronPython I don't know how to make it work.
A:
Your solution is actually all nosetests does:
#!/usr/bin/env python
from nose import main
if __name__ == '__main__':
main()
You'll want to make sure you add your system's Python lib to the path for it to find the nose extensions:
>>>import sys
>>>sys.path.append(r'C:\Python26\lib')
And you'll need to make sure you're executing your script with ipy.exe and not your system's Python executable.
A:
I've been trying to run the sqlalchemy test suite, which uses nose and a plugin. So, this may be useful if anyone is trying to run nose on ironpython with plugins.
this tends not to work transparently on ipy, because setuptools doesn't quite work on ironpython.
after a bit of diggin, i found the nose init.py instructions for registering a plugin manually - essentially, import the plugin class (which subclasses nose.plugins.Plugin), and add it to the call to main().
here's what my script ended up looking like:
import sys, os
#import ironclad #not needed. i think.
sys.path.append(r'C:\Python26\lib')
#now load Jeff Hardys sqlite dll which is in sqlite folder (sqlite not supported on ipy)
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),'sqlite'))
import clr
clr.AddReference('IronPython.SQLite')
#load plugin
from sqlalchemy.test.noseplugin import NoseSQLAlchemy
from nose import main
if __name__ == '__main__':
main(addplugins=[NoseSQLAlchemy()])
Hope this helps someone!
| How to use nose with IronPython? | I installed nose using the 'setup.py install' on the command line , I am able to run 'nosetests' and any python file matching testMatch regular expression is picked up and tests are automated in the %python home%\Scripts directory. Now I want nose to work with my iron Python files , how do I install nose on the %Iron Python home% directory ? i noticed my Iron Python Home directory does not even have a Scripts folder.
If i try running 'nosetests' with iron python code , it throws all sorts of exception
for eg. no module named clr.
Is anybody using nose with iron python ? if yes , please guide me. I have been struggling with this since an entire day,
currently my only workaround has been adding the following in my IronPython code:
import nose
nose.main(argv=['<arguments>'])
is this is the only way to go about using nose in iron python files ?
if there is no other way , then I wanted to know how to use the several plugins that nose has ? especially the coverage plugin ? i installed it for python2.6 , but how to make it work for ironpython ?
The reason I am asking is because with python , it gets easy to use the plugins just by calling the command line , but with IronPython I don't know how to make it work.
| [
"Your solution is actually all nosetests does:\n#!/usr/bin/env python\n\nfrom nose import main\n\nif __name__ == '__main__':\n main()\n\nYou'll want to make sure you add your system's Python lib to the path for it to find the nose extensions:\n>>>import sys\n>>>sys.path.append(r'C:\\Python26\\lib')\n\nAnd you'll... | [
0,
0
] | [] | [] | [
"ironpython",
"nosetests",
"python"
] | stackoverflow_0003198500_ironpython_nosetests_python.txt |
Q:
Manipulate and print to PDF files in a script
I have several pdf files of some lecture slides. I want to do the following: print every pdf file to another pdf file in which there are 6 slides per page and then merge all the resulting files to one big file while making sure that every original file starts on an odd page number (Edit: obviously, it will be printed in duplex) (possibly adding blank pages when necessary).
Is that possible?
Edit: For those interested, this is for printing a LOT of course material for an exam... And I need to do this for a lot of courses.
A:
If it were me, I would use PDFjam or a similar tool to perform the 6-up on each of the source documents.
I would then use PyPDF to calculate the number of pages in each, add a blank page if necessary, and merge the rest of the pages. Something like:
blank_page = PDFFileReader('blank.pdf').pages[0]
dest = PDFFileWriter()
for source in sources:
PDF = PDFFileReader(source)
dest.addPage(PDF.pages)
if PDF.numPages % 2: #odd number of pages in source
dest.addPage(blank_page)
It appears PyPDF does also have support for merging pages with resize and relocate, so theoretically, it should also work for creating an n-up document, though I see no example code for that.
A:
For putting multiple slides on one page, pdfnup from the PDFjam package is your friend.
For inserting the blank pages, I'm not sure; maybe you can convince pdfjam to do this as well. But can't you just turn off duplexing in the print settings?
| Manipulate and print to PDF files in a script | I have several pdf files of some lecture slides. I want to do the following: print every pdf file to another pdf file in which there are 6 slides per page and then merge all the resulting files to one big file while making sure that every original file starts on an odd page number (Edit: obviously, it will be printed in duplex) (possibly adding blank pages when necessary).
Is that possible?
Edit: For those interested, this is for printing a LOT of course material for an exam... And I need to do this for a lot of courses.
| [
"If it were me, I would use PDFjam or a similar tool to perform the 6-up on each of the source documents.\nI would then use PyPDF to calculate the number of pages in each, add a blank page if necessary, and merge the rest of the pages. Something like:\nblank_page = PDFFileReader('blank.pdf').pages[0]\ndest = PDFFil... | [
3,
1
] | [] | [] | [
"pdf_generation",
"python"
] | stackoverflow_0003222960_pdf_generation_python.txt |
Q:
Is it possible, and/or advisable to develop Django web applications on OS X (10.6.4 and 10.5.8) using Python 2.6.5 64-bit? Why?
I'm trying to decide on which architecture to choose for developing Django 1.0.x through Django 1.2.1. I've managed to get MySQL, MySQLdb, PIL, and Python 2.65 installed on Snow Leopard using x86 64-bit builds, but I'm curious as to whether or not there is a definitive answer to this question at the moment, and if so, why?
Thank you!
Michaux
A:
Of course it's possible. Advisable? You didn't mention httpd and mod_wsgi, or some other WSGI container. Get one installed and it should be fine.
A:
It certainly is possible: I do it every day.
Some tips:
use virtualenv to sandbox your python packages between projects.
use mod_passenger (via Passenger.prefpane) to make VirtualHosts easier to deal with.
You may need to fiddle a bit harder with things if you run stuff under mod_python, as I recall having to work hard to get a version compiled that worked with the version of apache that is installed by default, and the python I was using.
| Is it possible, and/or advisable to develop Django web applications on OS X (10.6.4 and 10.5.8) using Python 2.6.5 64-bit? Why? | I'm trying to decide on which architecture to choose for developing Django 1.0.x through Django 1.2.1. I've managed to get MySQL, MySQLdb, PIL, and Python 2.65 installed on Snow Leopard using x86 64-bit builds, but I'm curious as to whether or not there is a definitive answer to this question at the moment, and if so, why?
Thank you!
Michaux
| [
"Of course it's possible. Advisable? You didn't mention httpd and mod_wsgi, or some other WSGI container. Get one installed and it should be fine.\n",
"It certainly is possible: I do it every day.\nSome tips: \n\nuse virtualenv to sandbox your python packages between projects.\nuse mod_passenger (via Passenger.pr... | [
1,
1
] | [] | [] | [
"64_bit",
"django",
"python",
"python_2.6",
"x86_64"
] | stackoverflow_0003176695_64_bit_django_python_python_2.6_x86_64.txt |
Q:
Since Django 1.2.1 'prepopulated_fields' won't prepopulate in the admin
Since Django 1.2.1 'prepopulated_fields' won't prepopulate in the admin.
prepopulated_fields = {'slug': ('title',)} doesn't seem to work since uploading to a Django 1.2.1 server after developing on a 1.1.1.
What changed?
I read http://code.djangoproject.com/wiki/NewformsAdminBranch#Changedprepopulate_fromtobedefinedintheAdminclassnotdatabasefieldclasses
but didn't find a way to fix it, my code seems good.
Ideas? Code:
class Data(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.')
class DataAdmin(admin.ModelAdmin):
list_display = ('title', 'user', 'category')
list_filter = ('user', 'category')
ordering = ('title',)
search_fields = ('title',)
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Data, DataAdmin)
A:
It happened to me exactly when upgrading from django 1.1.1 to 1.2.1. It is because the media/admin directory it has changed, before it was something like that: media/admin/js/admin and now is: admin/media/js/admin.
What I did was to change in settings ADMIN_MEDIA_PREFIX = '/media/admin/'
To be sure when you are in your admin page, the one that does not prepopulate, run firebug and check from where that page is trying to fetch the js files. You will see that there is a discrepancy between that location and the actual location of those js files in Django 1.2.1.
A:
Did you read the current documentation for prepulated_fields ?
It would help if you showed your code, but you just place it under your Admin class, it's a pretty straight forward setup.
A:
I can say with certainty that prepopulated_fields still works as indicated in the docs. Your code looks sound, but here are some possible problems I can think of:
Javascript is disabled and/or your admin media links are broken.
You've got a typo somewhere in the names of your fields.
You have something cached in your browser that is preventing the javascript from working correctly.
| Since Django 1.2.1 'prepopulated_fields' won't prepopulate in the admin | Since Django 1.2.1 'prepopulated_fields' won't prepopulate in the admin.
prepopulated_fields = {'slug': ('title',)} doesn't seem to work since uploading to a Django 1.2.1 server after developing on a 1.1.1.
What changed?
I read http://code.djangoproject.com/wiki/NewformsAdminBranch#Changedprepopulate_fromtobedefinedintheAdminclassnotdatabasefieldclasses
but didn't find a way to fix it, my code seems good.
Ideas? Code:
class Data(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.')
class DataAdmin(admin.ModelAdmin):
list_display = ('title', 'user', 'category')
list_filter = ('user', 'category')
ordering = ('title',)
search_fields = ('title',)
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Data, DataAdmin)
| [
"It happened to me exactly when upgrading from django 1.1.1 to 1.2.1. It is because the media/admin directory it has changed, before it was something like that: media/admin/js/admin and now is: admin/media/js/admin.\nWhat I did was to change in settings ADMIN_MEDIA_PREFIX = '/media/admin/'\nTo be sure when you are ... | [
3,
0,
0
] | [] | [] | [
"admin",
"django",
"python"
] | stackoverflow_0003221666_admin_django_python.txt |
Q:
how can I get the ip address of the request in a regested function of python xmlrpc server
I'm writing a simple xmlrpc programe in python. something like the following:
def foo(data):
# I want get the calling client's IP address here... How can I ?
server=SimpleXMLRPCServer.SimpleXMLRPCServer((host, port))
server.register_function(foo)
server.handle_request()
As can be seen in the above, I want to get the client IP address in the registed function "foo", how can I ?
A:
You may do so by subclassing the server (and possibly the handler, too). E.g.:
class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
def process_request(self, request, client_address):
self.client_address = client_address
return SimpleXMLRPCServer.SimpleXMLRPCServer.process_request(
self, request, client_address)
server=SimpleXMLRPCServer.MyXMLRPCServer((host, port))
Now server.client_address gives you the desired data. Note that this direct, short coding only works for the single-threaded case (which you're using anyway by choosing the simple server in your code) -- the need to work with the handler comes in if you want to go multi-threaded.
| how can I get the ip address of the request in a regested function of python xmlrpc server | I'm writing a simple xmlrpc programe in python. something like the following:
def foo(data):
# I want get the calling client's IP address here... How can I ?
server=SimpleXMLRPCServer.SimpleXMLRPCServer((host, port))
server.register_function(foo)
server.handle_request()
As can be seen in the above, I want to get the client IP address in the registed function "foo", how can I ?
| [
"You may do so by subclassing the server (and possibly the handler, too). E.g.:\nclass MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):\n def process_request(self, request, client_address):\n self.client_address = client_address\n return SimpleXMLRPCServer.SimpleXMLRPCServer.process_request(... | [
3
] | [] | [] | [
"call",
"ip",
"python",
"xml_rpc"
] | stackoverflow_0003223373_call_ip_python_xml_rpc.txt |
Q:
Escaping … with BeautifulSoup
I am currrently using BeautifulSoup to scrape some websites, however I have a problem with some specific characters, the code inside UnicodeDammit seems to indicate this (again) are some Microsoft-invented ones.
I'm using the newest version of BeautifulSoup(3.0.8.1) as I am still using python2.5
The following code illustrates my problem:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('...Baby One More Time (Digital Deluxe Version…')
print soup
'...Baby One More Time (Digital Deluxe Version…'
As you can see the problem is the '…'(&hellip) character at the end (which your browser probably escaped correctly). Obviously that's not what I am interested in.
It would be nice to have this characters unicode representation or something.
Even sinmply ignoring it would solve my particular problem.
How can I do this with BeautifulSoup?
A:
Found the solution myself:
soup = BeautifulSoup('...Baby One More Time (Digital Deluxe Version…', convertEntities="html")
A:
MS may have invented it, but … is part of HTML 4: http://www.w3.org/TR/REC-html40/sgml/entities.html
Perhaps your Lib/htmlentitydefs.py is missing or out-of-date, as that's what BeautifulSoup uses to convert entities.
If you look at the Python 2.5 source tree you will clearly see it defined on line 126.
| Escaping … with BeautifulSoup | I am currrently using BeautifulSoup to scrape some websites, however I have a problem with some specific characters, the code inside UnicodeDammit seems to indicate this (again) are some Microsoft-invented ones.
I'm using the newest version of BeautifulSoup(3.0.8.1) as I am still using python2.5
The following code illustrates my problem:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('...Baby One More Time (Digital Deluxe Version…')
print soup
'...Baby One More Time (Digital Deluxe Version…'
As you can see the problem is the '…'(&hellip) character at the end (which your browser probably escaped correctly). Obviously that's not what I am interested in.
It would be nice to have this characters unicode representation or something.
Even sinmply ignoring it would solve my particular problem.
How can I do this with BeautifulSoup?
| [
"Found the solution myself:\nsoup = BeautifulSoup('...Baby One More Time (Digital Deluxe Version…', convertEntities=\"html\")\n\n",
"MS may have invented it, but … is part of HTML 4: http://www.w3.org/TR/REC-html40/sgml/entities.html\nPerhaps your Lib/htmlentitydefs.py is missing or out-of-date, as ... | [
2,
1
] | [] | [] | [
"beautifulsoup",
"escaping",
"python",
"web_scraping"
] | stackoverflow_0003155674_beautifulsoup_escaping_python_web_scraping.txt |
Q:
generating equation png files based on mathematical input
I was wondering what options were available to generate .png based on the kind of input one feeds a graphing calculator.. so
(y^2 + 5x + 3) / ((3x + 3) + 5y + 18)
would return
The only thing I've found so far is texvc in mediawiki, but it seems overkill to get the whole mediawiki for one of it's modules.
A:
The Google Chart API has this function, it takes TeX input and creates an output image.
Another option is jsMath.
A:
There's dvipng that ships with TeX. It has a lot of parameters to twiddle. That's good if you want such control, but bad if you'd like something simpler to use.
A:
An option using Mathematica is:
Export["etc.png",
Rasterize[TraditionalForm[HoldForm[(y^2 + 5 x + 3)/((3 x + 3) + 5 y + 18)]]]]
which produces this image file:
A:
Matplotlib's mathtext engine can turn a subset of TeX into images. See specifically MathtextBackendBitmap for a solution that does not require the other matplotlib backends.
If that doesn't help, matplotlib also has code that calls TeX and dvipng.
Sage could also include some useful code.
A:
As many people cited, TeX might be the most straightforward path to take there -
Searching for python tex yields some possibilities, one of the simpler might be:
http://pypi.python.org/pypi/tex/1.5
It is just a wrapper to call Tex as a subprocess, and have a "dvi" file -- you'd still have to run dvipng (which as @JohnCook puts it, comes with TeX) to get your png file.
The drawback is that you have to set up the full TeX tool chain (not a problem on most Linux distributions).
Anotherway would be to get hold of MathMl rendering libraries - but then, you'd have to assemble the MathML markup for yur equation. Thre is a promising Python MathML to SVGmodule here:
http://sourceforge.net/projects/svgmath/
That should have less librarie dependencies, and depending on your purposes, SVG might be more suitable than .PNG for equations. Else, ask stackoverflow again to go from .svg to .png in Python :-)
A:
There's a site EquationSheet.com that allows you to enter LaTeX and get back the URL of a generated image. Maybe your site could use it.
| generating equation png files based on mathematical input | I was wondering what options were available to generate .png based on the kind of input one feeds a graphing calculator.. so
(y^2 + 5x + 3) / ((3x + 3) + 5y + 18)
would return
The only thing I've found so far is texvc in mediawiki, but it seems overkill to get the whole mediawiki for one of it's modules.
| [
"The Google Chart API has this function, it takes TeX input and creates an output image.\n\n\n\nAnother option is jsMath.\n",
"There's dvipng that ships with TeX. It has a lot of parameters to twiddle. That's good if you want such control, but bad if you'd like something simpler to use.\n",
"An option using Mat... | [
9,
2,
2,
2,
1,
0
] | [] | [] | [
"equation",
"math",
"python"
] | stackoverflow_0003219098_equation_math_python.txt |
Q:
Custom function decorator for views that modified the request path
Could someone show me how i could write a login decorator like @redirect_to_home for my views so that it modifies the request.PATH variable to a new a value like / whenever it is applied to a view.
I've seen people do quite complex stuff with decorators: I'm yet to figure them out thoroughly.
Thanks
A:
The best way to start is to understand the login decorator from the django project ( auth module ):
http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/decorators.py#L33
If you look at the "user_passes_test" function you'll see how to access request object.
A good tutorial about decorators : http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
For some examples of useful decorators see : http://wiki.python.org/moin/PythonDecoratorLibrary
A:
Thanks to Piotr for his helpful examples.
def fake_requested_from_root(fn):
"""
Login decorator which when used on a view modifies the reqquest.path
to fool the template into thibking that the request is coming from the
root page
"""
def decorator(request, **kwargs):
request.path = reverse('home')
return fn(request, **kwargs)
return decorator
| Custom function decorator for views that modified the request path | Could someone show me how i could write a login decorator like @redirect_to_home for my views so that it modifies the request.PATH variable to a new a value like / whenever it is applied to a view.
I've seen people do quite complex stuff with decorators: I'm yet to figure them out thoroughly.
Thanks
| [
"The best way to start is to understand the login decorator from the django project ( auth module ):\nhttp://code.djangoproject.com/browser/django/trunk/django/contrib/auth/decorators.py#L33\nIf you look at the \"user_passes_test\" function you'll see how to access request object.\nA good tutorial about decorators ... | [
3,
1
] | [] | [] | [
"decorator",
"django",
"django_views",
"python"
] | stackoverflow_0003224083_decorator_django_django_views_python.txt |
Q:
How to render HTML form from schema using formencode?
I'm using formencode for validating and submitting forms in my Pylons application. The documentation says that it can be used also for generating forms, but there is no any example. I even found the old topic which says it can be done with
form = HTMLForm(form_template, FormSchema)
form.render()
but for the latest version of formencode it doesn't work.
So, someone please help, how can I generate a HTML using the simplest form Schema?
class LoginForm(formencode.Schema):
allow_extra_fields = True
filter_extra_fields = True
email = formencode.validators.String(not_empty=True)
password = formencode.validators.String(not_empty=True)
A:
Formencode library doesn't generate html for forms.
The code you are referring to uses formencode.htmlform module which no longer exists as it was removed in 1.1 release because, as author said, it was dumb. :)
I think you may have mistaken that kind of functionality with different feature of this lib, namely filling form values after unsuccessful submission which is realised by formencode.htmlfill module.
A:
What zifot said about formencode was spot on. I would only add that you should look at FormAlchemy and Sprox, two libraries built to generate forms from database schemas.
| How to render HTML form from schema using formencode? | I'm using formencode for validating and submitting forms in my Pylons application. The documentation says that it can be used also for generating forms, but there is no any example. I even found the old topic which says it can be done with
form = HTMLForm(form_template, FormSchema)
form.render()
but for the latest version of formencode it doesn't work.
So, someone please help, how can I generate a HTML using the simplest form Schema?
class LoginForm(formencode.Schema):
allow_extra_fields = True
filter_extra_fields = True
email = formencode.validators.String(not_empty=True)
password = formencode.validators.String(not_empty=True)
| [
"Formencode library doesn't generate html for forms. \nThe code you are referring to uses formencode.htmlform module which no longer exists as it was removed in 1.1 release because, as author said, it was dumb. :)\nI think you may have mistaken that kind of functionality with different feature of this lib, namely f... | [
1,
0
] | [] | [] | [
"formencode",
"forms",
"html",
"pylons",
"python"
] | stackoverflow_0003222408_formencode_forms_html_pylons_python.txt |
Q:
Python - Acquire value from dictionary depending on location/index in list
From MySQL query I get data which I put into a dictionary "d":
d = {0: (datetime.timedelta(0,
25200),), 1: (datetime.timedelta(0,
25500),), 2: (datetime.timedelta(0,
25800),), 3: (datetime.timedelta(0,
26100),), 4: (datetime.timedelta(0,
26400),), 5: (datetime.timedelta(0,
26700),)}
I have a list "m" with numbers like:
m = [3, 4, 1, 4, 7, 4]
I'd like to test "m" and if there is number "4", I'd like to receive another list "h" with hours from "d" where index from list "m" would be corresponding with keys from dictionary "d", so: m[1], m[3], m[5] would get me hours assigned to d[1], d[3], d[5] in list "h":
h = [7:05:00, 7:15:00, 7:25:00]
I'll appreciate your input for that...
A:
I'm not entirely sure if this is what you're looking for, but I'll take a shot:
>>> indices = [index for index, i in enumerate(m) if i == 4]
>>> h = [d[i][0] for i in indices]
Then you have to process the timedeltas as you want to.
A:
deltas = [str(d[i][0]) for i, j in enumerate(m) if j == 4]
produces list of delta representation as strings.
A:
So at each index is an n-tuple of timedeltas right? Assuming, from the code, that potentially there could be more than one timedelta at each index.
import datetime
import datetime
d = {0: (datetime.timedelta(0, 25200),), 1: (datetime.timedelta(0, 25500),), 2: (datetime.timedelta(0, 25800),), 3: (datetime.timedelta(0, 26100),), 4: (datetime.timedelta(0, 26400),), 5: (datetime.timedelta(0, 26700),)}
m = [3, 4, 1, 4, 7, 4]
def something(m, d):
h = {}
for index in m:
if index in d and index not in h:
for dt in d[index]:
total = sum([dt.seconds for dt in d[index]])
hours = total / 3600
minutes = (total - (3600 * hours)) / 60
seconds = (total - (3600 * hours) - (60 * minutes))
h[index] = "%d:%02d:%02d" % (hours, minutes, seconds)
return h.values()
print something(m, d) # returns exactly what you asked for
| Python - Acquire value from dictionary depending on location/index in list | From MySQL query I get data which I put into a dictionary "d":
d = {0: (datetime.timedelta(0,
25200),), 1: (datetime.timedelta(0,
25500),), 2: (datetime.timedelta(0,
25800),), 3: (datetime.timedelta(0,
26100),), 4: (datetime.timedelta(0,
26400),), 5: (datetime.timedelta(0,
26700),)}
I have a list "m" with numbers like:
m = [3, 4, 1, 4, 7, 4]
I'd like to test "m" and if there is number "4", I'd like to receive another list "h" with hours from "d" where index from list "m" would be corresponding with keys from dictionary "d", so: m[1], m[3], m[5] would get me hours assigned to d[1], d[3], d[5] in list "h":
h = [7:05:00, 7:15:00, 7:25:00]
I'll appreciate your input for that...
| [
"I'm not entirely sure if this is what you're looking for, but I'll take a shot:\n>>> indices = [index for index, i in enumerate(m) if i == 4]\n>>> h = [d[i][0] for i in indices]\n\nThen you have to process the timedeltas as you want to.\n",
"deltas = [str(d[i][0]) for i, j in enumerate(m) if j == 4]\n\nproduces ... | [
2,
0,
0
] | [
"Are you asking for\ndef hms( td ):\n h = dt.seconds // 3600\n m = dt.seconds%3600 // 60\n s = dt.seconds%60\n return h+td.days*24, m, s\n\n\n[ hms(d[ m[i] ]) for i in m ]\n\n?\n"
] | [
-1
] | [
"dictionary",
"list",
"python"
] | stackoverflow_0000653765_dictionary_list_python.txt |
Q:
Fuzzy runtime search without using database\index
I need to filter stream of text articles by checking every entry for fuzzy matches of predefined string(I am searching for misspelled product names, sometime they have different order of words and extra non letter characters like ":" or ",").
I get excellent results by putting this articles in sphinx index and performing search on it, but unfortunately I get hundreds of articles every second and updating index after getting every article is too slow(and I understand that it's not designed for such task). I need some library which can build in memory index of small ~100kb text and perform fuzzy search on it, does anything like this exist?
A:
This problem is almost identical to Bayesian spam filtering and tools already written for that can just be trained to recognize according to your criteria.
added in response to comment:
So how are you partitioning the stream into bins now? If you already have a corpus of separated articles, just feed that into the classifier. Bayesian classifiers are the way to do fuzzy content matching in context and can classify everything from spam to nucleotides to astronomical spectral categories.
You could use less stochastic methods (e.g. Levenshtein), but at some point you have to describe the difference between hits and misses. The beauty of Bayesian methods, especially if you already have a segregated corpus in hand is that you don't actually need to expressly know how you are classifying.
A:
How about using sqlite fts3 extension?
CREATE VIRTUAL TABLE enrondata1 USING fts3(content TEXT);
(You may create any number of columns -- all of them will be indexed)
After that you insert whatever you like, and can search it without index rebuild -- matching either specific column, or the whole row.
(http://www.sqlite.org/fts3.html)
| Fuzzy runtime search without using database\index | I need to filter stream of text articles by checking every entry for fuzzy matches of predefined string(I am searching for misspelled product names, sometime they have different order of words and extra non letter characters like ":" or ",").
I get excellent results by putting this articles in sphinx index and performing search on it, but unfortunately I get hundreds of articles every second and updating index after getting every article is too slow(and I understand that it's not designed for such task). I need some library which can build in memory index of small ~100kb text and perform fuzzy search on it, does anything like this exist?
| [
"This problem is almost identical to Bayesian spam filtering and tools already written for that can just be trained to recognize according to your criteria.\nadded in response to comment:\nSo how are you partitioning the stream into bins now? If you already have a corpus of separated articles, just feed that into t... | [
1,
1
] | [] | [] | [
"full_text_search",
"fuzzy_search",
"python"
] | stackoverflow_0003224207_full_text_search_fuzzy_search_python.txt |
Q:
what suits the most for creating interface?
i have an application of text to speech convertor and now want to prepare an graphical interface for it.I did whole of the coding involved in python..i want to know which languages can be used for creating the GUI so that i can connect my python code to it easily..can python be used for creating the gui..
as i have no previous experience of creating the gui,would like to take ur suggestion for making the gui which is attractive not just plain thing such as we get using vb or anything else..
looking for your suggestion plz
A:
Yes, a GUI can be created in Python, I recommend wxPython.
A:
You can find a list of GUI programming packages for Python in this page http://wiki.python.org/moin/GuiProgramming
A:
There are many GUI toolkits for python:
http://wiki.python.org/moin/GuiProgramming
I would look at PyQT and wxPython first.
A:
If you're unfamiliar with Python GUI development, I recommend Glade. It's got a fairly intuitive interface, good documentation, and allows you to get things done quickly.
| what suits the most for creating interface? | i have an application of text to speech convertor and now want to prepare an graphical interface for it.I did whole of the coding involved in python..i want to know which languages can be used for creating the GUI so that i can connect my python code to it easily..can python be used for creating the gui..
as i have no previous experience of creating the gui,would like to take ur suggestion for making the gui which is attractive not just plain thing such as we get using vb or anything else..
looking for your suggestion plz
| [
"Yes, a GUI can be created in Python, I recommend wxPython.\n",
"You can find a list of GUI programming packages for Python in this page http://wiki.python.org/moin/GuiProgramming\n",
"There are many GUI toolkits for python:\nhttp://wiki.python.org/moin/GuiProgramming\nI would look at PyQT and wxPython first.\n... | [
0,
0,
0,
0
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0003083697_python_user_interface.txt |
Q:
Python: list of lists anf HTML table help
I'm having trouble appending the values from a list of lists into a html table, for example my list if lists contains:
food_list = [['A','B'], ['Apple','banana'], ['Fruit','Fruit']]
How would i append each value into a correspondong HTML table? So the code looks like:
<table>
<tr><td>A</td><td>Apple</td><td>Fruit</td></tr>
<tr><td>B</td><td>Banana</td><td>Fruit</td></tr>
</table>
the closest i could get was with the code below, but i get a list index out of range error.
print '<table>'
for i in food_list:
print '<tr>'
print '<tr><td>'+i[0]+'</td><td>'+i[1]+'</td><td>'+i[2]+'</td></tr>'
print '</tr>'
print' </table>'
A:
I would do it like this;
# Example data.
raw_rows = [["A", "B"], ["Apple", "Banana"], ["Fruit", "Fruit"]]
# "zips" together several sublists, so it becomes [("A", "Apple", "Fruit"), ...].
rows = zip(*raw_rows)
html = "<table>"
for row in rows:
html += "<tr>"
# Make <tr>-pairs, then join them.
html += "\n".join(map(lambda x: "<td>" + x + "</td>", row))
html += "</tr>"
html += "</table>"
Maybe not the quickest version but it wraps up the rows into tuples, then we can just iterate over them and concatenate them.
A:
I think you're looking for this:
print '<table>'
for i in zip(*food_list):
print '<tr>'
print '<td>'+i[0]+'</td><td>'+i[1]+'</td><td>'+i[2]+'</td>'
print '</tr>'
print' </table>'
A:
The table has two elements, so you would use 0 and 1 as indexes. Here is your example rewritten:
print '<table>'
for i in food_list:
print '<tr>'
print '<tr><td>'+i[0]+'</td><td>'+i[1]+'</td></th>'
print '</tr>'
print' </table>'
| Python: list of lists anf HTML table help | I'm having trouble appending the values from a list of lists into a html table, for example my list if lists contains:
food_list = [['A','B'], ['Apple','banana'], ['Fruit','Fruit']]
How would i append each value into a correspondong HTML table? So the code looks like:
<table>
<tr><td>A</td><td>Apple</td><td>Fruit</td></tr>
<tr><td>B</td><td>Banana</td><td>Fruit</td></tr>
</table>
the closest i could get was with the code below, but i get a list index out of range error.
print '<table>'
for i in food_list:
print '<tr>'
print '<tr><td>'+i[0]+'</td><td>'+i[1]+'</td><td>'+i[2]+'</td></tr>'
print '</tr>'
print' </table>'
| [
"I would do it like this;\n# Example data.\nraw_rows = [[\"A\", \"B\"], [\"Apple\", \"Banana\"], [\"Fruit\", \"Fruit\"]]\n# \"zips\" together several sublists, so it becomes [(\"A\", \"Apple\", \"Fruit\"), ...].\nrows = zip(*raw_rows) \n\nhtml = \"<table>\"\nfor row in rows:\n html += \"<tr>\"\n # Make <tr>-pai... | [
3,
3,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0003224657_html_python.txt |
Q:
Python/Django or C#/ASP.NET for web development?
I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us.
Thank you.
A:
Much as I love Python (and, that's a LOT!-), if you're highly skilled at C# and, as you say, "have no experience on Python", your code will be more scalable and suitable (for the next several months, at least) if you stick with what you know best. For a hypothetical developer extremely skilled at both platforms, scalability would essentially be a wash, and Python would enhance that developer's productivity; but getting really good at any technology takes some months of practice, it doesn't "just happen" magically.
So, unless you're trying to broaden your range of skills and job opportunities, or enhance your productivity, but rather are specifically, strictly focused on the scalability of the web apps you're coding right now, I have, in good conscience, to recommend you stick with C#. You should also try IronPython (and get the great "IronPython in Action" book from Mannings -- bias alert, I'm friends with the author and was a tech reviewer of that book;-) for all sorts of non-production supporting code, to get a taste of it and the incredible productivity boost it can give you... but, to deliver best value to your clients or employers, stick with what you REALLY master, C#, for any scalability-critical work you deliver to them!
A:
Almost all the well known frameworks and languages can scale.
It doesn't really matter which one you use. Its about how well you structure the code that matters most.
On a personal level it is always good to know more than one language.
But, you can create perfectly scalable Python, PHP, .NET applications. The quality of the code is the first place scalability will fall down not the language.
A:
Derek had a great answer, so I won't repeat it.
I would like to make one observation, however. While for the most part, the language choice isn't really a big deal these days, if you really need high performance and scalability, the dynamic nature of python might come back to haunt you. For all the benefits that a dynamic language can provide, those benefits do come at the cost of additional overhead. The .NET platform offers fully compiled languages, and offers a variety of ways to tune the performance of compiled code (including ngen support, so you can create natively compiled modules that do not need to be JITted.)
I do not know if the performance edge .NET compiled languages have over Python is really enough for your particular application, but given that you are already a .NET developer, going with ASP.NET might be the best option.
A:
There is a added scalability cost with going with .NET over Python, the cost of Windows Server licenses (at the minimum, you usually add SQL Server to that as well).
| Python/Django or C#/ASP.NET for web development? | I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us.
Thank you.
| [
"Much as I love Python (and, that's a LOT!-), if you're highly skilled at C# and, as you say, \"have no experience on Python\", your code will be more scalable and suitable (for the next several months, at least) if you stick with what you know best. For a hypothetical developer extremely skilled at both platforms,... | [
16,
14,
3,
1
] | [] | [] | [
"asp.net",
"django",
"python",
"scalability"
] | stackoverflow_0001031438_asp.net_django_python_scalability.txt |
Q:
Python: Sanitize a string for unicode?
Possible Duplicate:
Python UnicodeDecodeError - Am I misunderstanding encode?
I have a string that I'm trying to make safe for the unicode() function:
>>> s = " foo “bar bar ” weasel"
>>> s.encode('utf-8', 'ignore')
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
s.encode('utf-8', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 5: ordinal not in range(128)
>>> unicode(s)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
unicode(s)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 5: ordinal not in range(128)
I'm mostly flailing around here. What do I need to do to remove the unsafe characters from the string?
Somewhat related to this question, although I was unable to solve my problem from it.
This also fails:
>>> s
' foo \x93bar bar \x94 weasel'
>>> s.decode('utf-8')
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
s.decode('utf-8')
File "C:\Python25\254\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x93 in position 5: unexpected code byte
A:
Good question. Encoding issues are tricky. Let's start with "I have a string." Strings in Python 2 aren't really "strings," they're byte arrays. So your string, where did it come from and what encoding is it in? Your example shows curly quotes in the literal, and I'm not even sure how you did that. I try to paste it into a Python interpreter, or type it on OS X with Option-[, and it doesn't come through.
Looking at your second example though, you have a character of hex 93. That can't be UTF-8, because in UTF-8, any byte higher than 127 is part of a multibyte sequence. So I'm guessing it's supposed to be Latin-1. The problem is, x93 isn't a character in the Latin-1 character set. There's this "invalid" range in Latin-1 from x7f to x9f that's considered illegal. However, Microsoft saw that unused range and decided to put "curly quotes" in there. In doing so they created this similar encoding called "windows-1252", which is like Latin-1 with stuff in that invalid range.
So, let's assume it is windows-1252. What now? String.decode converts bytes into Unicode, so that's the one you want. Your second example was on the right track, but it failed because the string wasn't UTF-8. Try:
>>> uni = 'foo \x93bar bar\x94 weasel'.decode("windows-1252")
u'foo \u201cbar bar\u201d weasel'
>>> print uni
foo “bar bar” weasel
>>> type(uni)
<type 'unicode'>
That's correct, because opening curly quote is Unicode U+201C. Now that you have Unicode, you can serialize it to bytes in any encoding you choose (if you need to pass it across the wire) or just keep it as Unicode if it's staying within Python. If you want to convert to UTF-8, use the oppose function, string.encode.
>>> uni.encode("utf-8")
'foo \xe2\x80\x9cbar bar \xe2\x80\x9d weasel'
Curly quotes take 3 bytes to encode in UTF-8. You could use UTF-16 and they'd only be two bytes. You can't encode as ASCII or Latin-1 though, because those don't have curly quotes.
A:
EDIT. Looks like your string is encoded in such a way that “ (LEFT DOUBLE QUOTATION MARK) becomes \x93 and ” (RIGHT DOUBLE QUOTATION MARK) becomes \x94. There is a number of codepages with such a mapping, CP1250 is one of them, so you may use this:
s = s.decode('cp1250')
For all the codepages which map “ to \x93 see here (all of them also map ” to \x94, which can be verified here).
| Python: Sanitize a string for unicode? |
Possible Duplicate:
Python UnicodeDecodeError - Am I misunderstanding encode?
I have a string that I'm trying to make safe for the unicode() function:
>>> s = " foo “bar bar ” weasel"
>>> s.encode('utf-8', 'ignore')
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
s.encode('utf-8', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 5: ordinal not in range(128)
>>> unicode(s)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
unicode(s)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 5: ordinal not in range(128)
I'm mostly flailing around here. What do I need to do to remove the unsafe characters from the string?
Somewhat related to this question, although I was unable to solve my problem from it.
This also fails:
>>> s
' foo \x93bar bar \x94 weasel'
>>> s.decode('utf-8')
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
s.decode('utf-8')
File "C:\Python25\254\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x93 in position 5: unexpected code byte
| [
"Good question. Encoding issues are tricky. Let's start with \"I have a string.\" Strings in Python 2 aren't really \"strings,\" they're byte arrays. So your string, where did it come from and what encoding is it in? Your example shows curly quotes in the literal, and I'm not even sure how you did that. I try to pa... | [
41,
5
] | [] | [] | [
"character_encoding",
"python",
"unicode"
] | stackoverflow_0003224427_character_encoding_python_unicode.txt |
Q:
Learning Python, is there a better way to write this?
I am learning Python (2.7) and to test what I have learned so far I wrote a temperature converter that converts Celsius to Fahrenheit and I wanted to know if my code could be written better to be faster or something more Pythonic. And could someone tell me if there is an actual name for the if __name__ == '__main__': main() (out of curiosity)?
from sys import argv, exit # import argv and exit functions
def to_f(c): # Convert celsius to ferinheight
temp = (c * 9/5) + 32
return temp
def to_c(f): # Convert ferinheight to celsius
temp = (f - 32) * 5/9
return temp
def main():
args = argv[1:] # Creates an argument list omitting the omitting the [0] element
if len(argv) < 2: exit(1) # If less than two arguments
if args[0] == '-f': # If the first argument is -f
print args[1], 'ferinheight is', str(to_c(int(args[1]))), 'celsius'
elif args[0] == '-c': # If the first argument is -c
print args[1], 'celsius is', str(to_f(int(args[1]))), 'ferinheight'
else: exit(1)
if __name__ == '__main__':
main()
http://pastebin.com/rjeNikDt
A:
import sys
def to_f(c): # Convert celsius to fahrenheit
return (c * 9/5) + 32
def to_c(f): # Convert fahrenheit to celsius
return (f - 32) * 5/9
def convert(args):
if len(args) < 2:
return 1 # If less than two arguments
t = args[1]
if args[0] == '-f': # If the first argument is -f
print "%s Fahrenheit is %s Celsius" % (t, to_c(int(t)))
return 0
elif args[0] == '-c': # If the first argument is -c
print "%s Celsius is %s Fahrenheit" % (t, to_f(int(t)))
return 0
else:
return 1
if __name__ == '__main__':
sys.exit(convert(sys.argv[1:]))
What I did:
Changed the name of main() to convert()
Pass the arguments to convert() explicitly
Change calls to exit() to returns, and call exit() in the main clause.
You were checking argv for length 2, when you should have been checking args.
The to_c and to_f functions don't need a temp variable, just return the expression.
Although others are right that you can just put the main() function at the top level, it is good form to use the if __name__ style, so that you could import this module and use the functions in other code.
String formatting is nicer than intermixing strings and values in the print statement.
args[1] appears enough that I assigned it to t for brevity.
I prefer importing sys, and using sys.argv, for example.
I always put dependent clauses on new lines, never if blah: doit()
Fix the spelling of Fahrenheit
A:
The if __name__ == '__main__': pattern is for when you're writing a module intended to be used by other code, but you want some testing code in the module.
If you run the module directly, it runs the stuff in that if block. If it's imported from somewhere else, it doesn't.
So, I would recommend keeping that if __name__ == '__main__': block because you can do something like:
from temp_conv import c_from_f
print c_from_f(73)
later in another piece of code if you named this temp_conv.py.
A:
A couple of improvements on Ned's answer.
In Python2.7 / still truncates the result by default, so you need to import division from __future__ otherwise (c * 9/5) + 32 always rounds down which leads to reduced accuracy.
eg if 36C is 96.8F it's better to return 97 than 96
You don't need a return statement in convert. By default None is returned. If there is a problem you can raise an exception
Also using "".format() is preferred nowdays
A further improvement would be to use optparse or similar to process the command arguments, but may be overkill for such a simple program
from __future__ import division
import sys
def to_f(c): # Convert celsius to fahrenheit
return (c * 9/5) + 32
def to_c(f): # Convert fahrenheit to celsius
return (f - 32) * 5/9
def convert(args):
if len(args) != 2:
raise RuntimeError("List of two elememts required")
t = int(args[1])
if args[0] == '-f': # If the first argument is -f
print "{0} Fahrenheit is {1} Celsius".format(t, round(to_c(t)))
elif args[0] == '-c': # If the first argument is -c
print "{0} Celsius is {1} Fahrenheit".format(t, round(to_f(t)))
else:
raise RuntimeError("First element should be -c or -f")
if __name__ == '__main__':
sys.exit(convert(sys.argv[1:]))
A:
import sys
from getopt import getopt, GetoptError
def to_f(c):
return (c*9/5) + 32
def to_c(f):
return (f-32) * 5/9
def usage():
print "usage:\n\tconvert [-f|-c] temp"
def convert(args):
opts = None
try:
opts, args = getopt(args, "f:c:")
except GetoptError as e:
print e
if not opts or len(opts) != 1:
usage()
return 1
converters = {
'-f': (to_c, '{0} Fahrenheit is {1} Celsius'),
'-c': (to_f, '{0} Celsius is {1} Fahrenheit')
}
# opts will be [('-f', '123')] or [('-c', '123')]
scale, temp = opts[0][0], int(opts[0][1])
converter = converters[scale][0]
output = converters[scale][1]
print output.format(temp, converter(temp))
return 0
if __name__ == '__main__':
sys.exit(convert(sys.argv[1:]))
I used getopt to clean up your argument and error handling. I also consolidated the logic that acts upon the given option, once that option has been determined. Getopt is a very powerful option parser and I think it's worth learning if you are going to be writing these sorts of programs often.
| Learning Python, is there a better way to write this? | I am learning Python (2.7) and to test what I have learned so far I wrote a temperature converter that converts Celsius to Fahrenheit and I wanted to know if my code could be written better to be faster or something more Pythonic. And could someone tell me if there is an actual name for the if __name__ == '__main__': main() (out of curiosity)?
from sys import argv, exit # import argv and exit functions
def to_f(c): # Convert celsius to ferinheight
temp = (c * 9/5) + 32
return temp
def to_c(f): # Convert ferinheight to celsius
temp = (f - 32) * 5/9
return temp
def main():
args = argv[1:] # Creates an argument list omitting the omitting the [0] element
if len(argv) < 2: exit(1) # If less than two arguments
if args[0] == '-f': # If the first argument is -f
print args[1], 'ferinheight is', str(to_c(int(args[1]))), 'celsius'
elif args[0] == '-c': # If the first argument is -c
print args[1], 'celsius is', str(to_f(int(args[1]))), 'ferinheight'
else: exit(1)
if __name__ == '__main__':
main()
http://pastebin.com/rjeNikDt
| [
"import sys\n\ndef to_f(c): # Convert celsius to fahrenheit\n return (c * 9/5) + 32\n\ndef to_c(f): # Convert fahrenheit to celsius\n return (f - 32) * 5/9\n\ndef convert(args):\n if len(args) < 2:\n return 1 # If less than two arguments\n t = args[1]\n if args[0] == '-f': # If the first argum... | [
11,
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003224412_python.txt |
Q:
Detect data type from XML string using python
I have some XML tagged string as follows.
<Processor>AMD Athlon(tm) 64 X2 Dual Core Processor 4400+ 2.31 GHz</Processor>
<ClockSpeed>2.31</ClockSpeed>
<NumberOfCores>2</NumberOfCores>
<InstalledMemory>2.00</InstalledMemory>
<OperatingSystem>Windows 7 Professional</OperatingSystem>
How can I detect the data type automatically using python?
For example, "AMD Athlon(tm) 64 X2 Dual Core Processor 4400+ 2.31 GHz" -> string, "2.31" -> float, and on.
I need this functionality as I need to make SQLite Table out of the XML data something like
CREATE table ABC (Processor string, ClockSpeed float ... )
A:
One possibility is to try various types in precise sequence, defaulting to str if none of those work. E.g.:
def what_type(s, possible_types=((int, [0]), (float, ()))):
for t, xargs in possible_types:
try: t(s, *xargs)
except ValueError: pass
else: return t
return str
This is particularly advisable, of course, when you to use want exactly the same syntax conventions as Python -- e.g., accept '0x7e' as int as well as '126', and so on. If you need different syntax conventions, then you should instead perform parsing on string s, whether via REs or by other means.
A:
Depending on the kinds of formats you expect, you could use regexes to detect floats and ints, and then assume that anything which can't be parsed into a number is a string, like so:
import re
FLOAT_RE = re.compile(r'^(\d+\.\d*|\d*\.\d+)$')
INT_RE = re.compile(r'^\d+$')
# ... code to get xml value into a variable ...
if FLOAT_RE.match(xml_value):
value_type = 'float'
elif INT_RE.match(xml_value):
value_type = 'int'
else:
value_type = 'string'
This is just a very basic stab at it - there are more complex formats for expressing numbers that are possible; if you think you might expect some of the more complex formats you'd have to expand this to make it work properly in all cases.
A:
BeautifulSoup is a good HTML/XML parser:
http://www.crummy.com/software/BeautifulSoup/
I'm not entirely sure if it can convert data by type given an xsd/xsl, but it can detect encoding, so there might be a start.
| Detect data type from XML string using python | I have some XML tagged string as follows.
<Processor>AMD Athlon(tm) 64 X2 Dual Core Processor 4400+ 2.31 GHz</Processor>
<ClockSpeed>2.31</ClockSpeed>
<NumberOfCores>2</NumberOfCores>
<InstalledMemory>2.00</InstalledMemory>
<OperatingSystem>Windows 7 Professional</OperatingSystem>
How can I detect the data type automatically using python?
For example, "AMD Athlon(tm) 64 X2 Dual Core Processor 4400+ 2.31 GHz" -> string, "2.31" -> float, and on.
I need this functionality as I need to make SQLite Table out of the XML data something like
CREATE table ABC (Processor string, ClockSpeed float ... )
| [
"One possibility is to try various types in precise sequence, defaulting to str if none of those work. E.g.:\ndef what_type(s, possible_types=((int, [0]), (float, ()))):\n for t, xargs in possible_types:\n try: t(s, *xargs)\n except ValueError: pass\n else: return t\n return str\n\nThis ... | [
3,
2,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003224969_python_sqlite.txt |
Q:
Change the gcc version that distutils uses
I'm on Snow Leopard, and want distutils to use gcc 4.0 and not 4.2, can anyone tell me how to make it do that? I've tried changing the /usr/bin/g* symlinks, and setting the C* environment vars -- but to no avail. Any thoughts?
A:
Did you try python setup.py build --compiler=gcc? it is described in the docs.
EDIT:
Also, this discussion looks very similar the present one. distutils.core appears to have the functions to specify the compiler and platform. distutils.ccompiler.get_compiler(osname, platform) or distutils.ccompiler.new_compiler(platform, compiler, verbose, dry_run, force) should work.
| Change the gcc version that distutils uses | I'm on Snow Leopard, and want distutils to use gcc 4.0 and not 4.2, can anyone tell me how to make it do that? I've tried changing the /usr/bin/g* symlinks, and setting the C* environment vars -- but to no avail. Any thoughts?
| [
"Did you try python setup.py build --compiler=gcc? it is described in the docs.\nEDIT:\nAlso, this discussion looks very similar the present one. distutils.core appears to have the functions to specify the compiler and platform. distutils.ccompiler.get_compiler(osname, platform) or distutils.ccompiler.new_compile... | [
0
] | [] | [] | [
"distutils",
"gcc",
"osx_snow_leopard",
"python"
] | stackoverflow_0003224934_distutils_gcc_osx_snow_leopard_python.txt |
Q:
Removing HTML tags from a unicode string in Python
I have a strong that I scraped from an XML file and It contains some HTML formatting tags
(<b>, <i>, etc)
Is there a quick and easy way to remove all of these tags from the text?
I tried
str = str.replace("<b>","")
and applied it several times to other tags, but that doesn't work
A:
Using lxml.html:
lxml.html.fromstring(s).text_content()
This strips all tags and converts all entities to their corresponding characters.
A:
Answer depends on your exact needs. You might have a look at regular expressions. But I would advise you to use http://www.crummy.com/software/BeautifulSoup/ if you want to clean up bad xml or html.
A:
Here's how to use the BeautifulSoup module to replace only some tags, leaving the rest of the HTML alone:
from BeautifulSoup import BeautifulSoup, NavigableString
def strip_tags(html, invalid_tags):
soup = BeautifulSoup(html)
for tag in soup.findAll(True):
if tag.name in invalid_tags:
s = ""
for c in tag.contents:
if type(c) != NavigableString:
c = strip_tags(unicode(c), invalid_tags)
s += unicode(c)
tag.replaceWith(s)
return soup
html = "<p>Good, <b>bad</b>, and <i>ug<b>l</b><u>y</u></i></p>"
invalid_tags = ['b', 'i', 'u']
print strip_tags(html, invalid_tags)
Result:
<p>Good, bad, and ugly</p>
| Removing HTML tags from a unicode string in Python | I have a strong that I scraped from an XML file and It contains some HTML formatting tags
(<b>, <i>, etc)
Is there a quick and easy way to remove all of these tags from the text?
I tried
str = str.replace("<b>","")
and applied it several times to other tags, but that doesn't work
| [
"Using lxml.html:\nlxml.html.fromstring(s).text_content()\n\nThis strips all tags and converts all entities to their corresponding characters.\n",
"Answer depends on your exact needs. You might have a look at regular expressions. But I would advise you to use http://www.crummy.com/software/BeautifulSoup/ if you w... | [
6,
1,
1
] | [] | [] | [
"html",
"python",
"replace",
"string",
"unicode"
] | stackoverflow_0003224358_html_python_replace_string_unicode.txt |
Q:
Jinja2: Looking for a View-Helper
I'am new to the Jinja2 template engine. Is there something like the view-helpers from Zend Framework? Can i create simple functions and reuse them all over all my template-files?
Something like this?
#somewhere in my python code:
def nice_demo_function(message):
""""return a simple message"""
return message
So i can to use that:
<!-- now in my template-file -->
{% nice_demo_function('yes, this works great!') %}
A:
There are a number of ways you can expose helper functions to your templates. You could define them using macros, and then import them into templates that use them. You could add functions to the globals attribute of your Template objects, or pass them to the render() method. You could subclass Template to do the same without having to repeat yourself each time. If you want to get really fancy, you could look into writing extensions as well (but you probably don't need to go that deep).
A:
At some point you will have created a Jinja2 environment. The environment has an attribute on it called filters which is a dict that maps names to functions. So what you want to do is:
def my_helper(value):
return "-~*#--- %s ---#*~-" % value
env = Jinja2.Environment(...)
env.filters['my_helper'] = my_helper
Now in your template you can do:
<p>The winner is {{ winner | my_helper }}</p>
And your function will be called with the value of the variable, in this case winner. If you are using Pylons, this all happens in config/environment.py.
| Jinja2: Looking for a View-Helper | I'am new to the Jinja2 template engine. Is there something like the view-helpers from Zend Framework? Can i create simple functions and reuse them all over all my template-files?
Something like this?
#somewhere in my python code:
def nice_demo_function(message):
""""return a simple message"""
return message
So i can to use that:
<!-- now in my template-file -->
{% nice_demo_function('yes, this works great!') %}
| [
"There are a number of ways you can expose helper functions to your templates. You could define them using macros, and then import them into templates that use them. You could add functions to the globals attribute of your Template objects, or pass them to the render() method. You could subclass Template to do t... | [
3,
2
] | [] | [] | [
"jinja2",
"python"
] | stackoverflow_0003223920_jinja2_python.txt |
Q:
Matplotlib: plot multiple graphs using same figure, without them overlapping
I have a class which I use to plot things then save them to a file. Here's a simplified version of it:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Test():
def __init__(self, x, y, filename):
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, y, 'D', color='red')
ax.set_xbound(-5,5)
ax.set_ybound(-5,5)
plt.savefig('%s.png' % filename)
test1 = Test(1,2, 'test1')
test2 = Test(2,4, 'test2')
Here are the results:
test1
test2
The problem is that the test2 image also has the point from test1. The graphs are generated dynamically in a loop so I can't hardcode the figure number.
I could make a counter and pass it to the class constructor but I was wondering if there's a more elegant way to do this. I tried deleting the test1 object but that didn't do anything.
A:
You could use the figure's clf method to clear the figure after you're done with one. Also, pyplot.clf will clear the current figure.
Alternatively, if you just want a new figure then call pyplot.figure without an explicit num argument -- it will autoincrement, so you don't need to keep a counter.
| Matplotlib: plot multiple graphs using same figure, without them overlapping | I have a class which I use to plot things then save them to a file. Here's a simplified version of it:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Test():
def __init__(self, x, y, filename):
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, y, 'D', color='red')
ax.set_xbound(-5,5)
ax.set_ybound(-5,5)
plt.savefig('%s.png' % filename)
test1 = Test(1,2, 'test1')
test2 = Test(2,4, 'test2')
Here are the results:
test1
test2
The problem is that the test2 image also has the point from test1. The graphs are generated dynamically in a loop so I can't hardcode the figure number.
I could make a counter and pass it to the class constructor but I was wondering if there's a more elegant way to do this. I tried deleting the test1 object but that didn't do anything.
| [
"You could use the figure's clf method to clear the figure after you're done with one. Also, pyplot.clf will clear the current figure.\nAlternatively, if you just want a new figure then call pyplot.figure without an explicit num argument -- it will autoincrement, so you don't need to keep a counter.\n"
] | [
10
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003225138_matplotlib_python.txt |
Q:
Which web technology to learn for an experienced C++ developer?
Friends,
I've got some exp in c++ and now kind of starting my way to J2EE (to survive:))). Meanwhile, I've got a plan to venture in to a web portal my own. But with very little experience in web technology, I'd need to start from scratch. I'm little confused on which way to go and I'm here.
PHP, Python or JSP, considering the fact that, anyway I've got to learn J2EE at my work.
Would that be worth to learn PHP or Python to develop a portal which I expect to get 80-100K
hits per day "IF" everything goes well OR jsp would be sufficient?
Many thanks
A:
Before learning either of these, spend some real time and learn HTML and CSS in depth. Also learn Javascript and JQuery (or your favorite client side library). The O'Reilly books on the topic are pretty much all good IMO.
I say that because I think that you'll find that for most modern web sites, a lot of richness is moving to the client side, and away from the server side. Under this model, your code in PHP or JSP is probably going to look pretty similar (ie, fetch data from the database and serve it to your view or into JSON for the client to consume).
A:
Considering you're used to c++, should look at aspx and c# - probably closer to your current experience.
That said, PHP is a doddle, so it shouldn't present any challenges. Bear in mind that if you want to get the most from the language, you absolutely have to learn a little bit about configuring apache, and frameworks (cake, codeigniter, zend etc).
A:
All the server-side technologies you list are "sufficient" for the volume of traffic you expect, if you design the site well from a performance and scaling viewpoint -- and so do many others you haven't mentioned, such as other Java-based approaches, C# ones, and (last but not least) Ruby (probably with Rails, though, like the other languages, it has several frameworks for you to choose from).
As most everybody said, the client-side considerations are sharper -- unless you want to try a "server-side generator of client-side code" like gwt (I'm told the latter works well, but personally I'm always wary of code generators, esp. using a code generator w/o understanding of the "code" it makes for you, which in this case is HTML, CSS, and Javascript with its own framework). Except for GWT and similar approaches (if that's your chosen poison), really learning HTML, CSS and Javascript is really a must -- and then you get to choose among many, many frameworks again (jQuery, Dojo, closure, etc, etc).
For performance issues, you really want to study Steve Souders' site (and books, etc) -- Steve was a server-side guru until measurement showed him the bottleneck was really client-side, and then he turned himself into the client-side performance wizard;-). But to get the most out of the books you'll need understanding of HTTP, HTML, etc, etc, to start with;-).
A:
Hit's per day isn't a really useful metric for estimating performance. You really need to be concerned with the peak load and the acceptable response time.
80-100k hits per day is an average of about 1 hit per second. The hits are not going to be evenly spread out, so for normal traffic you might expect a peak load of 10 hits per second.
If you are going to promote the site with newsletters or commercials, expect to peack at 100's of hits per second.
If you selling $1 air tickets, expect to peak at 1000's of hits per second.
Now the language you choose for the site isn't nearly as important as your choice of database (not necessarily relational) and the way you store the data in the database.
Scaling up frontends is relatively easy, so having really fast efficient HTML generation shouldn't be a primary concern. Pick a platform that is going to be efficient for development time.
A:
I expect this question to be closed as being subjective. But, I'll put in my 2 cents.
JSP would likely dovetail well with J2EE. (I've heard that it can be a bit rigid, but I have no experience to provide any insight on the matter.)
PHP is a good candidate, because it's popular. You can find a lot of info on the web.
Python isn't as popular for webdev, so finding examples won't be as easy.
I also second Dave Markle's opinion. If you want to learn webdev, HTML, CSS and JavaScript will be crucial as well. You may never want to be a front-end developer, but you can't get away from dealing with those technologies at some point.
A:
There are many options.
Since you already know (and is learning about) Java, one option is to use GWT for both server and client. This can help you in that you do not need to learn another language (JS/HTML/Python/PHP etc). If your portal is going to be big, using Java can help you organise the application better - usually JS/HTML based applications are not very suitable for proper organisation, even if you use good JS Libraries like jQuery or YUI. Having a good organisation can help a lot - during updation and modification later.
If your planned venture is a single/two person venture or if it is time bound - where time to market is everything - then I would not suggest the earlier approach - especially if your server side part is expected to be big.
Java is a slow language to write code in. A project which you will take say 6 months to write in Python will take you close to 1 year + in Java. In such a scneario, I would prefer Python - it is a proper language - unlike PHP, and you create code with good organisation there too - albeit a little less organised than using Java.
Please note that if your client side code is much more complex than your server side code, then going with GWT will do you no harm. But if your server side code is very complex compared to the client side, then I would suggest Python.
Another point is to use existing Web Frameworks to ease your work. For Python, Django is an excellent choice. This itself will decrease your work time by 50% or more, while making your code much more secure and scalable.
A:
It really isn't that similar to C++, but I would recommend PHP. You really can't expect a server-side scripting language to be similar to a compiled language like C++. Personally, I find PHP to be an ugly, messy looking language, but once you get into it, it's very rewarding. Other languages have too many drawbacks. ASP.Net is too Microsoft-centric, Python and Ruby on Rails are too obscure, and are also non-curly bracket languages, meaning it will require a lot of adjustment to change to them. Hope this helps.
| Which web technology to learn for an experienced C++ developer? | Friends,
I've got some exp in c++ and now kind of starting my way to J2EE (to survive:))). Meanwhile, I've got a plan to venture in to a web portal my own. But with very little experience in web technology, I'd need to start from scratch. I'm little confused on which way to go and I'm here.
PHP, Python or JSP, considering the fact that, anyway I've got to learn J2EE at my work.
Would that be worth to learn PHP or Python to develop a portal which I expect to get 80-100K
hits per day "IF" everything goes well OR jsp would be sufficient?
Many thanks
| [
"Before learning either of these, spend some real time and learn HTML and CSS in depth. Also learn Javascript and JQuery (or your favorite client side library). The O'Reilly books on the topic are pretty much all good IMO.\nI say that because I think that you'll find that for most modern web sites, a lot of richn... | [
13,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"jsp",
"php",
"python"
] | stackoverflow_0003223557_jsp_php_python.txt |
Q:
Pango error after a minute of running
I have the following python modules. Sorry if the code is ugly. This is my first python GUI app and I'm fairly new to python as well. It's some sort of a count down timer with a todo list. It works kinda well except that after two minutes after running the program, it crashes with the following error:
Pango:ERROR:/build/buildd/pango1.0-1.28.0/pango/pango-layout.c:3739:pango_layout_check_lines: assertion failed: (!layout->log_attrs)
I have absolutely no idea what that even means. One I'm confused about is that it works after the first minute, ie. the timer label counts down ok but on the next minute, it crashes immediately.
After googling a bit, I think the issue might be related to multithreading? Any ideas?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Fri Jul 9 17:00:08 2010
import wx
import settimer
# begin wxGlade: extracode
# end wxGlade
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.todo1 = wx.TextCtrl(self, -1, "")
self.timer_label1 = wx.StaticText(self, -1, "00:00")
self.set_timer1 = wx.Button(self, -1, "Set Timer")
self.todo2 = wx.TextCtrl(self, -1, "")
self.timer_label2 = wx.StaticText(self, -1, "00:00")
self.set_timer2 = wx.Button(self, -1, "Set Timer")
self.todo3 = wx.TextCtrl(self, -1, "")
self.timer_label3 = wx.StaticText(self, -1, "00:00")
self.set_timer3 = wx.Button(self, -1, "Set Timer")
self.todo4 = wx.TextCtrl(self, -1, "")
self.timer_label4 = wx.StaticText(self, -1, "00:00")
self.set_timer4 = wx.Button(self, -1, "Set Timer")
self.todo5 = wx.TextCtrl(self, -1, "")
self.timer_label5 = wx.StaticText(self, -1, "00:00")
self.set_timer5 = wx.Button(self, -1, "Set Timer")
self.hours = 0
self.minutes = 0
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_BUTTON, self.on_set1, self.set_timer1)
self.Bind(wx.EVT_BUTTON, self.on_set2, self.set_timer2)
self.Bind(wx.EVT_BUTTON, self.on_set3, self.set_timer3)
self.Bind(wx.EVT_BUTTON, self.on_set4, self.set_timer4)
self.Bind(wx.EVT_BUTTON, self.on_set5, self.set_timer5)
# end wxGlade
def __set_properties(self):
# begin wxGlade: MyFrame.__set_properties
self.SetTitle("Track Work")
self.todo1.SetMinSize((300, 25))
self.timer_label1.SetMinSize((100, 30))
self.timer_label1.SetFont(wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set_timer1.SetMinSize((85, 27))
self.todo2.SetMinSize((300, 25))
self.timer_label2.SetMinSize((100, 30))
self.timer_label2.SetFont(wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set_timer2.SetMinSize((85, 27))
self.todo3.SetMinSize((300, 25))
self.timer_label3.SetMinSize((100, 30))
self.timer_label3.SetFont(wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set_timer3.SetMinSize((85, 27))
self.todo4.SetMinSize((300, 25))
self.timer_label4.SetMinSize((100, 30))
self.timer_label4.SetFont(wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set_timer4.SetMinSize((85, 27))
self.todo5.SetMinSize((300, 25))
self.timer_label5.SetMinSize((100, 30))
self.timer_label5.SetFont(wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set_timer5.SetMinSize((85, 27))
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyFrame.__do_layout
flex_sizer = wx.FlexGridSizer(5, 3, 2, 25)
flex_sizer.Add(self.todo1, 0, 0, 0)
flex_sizer.Add(self.timer_label1, 0, 0, 0)
flex_sizer.Add(self.set_timer1, 0, 0, 0)
flex_sizer.Add(self.todo2, 0, 0, 0)
flex_sizer.Add(self.timer_label2, 0, 0, 0)
flex_sizer.Add(self.set_timer2, 0, 0, 0)
flex_sizer.Add(self.todo3, 0, 0, 0)
flex_sizer.Add(self.timer_label3, 0, 0, 0)
flex_sizer.Add(self.set_timer3, 0, 0, 0)
flex_sizer.Add(self.todo4, 0, 0, 0)
flex_sizer.Add(self.timer_label4, 0, 0, 0)
flex_sizer.Add(self.set_timer4, 0, 0, 0)
flex_sizer.Add(self.todo5, 0, 0, 0)
flex_sizer.Add(self.timer_label5, 0, 0, 0)
flex_sizer.Add(self.set_timer5, 0, 0, 0)
self.SetSizer(flex_sizer)
flex_sizer.Fit(self)
self.Layout()
# end wxGlade
def on_set1(self, event): # wxGlade: MyFrame.<event_handler>
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
MyTimer = settimer.Timer(None, -1, "")
MyTimer.get_out_instance(self)
app.SetTopWindow(MyTimer)
MyTimer.Show()
app.MainLoop()
event.Skip()
def set_label(self):
self.timer_label1.SetLabel("%02d:%02d" % (self.hours, self.minutes))
self.minutes -= 1
# end of class MyFrame
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
main_frame = MyFrame(None, -1, "")
app.SetTopWindow(main_frame)
main_frame.Show()
app.MainLoop()
timer.py
import threading
import time
class Timer(threading.Thread):
def __init__(self, seconds, track):
threading.Thread.__init__(self)
self.total_time = seconds
self.track = track
def run(self):
for sec in range(self.total_time):
time.sleep(60)
self.track.set_label()
settimer.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Fri Jul 9 16:49:11 2010
import wx
import timer
# begin wxGlade: extracode
# end wxGlade
class Timer(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: Timer.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.hours_text = wx.TextCtrl(self, -1, "")
self.hours = wx.StaticText(self, -1, "HH")
self.minutes_text = wx.TextCtrl(self, -1, "")
self.minutes = wx.StaticText(self, -1, "MM")
self.set = wx.Button(self, -1, "Set")
self.out_instance = None
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_BUTTON, self.on_set, self.set)
# end wxGlade
def __set_properties(self):
# begin wxGlade: Timer.__set_properties
self.SetTitle("Set Timer")
self.hours_text.SetMinSize((40, 25))
self.hours.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.minutes_text.SetMinSize((40, 25))
self.minutes.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set.SetMinSize((50, 27))
# end wxGlade
def __do_layout(self):
# begin wxGlade: Timer.__do_layout
flex_sizer = wx.FlexGridSizer(1, 5, 0, 4)
flex_sizer.Add(self.hours_text, 0, 0, 0)
flex_sizer.Add(self.hours, 0, wx.ALIGN_CENTER_VERTICAL, 0)
flex_sizer.Add(self.minutes_text, 0, 0, 0)
flex_sizer.Add(self.minutes, 0, wx.ALIGN_CENTER_VERTICAL, 0)
flex_sizer.Add(self.set, 0, wx.ALIGN_CENTER_VERTICAL, 0)
self.SetSizer(flex_sizer)
flex_sizer.Fit(self)
flex_sizer.AddGrowableRow(1)
flex_sizer.AddGrowableCol(3)
self.Layout()
# end wxGlade
def get_out_instance(self, out):
# get the instance of trackwork
# this method is meant to be called outside this class
self.out_instance = out
def on_set(self, event): # wxGlade: Timer.<event_handler>
self.out_instance.hours = int(self.hours_text.GetValue())
self.out_instance.minutes = int(self.minutes_text.GetValue())
self.out_instance.set_label()
t = timer.Timer(self.out_instance.minutes, self.out_instance)
t.start()
self.Destroy()
event.Skip()
# end of class Timer
A:
You should have used wx.Timer instead of starting a thread that will be most of the time waiting.
wx.Timer will call your code in the specified interval.
| Pango error after a minute of running | I have the following python modules. Sorry if the code is ugly. This is my first python GUI app and I'm fairly new to python as well. It's some sort of a count down timer with a todo list. It works kinda well except that after two minutes after running the program, it crashes with the following error:
Pango:ERROR:/build/buildd/pango1.0-1.28.0/pango/pango-layout.c:3739:pango_layout_check_lines: assertion failed: (!layout->log_attrs)
I have absolutely no idea what that even means. One I'm confused about is that it works after the first minute, ie. the timer label counts down ok but on the next minute, it crashes immediately.
After googling a bit, I think the issue might be related to multithreading? Any ideas?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Fri Jul 9 17:00:08 2010
import wx
import settimer
# begin wxGlade: extracode
# end wxGlade
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.todo1 = wx.TextCtrl(self, -1, "")
self.timer_label1 = wx.StaticText(self, -1, "00:00")
self.set_timer1 = wx.Button(self, -1, "Set Timer")
self.todo2 = wx.TextCtrl(self, -1, "")
self.timer_label2 = wx.StaticText(self, -1, "00:00")
self.set_timer2 = wx.Button(self, -1, "Set Timer")
self.todo3 = wx.TextCtrl(self, -1, "")
self.timer_label3 = wx.StaticText(self, -1, "00:00")
self.set_timer3 = wx.Button(self, -1, "Set Timer")
self.todo4 = wx.TextCtrl(self, -1, "")
self.timer_label4 = wx.StaticText(self, -1, "00:00")
self.set_timer4 = wx.Button(self, -1, "Set Timer")
self.todo5 = wx.TextCtrl(self, -1, "")
self.timer_label5 = wx.StaticText(self, -1, "00:00")
self.set_timer5 = wx.Button(self, -1, "Set Timer")
self.hours = 0
self.minutes = 0
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_BUTTON, self.on_set1, self.set_timer1)
self.Bind(wx.EVT_BUTTON, self.on_set2, self.set_timer2)
self.Bind(wx.EVT_BUTTON, self.on_set3, self.set_timer3)
self.Bind(wx.EVT_BUTTON, self.on_set4, self.set_timer4)
self.Bind(wx.EVT_BUTTON, self.on_set5, self.set_timer5)
# end wxGlade
def __set_properties(self):
# begin wxGlade: MyFrame.__set_properties
self.SetTitle("Track Work")
self.todo1.SetMinSize((300, 25))
self.timer_label1.SetMinSize((100, 30))
self.timer_label1.SetFont(wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set_timer1.SetMinSize((85, 27))
self.todo2.SetMinSize((300, 25))
self.timer_label2.SetMinSize((100, 30))
self.timer_label2.SetFont(wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set_timer2.SetMinSize((85, 27))
self.todo3.SetMinSize((300, 25))
self.timer_label3.SetMinSize((100, 30))
self.timer_label3.SetFont(wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set_timer3.SetMinSize((85, 27))
self.todo4.SetMinSize((300, 25))
self.timer_label4.SetMinSize((100, 30))
self.timer_label4.SetFont(wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set_timer4.SetMinSize((85, 27))
self.todo5.SetMinSize((300, 25))
self.timer_label5.SetMinSize((100, 30))
self.timer_label5.SetFont(wx.Font(15, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set_timer5.SetMinSize((85, 27))
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyFrame.__do_layout
flex_sizer = wx.FlexGridSizer(5, 3, 2, 25)
flex_sizer.Add(self.todo1, 0, 0, 0)
flex_sizer.Add(self.timer_label1, 0, 0, 0)
flex_sizer.Add(self.set_timer1, 0, 0, 0)
flex_sizer.Add(self.todo2, 0, 0, 0)
flex_sizer.Add(self.timer_label2, 0, 0, 0)
flex_sizer.Add(self.set_timer2, 0, 0, 0)
flex_sizer.Add(self.todo3, 0, 0, 0)
flex_sizer.Add(self.timer_label3, 0, 0, 0)
flex_sizer.Add(self.set_timer3, 0, 0, 0)
flex_sizer.Add(self.todo4, 0, 0, 0)
flex_sizer.Add(self.timer_label4, 0, 0, 0)
flex_sizer.Add(self.set_timer4, 0, 0, 0)
flex_sizer.Add(self.todo5, 0, 0, 0)
flex_sizer.Add(self.timer_label5, 0, 0, 0)
flex_sizer.Add(self.set_timer5, 0, 0, 0)
self.SetSizer(flex_sizer)
flex_sizer.Fit(self)
self.Layout()
# end wxGlade
def on_set1(self, event): # wxGlade: MyFrame.<event_handler>
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
MyTimer = settimer.Timer(None, -1, "")
MyTimer.get_out_instance(self)
app.SetTopWindow(MyTimer)
MyTimer.Show()
app.MainLoop()
event.Skip()
def set_label(self):
self.timer_label1.SetLabel("%02d:%02d" % (self.hours, self.minutes))
self.minutes -= 1
# end of class MyFrame
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
main_frame = MyFrame(None, -1, "")
app.SetTopWindow(main_frame)
main_frame.Show()
app.MainLoop()
timer.py
import threading
import time
class Timer(threading.Thread):
def __init__(self, seconds, track):
threading.Thread.__init__(self)
self.total_time = seconds
self.track = track
def run(self):
for sec in range(self.total_time):
time.sleep(60)
self.track.set_label()
settimer.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Fri Jul 9 16:49:11 2010
import wx
import timer
# begin wxGlade: extracode
# end wxGlade
class Timer(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: Timer.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.hours_text = wx.TextCtrl(self, -1, "")
self.hours = wx.StaticText(self, -1, "HH")
self.minutes_text = wx.TextCtrl(self, -1, "")
self.minutes = wx.StaticText(self, -1, "MM")
self.set = wx.Button(self, -1, "Set")
self.out_instance = None
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_BUTTON, self.on_set, self.set)
# end wxGlade
def __set_properties(self):
# begin wxGlade: Timer.__set_properties
self.SetTitle("Set Timer")
self.hours_text.SetMinSize((40, 25))
self.hours.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.minutes_text.SetMinSize((40, 25))
self.minutes.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.set.SetMinSize((50, 27))
# end wxGlade
def __do_layout(self):
# begin wxGlade: Timer.__do_layout
flex_sizer = wx.FlexGridSizer(1, 5, 0, 4)
flex_sizer.Add(self.hours_text, 0, 0, 0)
flex_sizer.Add(self.hours, 0, wx.ALIGN_CENTER_VERTICAL, 0)
flex_sizer.Add(self.minutes_text, 0, 0, 0)
flex_sizer.Add(self.minutes, 0, wx.ALIGN_CENTER_VERTICAL, 0)
flex_sizer.Add(self.set, 0, wx.ALIGN_CENTER_VERTICAL, 0)
self.SetSizer(flex_sizer)
flex_sizer.Fit(self)
flex_sizer.AddGrowableRow(1)
flex_sizer.AddGrowableCol(3)
self.Layout()
# end wxGlade
def get_out_instance(self, out):
# get the instance of trackwork
# this method is meant to be called outside this class
self.out_instance = out
def on_set(self, event): # wxGlade: Timer.<event_handler>
self.out_instance.hours = int(self.hours_text.GetValue())
self.out_instance.minutes = int(self.minutes_text.GetValue())
self.out_instance.set_label()
t = timer.Timer(self.out_instance.minutes, self.out_instance)
t.start()
self.Destroy()
event.Skip()
# end of class Timer
| [
"You should have used wx.Timer instead of starting a thread that will be most of the time waiting.\nwx.Timer will call your code in the specified interval.\n"
] | [
0
] | [] | [] | [
"python",
"wxglade",
"wxpython"
] | stackoverflow_0003225183_python_wxglade_wxpython.txt |
Q:
How to check if an element of a list is a number?
How can I check if the first element of the list (below) is a number (using some sort of regular expression) in python:
temp = ['1', 'abc', 'XYZ', 'test', '1']
Many thanks.
A:
try:
i = int(temp[0])
except ValueError:
print "not an integer\n"
try:
i = float(temp[0])
except ValueError:
print "not a number\n"
If it must be done with a regex:
import re
re.match( '^[-+]?(([0-9]+([.][0-9]*)?)|(([0-9]*[.])?[0-9]+))$', temp[0] )
A:
If you are just expecting a simple positive number, you can use the isDigit method of Strings.
if temp[0].isdigit(): print "It's a number"
A:
Using regular expressions (because you asked):
>>> import re
>>> if re.match('\d+', temp[0]): print "it's a number!"
Otherwise, just try to parse as an int and catch the exception:
>>> int(temp[0])
Of course, this all gets (slightly) more complicated if you want floats, negatives, scientific notation, etc. I'll leave that as an exercise to the asker :)
| How to check if an element of a list is a number? | How can I check if the first element of the list (below) is a number (using some sort of regular expression) in python:
temp = ['1', 'abc', 'XYZ', 'test', '1']
Many thanks.
| [
"try:\n i = int(temp[0])\nexcept ValueError:\n print \"not an integer\\n\"\n\ntry:\n i = float(temp[0])\nexcept ValueError:\n print \"not a number\\n\"\n\nIf it must be done with a regex:\nimport re\nre.match( '^[-+]?(([0-9]+([.][0-9]*)?)|(([0-9]*[.])?[0-9]+))$', temp[0] )\n\n",
"If you are just expecting a s... | [
13,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0003225305_python.txt |
Q:
mod_python for python 2.7
I recently downloaded python 2.7 on my computer (x64) and I would like to install mod_python for it (I have apache 2.2), however, I can't find a mod_python release supporting python 2.7. Has development stopped? If so, what should I use instead?
A:
Development on mod_python has stopped and its use is no longer recommended. I suggest mod_wsgi
From the mod_python Django documentation:
Support for mod_python has been deprecated, and will be removed in Django 1.5. If you are configuring a new deployment, you are strongly encouraged to consider using mod_wsgi or any of the other supported servers.
| mod_python for python 2.7 | I recently downloaded python 2.7 on my computer (x64) and I would like to install mod_python for it (I have apache 2.2), however, I can't find a mod_python release supporting python 2.7. Has development stopped? If so, what should I use instead?
| [
"Development on mod_python has stopped and its use is no longer recommended. I suggest mod_wsgi \nFrom the mod_python Django documentation:\n\nSupport for mod_python has been deprecated, and will be removed in Django 1.5. If you are configuring a new deployment, you are strongly encouraged to consider using mod_wsg... | [
12
] | [] | [] | [
"mod_python",
"python",
"python_2.7"
] | stackoverflow_0003225498_mod_python_python_python_2.7.txt |
Q:
Base64 encode binary uploaded data on the AppEngine
I've been trying to Base64 encode image data from the user (in this case a trusted admin) in order to skip as many calls to the BlobStore as I possibly can. Every time I attempt to encode it, I recieve an error saying:
Error uploading image: 'ascii' codec can't decode byte 0x89 in position 0: ordinal not in range(128)
I've googled the error (the less significant parts) and found that it may have something to do with Unicode (?). The template portion is just a basic upload form, while the handler contains the following code:
def post(self,id):
logging.info("ImagestoreHandler#post %s", self.request.path)
fileupload = self.request.POST.get("file",None)
if fileupload is None : return self.error(400)
content_type = fileupload.type or getContentType( fileupload.filename )
if content_type is None:
self.error(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write( "Unsupported image type: " + fileupload.filename )
return
logging.debug( "File upload: %s, mime type: %s", fileupload.filename, content_type )
try:
(img_name, img_url) = self._store_image(
fileupload.filename, fileupload.file, content_type )
self.response.headers['Location'] = img_url
ex=None
except Exception, err:
logging.exception( "Error while storing image" )
self.error(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("Error uploading image: " + str(err))
return
#self.redirect(urlBase % img.key() ) #dummy redirect is acceptable for non-AJAX clients,
# location header should be acceptable for true REST clients, however AJAX requests
# might not be able to access the location header so we'll write a 200 response with
# the new URL in the response body:
acceptType = self.request.accept.best_match( listRenderers.keys() )
out = self.response.out
if acceptType == 'application/json':
self.response.headers['Content-Type'] = 'application/json'
out.write( '{"name":"%s","href":"%s"}' % ( img_name, img_url ) )
elif re.search( 'html|xml', acceptType ):
self.response.headers['Content-Type'] = 'text/html'
out.write( '<a href="%s">%s</a>' % ( img_url, img_name) )
def _store_image(self, name, file, content_type):
"""POST handler delegates to this method for actual image storage; as
a result, alternate implementation may easily override the storage
mechanism without rewriting the same content-type handling.
This method returns a tuple of file name and image URL."""
img_enc = base64.b64encode(file.read())
img_enc_struct = "data:%s;base64,%s" % (content_type, img_enc)
img = Image( name=name, data=img_enc_struct )
img.put()
logging.info("Saved image to key %s", img.key() )
return ( str(img.name), img.key() )
My image model:
from google.appengine.ext import db
class Image(db.Model):
name = db.StringProperty(required=True)
data = db.TextProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
owner = db.UserProperty(auto_current_user_add=True)
Any help is greatly appreciated. This code, minus my image encoding in _store_image, comes from the blooger branch of gvdent here.
A:
your store image code could be like this....
img = Image( name=name, data=file.read() )
img.put()
return ( str(img.name), img.key() )
doing base64encode of binary data may increase the size of data itself and increase the cpu encoding and decoding time.
and Blobstore uses the same storage sturcuture as datastore, so it is just making easier to
use file upload store download.
| Base64 encode binary uploaded data on the AppEngine | I've been trying to Base64 encode image data from the user (in this case a trusted admin) in order to skip as many calls to the BlobStore as I possibly can. Every time I attempt to encode it, I recieve an error saying:
Error uploading image: 'ascii' codec can't decode byte 0x89 in position 0: ordinal not in range(128)
I've googled the error (the less significant parts) and found that it may have something to do with Unicode (?). The template portion is just a basic upload form, while the handler contains the following code:
def post(self,id):
logging.info("ImagestoreHandler#post %s", self.request.path)
fileupload = self.request.POST.get("file",None)
if fileupload is None : return self.error(400)
content_type = fileupload.type or getContentType( fileupload.filename )
if content_type is None:
self.error(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write( "Unsupported image type: " + fileupload.filename )
return
logging.debug( "File upload: %s, mime type: %s", fileupload.filename, content_type )
try:
(img_name, img_url) = self._store_image(
fileupload.filename, fileupload.file, content_type )
self.response.headers['Location'] = img_url
ex=None
except Exception, err:
logging.exception( "Error while storing image" )
self.error(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("Error uploading image: " + str(err))
return
#self.redirect(urlBase % img.key() ) #dummy redirect is acceptable for non-AJAX clients,
# location header should be acceptable for true REST clients, however AJAX requests
# might not be able to access the location header so we'll write a 200 response with
# the new URL in the response body:
acceptType = self.request.accept.best_match( listRenderers.keys() )
out = self.response.out
if acceptType == 'application/json':
self.response.headers['Content-Type'] = 'application/json'
out.write( '{"name":"%s","href":"%s"}' % ( img_name, img_url ) )
elif re.search( 'html|xml', acceptType ):
self.response.headers['Content-Type'] = 'text/html'
out.write( '<a href="%s">%s</a>' % ( img_url, img_name) )
def _store_image(self, name, file, content_type):
"""POST handler delegates to this method for actual image storage; as
a result, alternate implementation may easily override the storage
mechanism without rewriting the same content-type handling.
This method returns a tuple of file name and image URL."""
img_enc = base64.b64encode(file.read())
img_enc_struct = "data:%s;base64,%s" % (content_type, img_enc)
img = Image( name=name, data=img_enc_struct )
img.put()
logging.info("Saved image to key %s", img.key() )
return ( str(img.name), img.key() )
My image model:
from google.appengine.ext import db
class Image(db.Model):
name = db.StringProperty(required=True)
data = db.TextProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
owner = db.UserProperty(auto_current_user_add=True)
Any help is greatly appreciated. This code, minus my image encoding in _store_image, comes from the blooger branch of gvdent here.
| [
"your store image code could be like this....\nimg = Image( name=name, data=file.read() )\nimg.put()\nreturn ( str(img.name), img.key() )\n\ndoing base64encode of binary data may increase the size of data itself and increase the cpu encoding and decoding time.\nand Blobstore uses the same storage sturcuture as data... | [
4
] | [] | [] | [
"base64",
"encoding",
"google_app_engine",
"python"
] | stackoverflow_0003225500_base64_encoding_google_app_engine_python.txt |
Q:
MemoryError when using imaplib fetch
Please help me, I am getting MemoryError when trying to fetch a specific email. This is the error message:
python(23838,0x1888c00) malloc: *** vm_allocate(size=3309568) failed (error code=3)
python(23838,0x1888c00) malloc: *** error: can't allocate region
python(23838,0x1888c00) malloc: *** set a breakpoint in szone_error to debug
Exception in thread Thread-1:Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/threading.py", line 442, in __bootstrap
self.run()
File "/Volumes/SvnDevDisk/branches/HaversackProject_Version_0.2/plugins/GaMailClientPlugin/python/imap/imap_reader.py", line 25, in run
self.readMailbox(eachMailbox)
File "/Volumes/SvnDevDisk/branches/HaversackProject_Version_0.2/plugins/GaMailClientPlugin/python/imap/imap_reader.py", line 58, in readMailbox
resp, content = _mailConnection.fetch(num, '(RFC822 FLAGS)')
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 417, in fetch
typ, dat = self._simple_command(name, message_set, message_parts)
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 1004, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 830, in _command_complete
typ, data = self._get_tagged_response(tag)
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 935, in _get_tagged_response
self._get_response()
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 896, in _get_response
data = self.read(size)
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 231, in read
return self.file.read(size)
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/socket.py", line 301, in read
data = self._sock.recv(recv_size)
MemoryError
And here is my code:
resp, content = _mailConnection.fetch(num, '(RFC822 FLAGS)')
I am using python 2.3.5
Thanks in advance!
A:
A MemoryError usually indicates that your system ran out of free memory. Perhaps your Python script is keeping references to all messages it's seen and the total sum of them is too big to fit in memory?
A:
http://bugs.python.org/issue1092502
The suggested fix there by a_lauer seems to have fixed my problem.
| MemoryError when using imaplib fetch | Please help me, I am getting MemoryError when trying to fetch a specific email. This is the error message:
python(23838,0x1888c00) malloc: *** vm_allocate(size=3309568) failed (error code=3)
python(23838,0x1888c00) malloc: *** error: can't allocate region
python(23838,0x1888c00) malloc: *** set a breakpoint in szone_error to debug
Exception in thread Thread-1:Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/threading.py", line 442, in __bootstrap
self.run()
File "/Volumes/SvnDevDisk/branches/HaversackProject_Version_0.2/plugins/GaMailClientPlugin/python/imap/imap_reader.py", line 25, in run
self.readMailbox(eachMailbox)
File "/Volumes/SvnDevDisk/branches/HaversackProject_Version_0.2/plugins/GaMailClientPlugin/python/imap/imap_reader.py", line 58, in readMailbox
resp, content = _mailConnection.fetch(num, '(RFC822 FLAGS)')
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 417, in fetch
typ, dat = self._simple_command(name, message_set, message_parts)
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 1004, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 830, in _command_complete
typ, data = self._get_tagged_response(tag)
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 935, in _get_tagged_response
self._get_response()
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 896, in _get_response
data = self.read(size)
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/imaplib.py", line 231, in read
return self.file.read(size)
File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/socket.py", line 301, in read
data = self._sock.recv(recv_size)
MemoryError
And here is my code:
resp, content = _mailConnection.fetch(num, '(RFC822 FLAGS)')
I am using python 2.3.5
Thanks in advance!
| [
"A MemoryError usually indicates that your system ran out of free memory. Perhaps your Python script is keeping references to all messages it's seen and the total sum of them is too big to fit in memory?\n",
"http://bugs.python.org/issue1092502\nThe suggested fix there by a_lauer seems to have fixed my problem.\... | [
0,
0
] | [] | [] | [
"imaplib",
"malloc",
"python"
] | stackoverflow_0003184198_imaplib_malloc_python.txt |
Q:
3d Drawing in Python with OpenGL
I need to:
draw 3d models with specific 3ds textures
have the models be moving (just position)
have a camera viewer which is easily maneuverable (ideally in real time)
I would like to accomplish this with Python and OpenGL. What would be the best libraries to accomplish this and what are some good resources to read up on?
Thanks in advance!
A:
I recommend python-ogre for this. It abstracts away keyboard, mouse, windowing, OpenGL and with some additional extension you can even get sound and physics. I have a fairly sophisticated 3D project that I have been writing with OGRE so I can attest to its ease of use. The tutorial apps and examples are enough to do what you described here. There are also exporters for all the major 3D modeling packages so you can export models to a format that is acceptable for OGRE. It's very mature and stable at this point as well, and the community is large.
A:
While I usually dislike answers that point to other technologies than the ones asked, I will bedoing that here.
As you might have seen, googling for Python OpenGL will yield a host of options. From raw unmaintained hard-to install bindings, to higer level 3D libraries that still allow low level OpenGL calls.
I am no 3D man -but I will recomend you to use Blender 3D. (http://www.blender.org/) -
it is a full featured 3D modeling + animation + presentation software, scriptable and controlable with Python. Wiithin it, you will have the camera viewer feature ready to use in the presentation mode (called "Game Engine") , there are python scripts to import 3ds files, yo can move the models either programatically from python or with the logic blocks -
and yes, it eve allows you to do low level OpenGL calls :-) (so it is not that out of the way).
I think it will have everything you want, and it willbe far easier to get there than scripting everything from the ground up.
A:
Either pyOpengl or Qt and the QopenGL widget
| 3d Drawing in Python with OpenGL | I need to:
draw 3d models with specific 3ds textures
have the models be moving (just position)
have a camera viewer which is easily maneuverable (ideally in real time)
I would like to accomplish this with Python and OpenGL. What would be the best libraries to accomplish this and what are some good resources to read up on?
Thanks in advance!
| [
"I recommend python-ogre for this. It abstracts away keyboard, mouse, windowing, OpenGL and with some additional extension you can even get sound and physics. I have a fairly sophisticated 3D project that I have been writing with OGRE so I can attest to its ease of use. The tutorial apps and examples are enough to ... | [
4,
2,
0
] | [] | [] | [
"opengl",
"python"
] | stackoverflow_0003225539_opengl_python.txt |
Q:
How do I concatenate strings from a dictionary by identifying the last item with Python?
I need to concatenate string to an existing one as follows.
for k,v in r.iteritems():
tableGenString += "%s %s, " % (k, what_type(v))
The problem is that for the last item the comma(',') should not be added.
How can I check if k,v is the last item?
Added
The example is a simplified version of the real code as follows.
for k,v in r.iteritems():
filteredKey = m.mapper(k)
(typestring, valuestring) = what_type(v)
tableGenString += "%s %s, " % (k, typestring)
string1 += "%s, " % k
string2 += "%s, " % valuestring
I need to check the last item for this case.
A:
Don't build large strings with concatenation like that. Do this instead:
tableGenString = ', '.join('%s %s' % (k, what_type(v)) for k, v in r.iteritems())
A:
The OP insists in a comment:
I need to find a way to find the last
item as I added to my original
question
apparently for purposes other than clumsily duplicate the ', '.join correctly suggested in other answers.
Of course, the order in which keys and values are presented by iteritems (or any other way to iterate on a dict, which is a hash table and has no concept of "order", and therefore not of "first" or "last" either!) is totally arbitrary. Nevertheless, the last one (to be presented in this arbitrary order) can be identified:
for i, (k,v) in enumerate(r.iteritems()):
if i == len(r) - 1:
print "last item: key=%r, value=%r" % (k, v)
Similarly, once you get i from this kind of enumerate call, if i==0: will identify the first item, if i==len(r)//2: will identify the middle item, and so forth.
A:
Use the "join" string method instead of an outter for:
tableGenString = ", ".join ("%s %s" %(k, what_type(v) for k, v in r.iteritems())
A:
Ugh. If you'd like something that's readable instead of an overly-dense join, here:
def build_str(r):
tableGenString = ""
for k,v in r.iteritems():
if tableGenString != "":
tableGenString += ", "
tableGenString += "%s %s" % (k, type(v))
return tableGenString
Sample return value:
baz <type 'str'>, have a list <type 'list'>, foo <type 'int'>, bar <type 'str'>, or a tuple <type 'tuple'>
And lest someone complain that this is somehow slower than the join... it's not on my box:
import timeit
r = {
"foo": 123,
"bar": "456",
"baz": "abcd",
"have a list": [7, 8, "efgh"],
"or a tuple": (9, 0, 10),
}
def build_str(r):
tableGenString = ""
for k,v in r.iteritems():
if tableGenString != "":
tableGenString += ", "
tableGenString += "%s %s" % (k, type(v))
return tableGenString
if __name__ == '__main__':
readable_time = timeit.Timer("build_str(r)", "from __main__ import build_str, r").timeit()
print "Readable time: %f" % (readable_time,)
join_time = timeit.Timer("', '.join('%s %s' % (k, type(v)) for k, v in r.iteritems())", "from __main__ import r").timeit()
print "Join time: %f" % (join_time,)
...
$ python concat.py
Readable time: 4.705579
Join time: 5.277732
$
| How do I concatenate strings from a dictionary by identifying the last item with Python? | I need to concatenate string to an existing one as follows.
for k,v in r.iteritems():
tableGenString += "%s %s, " % (k, what_type(v))
The problem is that for the last item the comma(',') should not be added.
How can I check if k,v is the last item?
Added
The example is a simplified version of the real code as follows.
for k,v in r.iteritems():
filteredKey = m.mapper(k)
(typestring, valuestring) = what_type(v)
tableGenString += "%s %s, " % (k, typestring)
string1 += "%s, " % k
string2 += "%s, " % valuestring
I need to check the last item for this case.
| [
"Don't build large strings with concatenation like that. Do this instead:\ntableGenString = ', '.join('%s %s' % (k, what_type(v)) for k, v in r.iteritems())\n\n",
"The OP insists in a comment:\n\nI need to find a way to find the last\n item as I added to my original\n question\n\napparently for purposes other ... | [
15,
2,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003225594_dictionary_python.txt |
Q:
Removing the first part of a concatenated string with Python
I have a string as follows
CompilationStatistics_Compilation_StepList_Map_TimingUsage_ClockList_Clock_MinimumPeriod
What would be the simplest way to remove the first part (CompilationStatistics_) or the last part (_MiniumuPeriod)?
I think about using regular expression, but I expect there should a better way.
m = re.search("{.+}_{.+}", string)
m.group(2)
A:
See the Python documentation for String methods, particularly partition and rpartition:
s = "CompilationStatistics_Compilation_StepList_Map_TimingUsage_ClockList_Clock_MinimumPeriod"
print s.partition('_')[2].rpartition('_')[0]
Result
Compilation_StepList_Map_TimingUsage_ClockList_Clock
A:
'_'.join(s.split("_")[1:-1])?
Changing the splice numbers will change how much you get: removing the "-1" will only remove the first item, for example.
A:
All but first:
s[s.find('_') + 1:]
All but last:
s[0:s.rfind('_')]
Without either:
s[s.find('_') + 1:s.rfind('_')]
find returns the first index of the string, and rfind returns the last. Then, we just use slice syntax.
A:
If you know the size of the chunks you want to cut out, you can use Python's string slicing, like this:
s="CompilationStatistics_Compilation_StepList_Map_TimingUsage_ClockList_Clock_MinimumPeriod"
print s[22:-14]
Of course, there are other ways you can find the number you need, like using String.rindex() to find the place where the end chunk you want to cut off starts. For example:
print s[len("CompilationStatistics_"):s.rindex("_MinimumPeriod")]
A:
Removing the first part is trivially down with split():
s.split("_", 1)[1] # Take the second part of the string, split into 2 pieces.
| Removing the first part of a concatenated string with Python | I have a string as follows
CompilationStatistics_Compilation_StepList_Map_TimingUsage_ClockList_Clock_MinimumPeriod
What would be the simplest way to remove the first part (CompilationStatistics_) or the last part (_MiniumuPeriod)?
I think about using regular expression, but I expect there should a better way.
m = re.search("{.+}_{.+}", string)
m.group(2)
| [
"See the Python documentation for String methods, particularly partition and rpartition:\ns = \"CompilationStatistics_Compilation_StepList_Map_TimingUsage_ClockList_Clock_MinimumPeriod\"\nprint s.partition('_')[2].rpartition('_')[0]\n\nResult\nCompilation_StepList_Map_TimingUsage_ClockList_Clock\n\n",
"'_'.join(s... | [
3,
3,
2,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003225716_python_string.txt |
Q:
How many can a tuple or list contain in Python?
How many items can contain tuple or list in python? What will be if it is 10 000?
A:
import sys
print sys.maxsize
# prints some system-dependent number representing the maximum
# size most containers can hold.
Python sys module
I suspect on most platforms, sys.maxsize would return the same value as sys.maxint (which is guaranteed to be at least 2**31-1), but I doubt that's guaranteed.
A:
You can try this yourself, interactively in the Python interpreter:
>>> tuple([0] * 10000)
(0, 0, 0, ... 0, 0)
where ... represents 9995 zeros.
A:
If you mean what the maximum size of a tuple or list is, I assume that it is very large. Most likely you would run out of memory before hitting some limit. Someone else can add to this if they have specific knowledge of the indexing, possible 2.1 or 4.2 billion items in 32-bit and 8 or 16 sextillion in 64-bit.
| How many can a tuple or list contain in Python? | How many items can contain tuple or list in python? What will be if it is 10 000?
| [
"import sys\n\nprint sys.maxsize\n# prints some system-dependent number representing the maximum\n# size most containers can hold.\n\nPython sys module\nI suspect on most platforms, sys.maxsize would return the same value as sys.maxint (which is guaranteed to be at least 2**31-1), but I doubt that's guaranteed.\n",... | [
6,
3,
0
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0003225712_list_python_tuples.txt |
Q:
GAE: Best way to determine how many of a Kind is stored?
What is the best way to determine how many models of a certain kind are in my app's datastore? The documentation says that MyKind.all().count() is only marginally better than retrieving all of the data, and has a limit of 1000. This is not helpful, because I am expecting to have 6000+ instances of MyKind stored.
Is there a better way to do this? What if I just get the keys, and count those?
I'm using Python.
A:
If an approximate count is good enough, you could use the statistics API:
http://code.google.com/appengine/docs/python/datastore/stats.html
A:
If you do keys-only it should be pretty fast, since this only has to read the index and doesn't actually fetch any entities. Use a cursor and loop until count() returns less than 1000.
A:
This SO question has an answer (by @jgeewax) that is almost right (wrong exit condition, as I commented there). Here is a fixed one...:
class MyModel(db.Expando):
@classmethod
def count_all(cls):
"""
Count *all* of the rows (without maxing out at 1000)
"""
count = 0
query = cls.all().order('__key__')
while True:
current_count = query.count()
if current_count == 0: return count
count += current_count
if current_count == 1000:
last_key = query.fetch(1, 999)[0].key()
query = query.filter('__key__ > ', last_key)
return count
The performance problem, of course, is that this will use one actual query to the datastore for every 1000 items you have -- denormalizing things by keeping an actual count, as @Chris suggests, is going to use far fewer queries. (Be sure to use a sharded counter or other forms of efficient counters as App Engine Fan explains!).
Denormalization is a fact of life with non-relational DBs, and, done properly, can make a huge difference to your performance. As for the worries you express about DRY, just use class methods or other forms of functions to performs all puts and removes of your entities (i.e., [[except within the class methods in question]], never call methods such as .put() directly on the entities, call the appropriate class methods instead!), and those functions will be the obvious place to keep the denormalized counters up to date!
A:
Keep a counter object for your application stored in the database, and update it whenever you create and delete objects.
| GAE: Best way to determine how many of a Kind is stored? | What is the best way to determine how many models of a certain kind are in my app's datastore? The documentation says that MyKind.all().count() is only marginally better than retrieving all of the data, and has a limit of 1000. This is not helpful, because I am expecting to have 6000+ instances of MyKind stored.
Is there a better way to do this? What if I just get the keys, and count those?
I'm using Python.
| [
"If an approximate count is good enough, you could use the statistics API:\nhttp://code.google.com/appengine/docs/python/datastore/stats.html\n",
"If you do keys-only it should be pretty fast, since this only has to read the index and doesn't actually fetch any entities. Use a cursor and loop until count() return... | [
5,
3,
2,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003225397_google_app_engine_python.txt |
Q:
Python: JobID counter
Whats the best to make a job ID counter in python? For example if a Job ID startd of with value of "0" and everytime someone ran the script the counter went up by one?
E.G.
X = 0
Perform_some_process
x +=1
Now the value of x will be one, but if i ran the script again x will be equal to one again and not two. How would make so when someone ran the script for the second time x is equal to two? and so forth for the future runs.
A:
You need to "persist" that counter -- simplest is to use a file for the purpose. For example:
import os
def onemore():
f = __file__ + '.counter'
if os.path.exists(f):
with open(f) as thefile:
counter = int(thefile.read())
else:
counter = -1
counter += 1
with open(f, 'w') as thefile:
thefile.write(str(counter) + '\n')
return counter
This could give problems (missing some counts) if multiple instances of the script are starting at exactly the same time -- if that's an issue for you please let us know (and let us know what OS you need to work on) to learn more about how to perform locking on that crucial file.
This solution also assumes that the directory where this Python (or bytecode) file exists is writable by the user under whose identity the script is running. If that's a problem, the script needs some configuration file indicating which directory is guaranteed to be writable by any user who may be running the script (and will use that directory to form the string f, the name of the counter file).
Note that I've kept the contents of the counter file in easily human-readable form -- that's for ease of debugging (and a tiny price to pay when one number is all that's in the file). It would of course be possible to keep the file in binary form instead.
If your script needs to persist many bits and pieces of info, a sqlite database file is probably the handiest way to keep them all together.
| Python: JobID counter | Whats the best to make a job ID counter in python? For example if a Job ID startd of with value of "0" and everytime someone ran the script the counter went up by one?
E.G.
X = 0
Perform_some_process
x +=1
Now the value of x will be one, but if i ran the script again x will be equal to one again and not two. How would make so when someone ran the script for the second time x is equal to two? and so forth for the future runs.
| [
"You need to \"persist\" that counter -- simplest is to use a file for the purpose. For example:\nimport os\n\ndef onemore():\n f = __file__ + '.counter'\n if os.path.exists(f):\n with open(f) as thefile:\n counter = int(thefile.read())\n else:\n counter = -1\n counter += 1\n ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003225784_python.txt |
Q:
Simulating C#'s sbyte (8 bit signed integer) casting in Python
In C#, I can cast things to 8bit signed ints like so:
(sbyte)arg1;
which when arg1 = 2, the cast returns 2 also. However, obviously casting 128 will return -128. More specifically casting 251 will return -5.
What's the best way to emulate this behavior?
Edit: Found a duplicate question: Typecasting in Python
s8 = (i + 2**7) % 2**8 - 2**7 // convert to signed 8-bit
A:
With ctypes:
from ctypes import cast, pointer, c_int32, c_byte, POINTER
cast(pointer(c_int32(arg1)), POINTER(c_byte)).contents.value
A:
I'd use the struct module of the Python standard library, which, as so often, comes in handy for turning values into bytes and viceversa:
>>> def cast_sbyte(anint):
return struct.unpack('b', struct.pack('<i', anint)[0])[0]
... ...
>>> cast_sbyte(251)
-5
A:
struct module can help you, e.g. here is a way to convert int(4 bytes) to 4 signed bytes
>>> import struct
>>> struct.pack('i',251)
'\xfb\x00\x00\x00'
>>> s=struct.pack('i',251)
>>> print struct.unpack('bbbb',s)
(-5, 0, 0, 0)
A:
>>> from numpy import int8
>>> int8(251)
-5
A:
Try one of the following:
>>> sbyte=lambda n:(255 & n^128)-128
>>> # or sbyte=lambda n:(n+128 & 255)-128
>>> sbyte(251)
-5
>>> sbyte(2)
2
| Simulating C#'s sbyte (8 bit signed integer) casting in Python | In C#, I can cast things to 8bit signed ints like so:
(sbyte)arg1;
which when arg1 = 2, the cast returns 2 also. However, obviously casting 128 will return -128. More specifically casting 251 will return -5.
What's the best way to emulate this behavior?
Edit: Found a duplicate question: Typecasting in Python
s8 = (i + 2**7) % 2**8 - 2**7 // convert to signed 8-bit
| [
"With ctypes:\nfrom ctypes import cast, pointer, c_int32, c_byte, POINTER\ncast(pointer(c_int32(arg1)), POINTER(c_byte)).contents.value\n\n",
"I'd use the struct module of the Python standard library, which, as so often, comes in handy for turning values into bytes and viceversa:\n>>> def cast_sbyte(anint):\n ... | [
3,
2,
0,
0,
0
] | [] | [] | [
"c#",
"casting",
"python"
] | stackoverflow_0003222088_c#_casting_python.txt |
Q:
Help me translate Python code which replaces an extension in file name to C++
I apologize if you know nothing about Python, however, the following snippet should be very readable to anyone. The only trick to watch out for - indexing a list with [-1] gives you the last element if there is one, or raises an exception.
>>> fileName = 'TheFileName.Something.xMl'
>>> fileNameList = fileName.split('.')
>>> assert(len(fileNameList) > 1) # Must have at least one period in it
>>> assert(fileNameList[-1].lower() == 'xml')
>>> fileNameList[-1] = 'bak'
>>> fileName = '.'.join(fileNameList)
>>> print(fileName)
TheFileName.Something.bak
I need to convert this logic into C++ (the language I am actually using, but so far suck at) function with the following signature: void PopulateBackupFileNameOrDie(CAtlString& strBackupFileName, CAtlString& strXmlFileName);. Here strXmlFileName is "input", strBackupFileName is "output" (should I reverse the oprder of the two?). The tricky part is that (correct me if I am wrong) I am working with a Unicode string, so looking for these characters: .xmlXML is not as straight-forward. Latest Python does not have these issues because '.' and "." are both Unicode strings (not a "char" type) of length 1, both contain just a dot.
Notice that the return type is void - do not worry much about it. I do not want to bore you with details of how we communicate an error back to the user. In my Python example I just used an assert. You can do something like that or just include a comment such as // ERROR: [REASON].
Please ask if something is not clear. Suggestions to use std::string, etc. instead of CAtlString for function parameters are not what I am looking for. You may convert them inside the function if you have to, but I would prefer not mixing different string types in one function. I am compiling this C++ on Windows, using VS2010. This implies that I WILL NOT install BOOST, QTString or other libraries which are not available out of the box. Stealing a boost or other header to enable some magic is also not the right solution.
Thanks.
A:
If you're using ATL why not just use CAtlString's methods?
CAtlString filename = _T("TheFileName.Something.xMl");
//search for '.' from the end
int dotIdx = filename.ReverseFind( _T('.') );
if( dotIdx != -1 ) {
//extract the file extension
CAtlString ext = filename.Right( filename.GetLength() - dotIdx );
if( ext.CompareNoCase( _T(".xml" ) ) == 0 ) {
filename.Delete( dotIdx, ext.GetLength() ); //remove extension
filename += _T(".bak");
}
}
A:
I didn't split the string as your code does because that's a bit more work in C++ for really no gain (it's slower, and for this task you really don't need to do it).
string filename = "TheFileName.Something.xMl";
size_t pos = filename.rfind('.');
assert(pos > 0 && pos == filename.length()-4); // the -4 here is for length of ".xml"
for(size_t i = pos+1; i < filename.length(); ++i)
filename[i] = tolower(filename[i]);
assert(filename.substr(pos+1) == "xml");
filename = filename.substr(0,pos+1) + "bak";
std::cout << filename << std::endl;
| Help me translate Python code which replaces an extension in file name to C++ | I apologize if you know nothing about Python, however, the following snippet should be very readable to anyone. The only trick to watch out for - indexing a list with [-1] gives you the last element if there is one, or raises an exception.
>>> fileName = 'TheFileName.Something.xMl'
>>> fileNameList = fileName.split('.')
>>> assert(len(fileNameList) > 1) # Must have at least one period in it
>>> assert(fileNameList[-1].lower() == 'xml')
>>> fileNameList[-1] = 'bak'
>>> fileName = '.'.join(fileNameList)
>>> print(fileName)
TheFileName.Something.bak
I need to convert this logic into C++ (the language I am actually using, but so far suck at) function with the following signature: void PopulateBackupFileNameOrDie(CAtlString& strBackupFileName, CAtlString& strXmlFileName);. Here strXmlFileName is "input", strBackupFileName is "output" (should I reverse the oprder of the two?). The tricky part is that (correct me if I am wrong) I am working with a Unicode string, so looking for these characters: .xmlXML is not as straight-forward. Latest Python does not have these issues because '.' and "." are both Unicode strings (not a "char" type) of length 1, both contain just a dot.
Notice that the return type is void - do not worry much about it. I do not want to bore you with details of how we communicate an error back to the user. In my Python example I just used an assert. You can do something like that or just include a comment such as // ERROR: [REASON].
Please ask if something is not clear. Suggestions to use std::string, etc. instead of CAtlString for function parameters are not what I am looking for. You may convert them inside the function if you have to, but I would prefer not mixing different string types in one function. I am compiling this C++ on Windows, using VS2010. This implies that I WILL NOT install BOOST, QTString or other libraries which are not available out of the box. Stealing a boost or other header to enable some magic is also not the right solution.
Thanks.
| [
"If you're using ATL why not just use CAtlString's methods?\nCAtlString filename = _T(\"TheFileName.Something.xMl\");\n\n//search for '.' from the end\nint dotIdx = filename.ReverseFind( _T('.') );\n\nif( dotIdx != -1 ) {\n //extract the file extension\n CAtlString ext = filename.Right( filename.GetLength() - dot... | [
6,
3
] | [] | [] | [
"c++",
"python",
"string",
"unicode_string",
"visual_studio_2010"
] | stackoverflow_0003216805_c++_python_string_unicode_string_visual_studio_2010.txt |
Q:
to remove specific rows in a csv file using python
i want ro remove specific lines from the following csv file :
"Title.XP PoseRank"
1VDV-constatomGlu-final-NoGluWat.
1VDV-constatomGlu-final-NoGluWat.
P6470-Usha.1
P6470-Usha.2
P6470-Usha.3
P6470-Usha.4
P6470-Usha.5
P6515-Usha.1
P6515-Usha.2
P6517.1
P6517.2
P6517.3
P6517.4
P6517.5
P6553-Usha.1
P6553-Usha.2
P6553-Usha.3
i want to remove the lines that begin with 1VDV-constatomGlu-final-NoGluWat.
A:
The right solution is to use csv parser(i didn't test this code):
writer = csv.writer(open('corrected.csv'))
for row in csv.reader('myfile.csv'):
if not row[0].startswith('1VDV-constatomGlu-final-NoGluWat.'):
writer.writerow(row)
writer.close()
You can use also regular expression or some string manipulations but there is the risk that after your transformations the file will be no longer in csv format
| to remove specific rows in a csv file using python | i want ro remove specific lines from the following csv file :
"Title.XP PoseRank"
1VDV-constatomGlu-final-NoGluWat.
1VDV-constatomGlu-final-NoGluWat.
P6470-Usha.1
P6470-Usha.2
P6470-Usha.3
P6470-Usha.4
P6470-Usha.5
P6515-Usha.1
P6515-Usha.2
P6517.1
P6517.2
P6517.3
P6517.4
P6517.5
P6553-Usha.1
P6553-Usha.2
P6553-Usha.3
i want to remove the lines that begin with 1VDV-constatomGlu-final-NoGluWat.
| [
"The right solution is to use csv parser(i didn't test this code):\n\n\nwriter = csv.writer(open('corrected.csv'))\nfor row in csv.reader('myfile.csv'):\n if not row[0].startswith('1VDV-constatomGlu-final-NoGluWat.'):\n writer.writerow(row)\nwriter.close()\n\n\nYou can use also regular expression or some ... | [
2
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003226285_csv_python.txt |
Q:
Matching "~" at the end of a filename with a python regular expression
I'm working in a script (Python) to find some files. I compare names of files against a regular expression pattern. Now, I have to find files ending with a "~" (tilde), so I built this regex:
if re.match("~$", string_test):
print "ok!"
Well, Python doesn't seem to recognize the regex, I don't know why. I tried the same regex in other languages and it works perfectly, any idea?
PD: I read in a web that I have to insert
# -*- coding: utf-8 -*-
but doesn't help :( .
Thanks a lot, meanwhile I'm going to keep reading to see if a find something.
A:
re.match() is only successful if the regular expression matches at the beginning of the input string. To search for any substring, use re.search() instead:
if re.search("~$", string_test):
print "ok!"
A:
Your regex will only match strings "~" and (believe it or not) "~\n".
You need re.match(r".*~$", whatever) ... that means zero or more of (anything except a newline) followed by a tilde followed by (end-of-string or a newline preceding the end of string).
In the unlikely event that a filename can include a newline, use the re.DOTALL flag and use \Z instead of $.
"worked" in other languages: you must have used a search function.
r at the beginning of a string constant means raw escapes e.g. '\n' is a newline but r'\n' is two characters, a backslash followed by n -- which can also be represented by '\n'. Raw escapes save a lot of \\ in regexes, one should use r"regex" automatically
BTW: in this case avoid the regex confusion ... use whatever.endswith('~')
A:
For finding files, use glob instead,
import os
import glob
path = '/path/to/files'
os.chdir(path)
files = glob.glob('./*~')
print files
A:
The correct regex and the glob solution have already been posted. Another option is to use the fnmatch module:
import fnmatch
if fnmatch.fnmatch(string_test, "*~"):
print "ok!"
This is a tiny bit easier than using a regex. Note that all methods posted here are essentially equivalent: fnmatch is implemented using regular expressions, and glob in turn uses fnmatch.
Note that only in 2009 a patch was added to fnmatch (after six years!) that added support for file names with newlines.
| Matching "~" at the end of a filename with a python regular expression | I'm working in a script (Python) to find some files. I compare names of files against a regular expression pattern. Now, I have to find files ending with a "~" (tilde), so I built this regex:
if re.match("~$", string_test):
print "ok!"
Well, Python doesn't seem to recognize the regex, I don't know why. I tried the same regex in other languages and it works perfectly, any idea?
PD: I read in a web that I have to insert
# -*- coding: utf-8 -*-
but doesn't help :( .
Thanks a lot, meanwhile I'm going to keep reading to see if a find something.
| [
"re.match() is only successful if the regular expression matches at the beginning of the input string. To search for any substring, use re.search() instead:\nif re.search(\"~$\", string_test):\n print \"ok!\"\n\n",
"Your regex will only match strings \"~\" and (believe it or not) \"~\\n\".\nYou need re.match(r... | [
10,
9,
7,
0
] | [] | [] | [
"python",
"regex",
"tilde"
] | stackoverflow_0003226202_python_regex_tilde.txt |
Q:
How do I ensure that the same Python instance is always returned for a particular C++ instance?
I'm using Boost.Python to wrap a C++ library.
How do I ensure that the same Python instance (by object identity) is always returned for a particular C++ instance (by pointer identity)? I can't extend the C++ classes, but I can add a member variable (such as a PyObject * or a boost::python::handle<>) if that helps. I'm thinking that I should be able to cache the Python instance in the C++ instance, and return the cached instance instead of creating a new one. However, I can't figure out what wrapping code is required.
Example class to be wrapped:
class C {
public:
boost::python::handle<> wrapper_;
private:
C();
C(const C &);
~C();
};
Can anyone offer advice?
A:
After investing some time into this very problem I came to the conclusion that it's more trouble than it's worth. I have resigned myself that id() will identify the (potentially short-lived) wrapper object and not the actual C++ object.
Instead I identify my C++ objects in some other way, e.g. by looking at the contents.
| How do I ensure that the same Python instance is always returned for a particular C++ instance? | I'm using Boost.Python to wrap a C++ library.
How do I ensure that the same Python instance (by object identity) is always returned for a particular C++ instance (by pointer identity)? I can't extend the C++ classes, but I can add a member variable (such as a PyObject * or a boost::python::handle<>) if that helps. I'm thinking that I should be able to cache the Python instance in the C++ instance, and return the cached instance instead of creating a new one. However, I can't figure out what wrapping code is required.
Example class to be wrapped:
class C {
public:
boost::python::handle<> wrapper_;
private:
C();
C(const C &);
~C();
};
Can anyone offer advice?
| [
"After investing some time into this very problem I came to the conclusion that it's more trouble than it's worth. I have resigned myself that id() will identify the (potentially short-lived) wrapper object and not the actual C++ object.\nInstead I identify my C++ objects in some other way, e.g. by looking at the c... | [
1
] | [] | [] | [
"boost",
"boost_python",
"c++",
"python"
] | stackoverflow_0003182264_boost_boost_python_c++_python.txt |
Q:
Full text search: Whoosh Vs SOLR
I am working on a Django project, where I need to implement full text search. I have seen SOLR and found some good comments for the same. But as its implemented in Java and would need java enviroment to be installed on the system along with Python. Looking for the python equivalent for SOLR, I have seen Whoosh but I am not sure whether Whoosh is as efficient and strong as SOLR. Or shall I go with SOLR option only or are there any better options than Whoosh and SOLR with python?
Please suggest.
Thanks in advance
A:
Whoosh is actually very fast for a python-only implementation. That said, it's still at least an order of magnitude slower. Depending on the amount of data you need to index and search and the requirements on the maximum allowable latency and concurrent searches, it may not be an option.
SOLR is a bit of a complicated beast, but it's by far the most comprehensive search solution. Mix it with solrpy for stunning results. Yes, you will need java hosting.
You might also want to check out the python bindings for xapian. Xapian is very very fast, but less of a complete solution than SOLR. They are GPL licensed though, so that may/may not be viable for you.
A:
I have used Lucene and Lucene extensions like SOLR and Nutch, and I found out that lucene pretty much satisfies what I need. I've only tried Whoosh once but chose Lucene because
1) I am using Java
2) I had trouble making UTF-8 work with Whoosh (not sure if it works out of the box now). In Lucene, I had no trouble working with Chinese characters.
If you're using Python as your Programming Language and Whoosh satisfies your needs then I'd suggest you use it over Java alternatives for better integration, avoid external dependencies, faster customization if you need to code additional functionalities.
UPDATE: If you're interested in using Lucene, it has a Python wrapper: See http://lucene.apache.org/pylucene/
| Full text search: Whoosh Vs SOLR | I am working on a Django project, where I need to implement full text search. I have seen SOLR and found some good comments for the same. But as its implemented in Java and would need java enviroment to be installed on the system along with Python. Looking for the python equivalent for SOLR, I have seen Whoosh but I am not sure whether Whoosh is as efficient and strong as SOLR. Or shall I go with SOLR option only or are there any better options than Whoosh and SOLR with python?
Please suggest.
Thanks in advance
| [
"Whoosh is actually very fast for a python-only implementation. That said, it's still at least an order of magnitude slower. Depending on the amount of data you need to index and search and the requirements on the maximum allowable latency and concurrent searches, it may not be an option.\nSOLR is a bit of a compli... | [
16,
3
] | [] | [] | [
"django",
"python",
"solr"
] | stackoverflow_0003226596_django_python_solr.txt |
Q:
index in google app engine application
can anyone tell me how to do indexing in gql
A:
Yes Google can, http://code.google.com/appengine/docs/python/config/indexconfig.html.
Alternatively there are books on the matter http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=google+app+engine&x=0&y=0
The best way is to create your code and let the default automatic index creation take care of it.
Indexes are automatically created for ascending/descending order on each property (except for long strings and blobs) so you do not need to make these.
Due to the inherent sort ordering in Google App Engine there are many permutations (some of them impossible to do without restructuring the data models) so we would need to see your example models to help.
| index in google app engine application | can anyone tell me how to do indexing in gql
| [
"Yes Google can, http://code.google.com/appengine/docs/python/config/indexconfig.html.\nAlternatively there are books on the matter http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=google+app+engine&x=0&y=0\nThe best way is to create your code and let the default automatic index creati... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003226664_google_app_engine_python.txt |
Q:
Pass request to model form using generic view in Django
I using Django and a generic view "django.views.generic.create_update.create_object"
I have a model form wich i pass to the generic view:
url(r'^add$', create_object, {'template_name':'tpl.html','form_class':MyModelForm,'post_save_redirect':'/'},name = 'add'),
I need to get current user in my ModelForm.save method..
But i can't find way to get it, please help me to find convinient way?
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def save(self,*a,**b):
MyModel.save(user=request.user) #how can i get here request.user?
In common way the question is - how can i accsess request params in forms passed to generic view.
A:
You could probably hack something up to inject the request into the form instantiation, but why would you bother? Generic views are meant as a quick-and-easy solution to the basic requirements only. As soon as you start needing massive customisations, you might as well just write the actual view yourself. It's not very much code, after all.
A:
Look at that:
url(r'^add$', create_object_with_request, {'template_name':'tpl.html','form_class':MyModelForm,'post_save_redirect':'/'},name = 'add'),
,
def create_object_with_request(request, *args, **kwargs):
def inject_request(fun):
def helper(*args, **kwargs):
return fun(*args, request=request, **kwargs)
return helper
kwargs['form_class'] = inject_request(kwargs['form_class'])
return create_object(request, *args, **kwargs)
So you have passed request to your class constructor. Or you can add it as attribute:
def create_object_with_request(request, *args, **kwargs):
def inject_request(fun):
def helper(*args, **kwargs):
res = fun(*args, **kwargs)
res.request = request
return res
return helper
kwargs['form_class'] = inject_request(kwargs['form_class'])
return create_object(request, *args, **kwargs)
A:
thnx this helps) I have some problems this syntax and _meta attr and i finished with this
def create_object_with_request(request, *args, **kwargs):
def inject_request(fun):
def helper(*args, **kwargs):
finst = fun(*args, **kwargs)
finst.request = request
return finst
helper._meta = fun._meta
return helper
kwargs['form_class'] = inject_request(kwargs['form_class'])
return create_object(request,*args, **kwargs)
| Pass request to model form using generic view in Django | I using Django and a generic view "django.views.generic.create_update.create_object"
I have a model form wich i pass to the generic view:
url(r'^add$', create_object, {'template_name':'tpl.html','form_class':MyModelForm,'post_save_redirect':'/'},name = 'add'),
I need to get current user in my ModelForm.save method..
But i can't find way to get it, please help me to find convinient way?
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def save(self,*a,**b):
MyModel.save(user=request.user) #how can i get here request.user?
In common way the question is - how can i accsess request params in forms passed to generic view.
| [
"You could probably hack something up to inject the request into the form instantiation, but why would you bother? Generic views are meant as a quick-and-easy solution to the basic requirements only. As soon as you start needing massive customisations, you might as well just write the actual view yourself. It's not... | [
2,
1,
1
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0003224307_django_forms_python.txt |
Q:
to add column values in a specific manner in a csv file using python
i have a csv file similar to the following :
title title2 h1 h2 h3 ...
l1.1 l1 1 1 0
l1.2 l1 0 1 0
l1.3 l1 1 0 1
l2.1 l2 0 0 1
l2.2 l2 1 0 1
l3.1 l3 0 1 1
l3.2 l3 1 1 0
l3.3 l3 1 1 0
l3.4 l3 1 1 0
i want to be able to add the columns in the following manner:
h1 ( l1.1 + l1.2+ l1.3 ) = 2
h1 ( l2.1 + l2.2 ) = 1
h1 ( l3.1 + l3.2 + l3.3 +l3.4) = 3 and so on for every column
And i want the final count for every such value as a summarised table :
title2 h1 h2 h3...
l1 2 2 1
l2 1 0 2
l3 3 4 1
how do i implement this?
A:
Something like this should work. It takes an input in the form
title,title2,h1,h2,h3
l1.1,l1,1,1,0
l1.2,l1,0,1,0
l1.3,l1,1,0,1
l2.1,l2,0,0,1
l2.2,l2,1,0,1
l3.1,l3,0,1,1
l3.2,l3,1,1,0
l3.3,l3,1,1,0
l3.4,l3,1,1,0
and outputs
title2,h1,h2,h3
l1,2,2,1
l2,1,0,2
l3,3,4,1
Tested with Python 3.1.2. In Python 2.x you'll need to change the open() calls to use binary mode, and drop the newline="" bit). You can also drop the call to list() since in Python 2.x, map() already returns a list.
import csv
import operator
reader = csv.reader(open("test.csv", newline=""), dialect="excel")
result = {}
for pos, entry in enumerate(reader):
if pos == 0:
headers = entry
else:
if entry[1] in result:
result[entry[1]] = list(map(operator.add, result[entry[1]], [int(i) for i in entry[2:]]))
else:
result[entry[1]] = [int(i) for i in entry[2:]]
writer = csv.writer(open("output.txt", "w", newline=""), dialect="excel")
writer.writerow(headers[1:])
keys = sorted(result.keys())
for key in keys:
output = [key]
output.extend(result[key])
writer.writerow(output)
A:
Have a look at the csv module. What you want to do is open the file with a csv.reader. Then you iterate over the file, one row at the time. You accumulate the results of the additions into a temporary list. When you are done, you write this list to a new csv.writer.
You might need to define a dialect as you are not really using CSV but some tab-delimited format.
| to add column values in a specific manner in a csv file using python | i have a csv file similar to the following :
title title2 h1 h2 h3 ...
l1.1 l1 1 1 0
l1.2 l1 0 1 0
l1.3 l1 1 0 1
l2.1 l2 0 0 1
l2.2 l2 1 0 1
l3.1 l3 0 1 1
l3.2 l3 1 1 0
l3.3 l3 1 1 0
l3.4 l3 1 1 0
i want to be able to add the columns in the following manner:
h1 ( l1.1 + l1.2+ l1.3 ) = 2
h1 ( l2.1 + l2.2 ) = 1
h1 ( l3.1 + l3.2 + l3.3 +l3.4) = 3 and so on for every column
And i want the final count for every such value as a summarised table :
title2 h1 h2 h3...
l1 2 2 1
l2 1 0 2
l3 3 4 1
how do i implement this?
| [
"Something like this should work. It takes an input in the form\ntitle,title2,h1,h2,h3\nl1.1,l1,1,1,0\nl1.2,l1,0,1,0\nl1.3,l1,1,0,1\nl2.1,l2,0,0,1\nl2.2,l2,1,0,1\nl3.1,l3,0,1,1\nl3.2,l3,1,1,0\nl3.3,l3,1,1,0\nl3.4,l3,1,1,0\n\nand outputs\ntitle2,h1,h2,h3\nl1,2,2,1\nl2,1,0,2\nl3,3,4,1\n\nTested with Python 3.1.2. In ... | [
2,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003226656_csv_python.txt |
Q:
Python not loading a specific function
I just run into a problem with the hamster's codebase where a module is loaded with one function and not the other. It's not my code, so I don't know many details, but I'd really like to learn how can such situation arise.
There is a module called hamster which includes i18n.py which has two functions: setup_i18n and C_. There is no __all__ defined in __init__. After loading the module C_ is visible, but the setup function isn't.
Here's the link for i18n file and the repo in general: http://git.gnome.org/browse/hamster-applet/tree/src/hamster/i18n.py?id=94b8ba72dad5b3e711d5f6b6a7018d83d770ce14
The session is only this (after setting the correct sys.path to include the packages)
> from hamster import i18n
> dir(i18n)
['C_', '__builtins__', '__doc__', '__file__', '__name__', 'gettext']
A:
You have an old version of the file in your system path. Notice that the most recent change to that file in the repo is to add the setup_i18n function. It's also possible you have an old .pyc file that for some reason isn't being compared properly to the .py file.
| Python not loading a specific function | I just run into a problem with the hamster's codebase where a module is loaded with one function and not the other. It's not my code, so I don't know many details, but I'd really like to learn how can such situation arise.
There is a module called hamster which includes i18n.py which has two functions: setup_i18n and C_. There is no __all__ defined in __init__. After loading the module C_ is visible, but the setup function isn't.
Here's the link for i18n file and the repo in general: http://git.gnome.org/browse/hamster-applet/tree/src/hamster/i18n.py?id=94b8ba72dad5b3e711d5f6b6a7018d83d770ce14
The session is only this (after setting the correct sys.path to include the packages)
> from hamster import i18n
> dir(i18n)
['C_', '__builtins__', '__doc__', '__file__', '__name__', 'gettext']
| [
"You have an old version of the file in your system path. Notice that the most recent change to that file in the repo is to add the setup_i18n function. It's also possible you have an old .pyc file that for some reason isn't being compared properly to the .py file.\n"
] | [
6
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0003227573_import_module_python.txt |
Q:
need help in understanding the code
class Problem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented terminology: an abstract class).
"""
def getStartState(self):
"""Returns the start state for the search problem"""
sahan.raiseNotDefined()
Now I want to know the meaning of above code? can I use the functions defined in the class in some other class functions as it is?
What does the class doc string mean?
A:
This class is an attempt to define an abstract base class, this is what would be an Interface in Java or a class with only pure virtual methods in C++. Essentially it is defining the contract for a group of classes but not providing the implementation. The users of this class will implement the behaviour in subclasses. This class is an attempt to programmatically document an interface and make it clear that it cannot be used.
Creating interfaces that users will extend is good practice in general but it is commonly done when creating a framework. The core of the framework provides some useful common behaviour written to the interface, with users of the framework implementing the behaviour to achieve their specific goals.
Python being a dynamically typed language historically did not have direct support for abstract base class. However the need for them has always been tacitly acknowledged with some high profile frameworks providing their own support the concept. This idea has finally been formalised in the Abstract Base Classes (abc) standard library module.
A:
def getStartState(self) is a stubbed method; it's fully declared, but doesn't really "do" anything functional at the moment.
When invoked, it will raise an exception. Subclasses need to implement this method with actual functional code in order to get things to work properly.
See also
Wikipedia/Method stub
Wikipedia/Abstract type
A:
class Problem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented terminology: an abstract class).
"""
def getStartState(self):
"""
Returns the start state for the search problem
"""
pass
Would allow you to use this class and denote that it is not yet defined.
By raising a notDefinedError you are explicitly stating that this code will fail when you try and use the class (instead of silently failing when you try and use its methods).
Python has a built-in exception for this called NotImplementedError.
class Problem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented terminology: an abstract class).
"""
def getStartState(self):
"""
Returns the start state for the search problem
"""
raise NotImplementedError()
The class doc is basically stating that this is an interface to be followed, an abstract class, and that you are to either inherit class this or override the function there and then.
| need help in understanding the code | class Problem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented terminology: an abstract class).
"""
def getStartState(self):
"""Returns the start state for the search problem"""
sahan.raiseNotDefined()
Now I want to know the meaning of above code? can I use the functions defined in the class in some other class functions as it is?
What does the class doc string mean?
| [
"This class is an attempt to define an abstract base class, this is what would be an Interface in Java or a class with only pure virtual methods in C++. Essentially it is defining the contract for a group of classes but not providing the implementation. The users of this class will implement the behaviour in subcla... | [
2,
1,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003226928_oop_python.txt |
Q:
GAE: Is it necessary to call fetch on a query before getting its cursor?
When the following code is executed:
q = MyKind.all()
taskqueue.add(url="/admin/build", params={'cursor': q.cursor()})
I get:
AssertionError: No cursor available.
Why does this happen? Do I need to fetch something first? (I'd rather not; the code is cleaner just to get the query and pass it on.)
I'm using Python on Google App Engine 1.3.5.
A:
Yes, a cursor is only available if you've fetched something; there's no cursor for the first result in the query.
As a workaround, you could wrap the call to cursor() in a try/except and pass on None to the next task if there isn't a cursor available.
| GAE: Is it necessary to call fetch on a query before getting its cursor? | When the following code is executed:
q = MyKind.all()
taskqueue.add(url="/admin/build", params={'cursor': q.cursor()})
I get:
AssertionError: No cursor available.
Why does this happen? Do I need to fetch something first? (I'd rather not; the code is cleaner just to get the query and pass it on.)
I'm using Python on Google App Engine 1.3.5.
| [
"Yes, a cursor is only available if you've fetched something; there's no cursor for the first result in the query.\nAs a workaround, you could wrap the call to cursor() in a try/except and pass on None to the next task if there isn't a cursor available.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003226188_google_app_engine_google_cloud_datastore_python.txt |
Q:
Matching all records in a datastore query
Is there a way to substitute:
def get_objects(attr1,attr2,..):
objects = Entities.all()
if attr1 != None:
objects.filter('attr1',attr1)
if attr2 != None:
objects.filter('attr2',attr2)
....
return objects
With a single query:
Entities.all().filter('attr1',attr1).filter('attr2',attr2)
By using some sort of 'match all' sign ( maybe a regexp query )?
The problem with the first query is that ( apart from being ugly ) it creates indexes for all possible filter sequences.
A:
The datastore doesn't support regex queries or OR queries.
However, if you're only using equality filters, indexes shouldn't be automatically created; these types of queries can be served using a merge-join strategy as long as the number of filters remains low (if you try to add too many filters, you'll get an error indicating that the existing indexes can't be used to execute the query efficiently; however, trying to add the required indexes in a case like this will usually result in the exploding indexes problem.)
The ugliness in the first approach can probably be solved by passing a list to your function instead of individual variables, then using a list comprehension instead of a bunch of if statements.
| Matching all records in a datastore query | Is there a way to substitute:
def get_objects(attr1,attr2,..):
objects = Entities.all()
if attr1 != None:
objects.filter('attr1',attr1)
if attr2 != None:
objects.filter('attr2',attr2)
....
return objects
With a single query:
Entities.all().filter('attr1',attr1).filter('attr2',attr2)
By using some sort of 'match all' sign ( maybe a regexp query )?
The problem with the first query is that ( apart from being ugly ) it creates indexes for all possible filter sequences.
| [
"The datastore doesn't support regex queries or OR queries.\nHowever, if you're only using equality filters, indexes shouldn't be automatically created; these types of queries can be served using a merge-join strategy as long as the number of filters remains low (if you try to add too many filters, you'll get an er... | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"web_applications"
] | stackoverflow_0003226775_google_app_engine_google_cloud_datastore_python_web_applications.txt |
Q:
Pylons importing Psycopg2 error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.6/site-packages/psycopg2/__init__.py", line 60, in <module>
from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: dlopen(/Library/Python/2.6/site-packages/psycopg2/_psycopg.so, 2): Symbol not found: _PQbackendPID
Referenced from: /Library/Python/2.6/site-packages/psycopg2/_psycopg.so
Expected in: flat namespace
in /Library/Python/2.6/site-packages/psycopg2/_psycopg.so
Psycopg2 was working fine before, but now I get this error.
Any ideas on this issue much appreciated.
EDIT: so after dealing with so many psycopg2 errors everytime I set up my mac, I've decided to use VMWareFusion running Ubuntu instead.
A:
You get this error because your 64-bit version of python can't find a 64-bit psycopg2.
You can either downgrade your python to run in 32-bit mode or try to get a 64-bit psycopg2. There is more discussion on this topic over on Ben Kreeger's blog.
A:
Could it be that the postgres installation was removed/updated? The symbol is supposed to come from libpq.
A:
This is broken for me too, and in my case it doesn't appear to be a 32 vs 64 bit issue:
decibel@workbook.1[6:55]~/src:85%file /opt/local/lib/postgresql83/libpq.dylib
/opt/local/lib/postgresql83/libpq.dylib: Mach-O 64-bit dynamically linked shared library x86_64
decibel@workbook.1[6:56]~/src:86%file ~/.python-eggs/psycopg2-2.0.14-py2.6-macosx-10.6-universal.egg-tmp/psycopg2/_psycopg.so
/Users/decibel/.python-eggs/psycopg2-2.0.14-py2.6-macosx-10.6-universal.egg-tmp/psycopg2/_psycopg.so: Mach-O universal binary with 3 architectures
/Users/decibel/.python-eggs/psycopg2-2.0.14-py2.6-macosx-10.6-universal.egg-tmp/psycopg2/_psycopg.so (for architecture i386): Mach-O bundle i386
/Users/decibel/.python-eggs/psycopg2-2.0.14-py2.6-macosx-10.6-universal.egg-tmp/psycopg2/_psycopg.so (for architecture ppc7400): Mach-O bundle ppc
/Users/decibel/.python-eggs/psycopg2-2.0.14-py2.6-macosx-10.6-universal.egg-tmp/psycopg2/_psycopg.so (for architecture x86_64): Mach-O 64-bit bundle x86_64
decibel@workbook.1[6:56]~/src:87%
A:
resolved similar issue by forcing Apache executables 32 bit execution
| Pylons importing Psycopg2 error | Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.6/site-packages/psycopg2/__init__.py", line 60, in <module>
from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: dlopen(/Library/Python/2.6/site-packages/psycopg2/_psycopg.so, 2): Symbol not found: _PQbackendPID
Referenced from: /Library/Python/2.6/site-packages/psycopg2/_psycopg.so
Expected in: flat namespace
in /Library/Python/2.6/site-packages/psycopg2/_psycopg.so
Psycopg2 was working fine before, but now I get this error.
Any ideas on this issue much appreciated.
EDIT: so after dealing with so many psycopg2 errors everytime I set up my mac, I've decided to use VMWareFusion running Ubuntu instead.
| [
"You get this error because your 64-bit version of python can't find a 64-bit psycopg2.\nYou can either downgrade your python to run in 32-bit mode or try to get a 64-bit psycopg2. There is more discussion on this topic over on Ben Kreeger's blog.\n",
"Could it be that the postgres installation was removed/updat... | [
4,
1,
1,
1
] | [] | [] | [
"psycopg2",
"pylons",
"python"
] | stackoverflow_0001623449_psycopg2_pylons_python.txt |
Q:
Is the Python Imaging Library not available on PyPI, or am I missing something?
easy_install pil results in an error:
Searching for pil
Reading http://pypi.python.org/simple/pil/
Reading http://www.pythonware.com/products/pil
Reading http://effbot.org/zone/pil-changes-115.htm
Reading http://effbot.org/downloads/#Imaging
No local packages or download links found for pil
error: Could not find suitable distribution for Requirement.parse(‘pil’)
Any ideas?
--
UPDATE:
Hm, asking it to find-links on the Python Ware site seems to be working:
easy_install -f http://www.pythonware.com/products/pil/ Imaging
Got a heap of warnings along the way though. I’ll see how it turns out.
--
UPDATE: I can import it in Python using import Image, but when I tell Django to syncdb I still get the following error:
Error: One or more models did not validate:
core.userprofile: “avatar”: To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ .
I'm using an ImageField in one of my models.
A:
Of course PIL is on PyPi! Specifically, it's right here.
A:
easy_install is case-sensitive. The package is under PIL.
A:
workaround is in easy_install PIL egg directory create link to this directory in name "PIL"
A:
import Image
Django tries to import PIL directly:
from PIL import Image
You should check presence of PIL directory in your site-packages
A:
from http://code.djangoproject.com/ticket/6054
It seems that there is something wrong with easy_install which installs PIL in the root namespace, installing from sources fixes this, strange.
| Is the Python Imaging Library not available on PyPI, or am I missing something? | easy_install pil results in an error:
Searching for pil
Reading http://pypi.python.org/simple/pil/
Reading http://www.pythonware.com/products/pil
Reading http://effbot.org/zone/pil-changes-115.htm
Reading http://effbot.org/downloads/#Imaging
No local packages or download links found for pil
error: Could not find suitable distribution for Requirement.parse(‘pil’)
Any ideas?
--
UPDATE:
Hm, asking it to find-links on the Python Ware site seems to be working:
easy_install -f http://www.pythonware.com/products/pil/ Imaging
Got a heap of warnings along the way though. I’ll see how it turns out.
--
UPDATE: I can import it in Python using import Image, but when I tell Django to syncdb I still get the following error:
Error: One or more models did not validate:
core.userprofile: “avatar”: To use ImageFields, you need to install the Python Imaging Library. Get it at http://www.pythonware.com/products/pil/ .
I'm using an ImageField in one of my models.
| [
"Of course PIL is on PyPi! Specifically, it's right here.\n",
"easy_install is case-sensitive. The package is under PIL.\n",
"workaround is in easy_install PIL egg directory create link to this directory in name \"PIL\"\n",
"\nimport Image\n\nDjango tries to import PIL directly:\nfrom PIL import Image\n\nYou... | [
5,
1,
1,
0,
0
] | [] | [] | [
"django",
"python",
"python_imaging_library"
] | stackoverflow_0000994281_django_python_python_imaging_library.txt |
Q:
Python images display Django
Since my last question here: Python images display
I understood that from all the answers I got the glob.glob could be the only one in the direction I need.
However where I am stuck right now is here:
I can create a list with all the filenames in my media directory by using glob.glob:
all = glob.glob("/Path_to_MEDIA/*/*.jpg")
But how can I use that and create a VERY SIMPLE image display with one next button that calls files in my MEDIA_ROOT and displays them.
What I know is:
I have a Template which looks something like the default directory index:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="en-us" />
<meta name="robots" content="NONE,NOARCHIVE" />
<title>Index of {{ directory }}</title>
</head>
<body>
<h1>Index of {{ directory }}</h1>
<ul>
{% ifnotequal directory "/" %}
<li><a href="../">../</a></li>
{% endifnotequal %}
{% for f in file_list %}
<li><a href="{{ f|urlencode }}">{{ f }}</a></li>
{% endfor %}
</ul>
</body>
</html>
I need to create a def in my views that feeds the list from glob.glob to this or similar template.
What I dont know:
How does this def in the view have to look like?
And here:
What do I have to write to display one image, sound in a browser?
What do I have to write to display a LIST of images, sounds?
Thanks for the time!
A:
Make a direct-to-template url with extra-context in urls.py:
from django.views.generic.simple import direct_to_template
...
url(r'^whatever', direct_to_template,
{ 'template':'foo.html', 'extra_context': {'files':myfiles} }
name='whatever' ),
Where myfiles above is a list/tuple of your files. However, make sure to format your file list in terms of MEDIA_URL instead of based on MEDIA_PATH. For example:
myfiles = [ 'relative/path/foo.jpg',
'http://static.mysite.com/absolute/path/bar.jpg' ]
Though, obviously generated from the filesystem in your case, not a hardcoded list. And you could do the work in a view rather than using direct-to-template -- just make sure to put the files key/value into your context:
def myview( request ... ):
context = RequestContext(request)
context[files]=myfiles
return render_to_respone( ..., context_instance=context )
Then, in your template foo.html:
{% for file in files %}
<img src='YOUR_MEDIA_URL_HERE/{{ file }}' />
{% endfor %}
| Python images display Django | Since my last question here: Python images display
I understood that from all the answers I got the glob.glob could be the only one in the direction I need.
However where I am stuck right now is here:
I can create a list with all the filenames in my media directory by using glob.glob:
all = glob.glob("/Path_to_MEDIA/*/*.jpg")
But how can I use that and create a VERY SIMPLE image display with one next button that calls files in my MEDIA_ROOT and displays them.
What I know is:
I have a Template which looks something like the default directory index:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="en-us" />
<meta name="robots" content="NONE,NOARCHIVE" />
<title>Index of {{ directory }}</title>
</head>
<body>
<h1>Index of {{ directory }}</h1>
<ul>
{% ifnotequal directory "/" %}
<li><a href="../">../</a></li>
{% endifnotequal %}
{% for f in file_list %}
<li><a href="{{ f|urlencode }}">{{ f }}</a></li>
{% endfor %}
</ul>
</body>
</html>
I need to create a def in my views that feeds the list from glob.glob to this or similar template.
What I dont know:
How does this def in the view have to look like?
And here:
What do I have to write to display one image, sound in a browser?
What do I have to write to display a LIST of images, sounds?
Thanks for the time!
| [
"Make a direct-to-template url with extra-context in urls.py:\nfrom django.views.generic.simple import direct_to_template\n...\nurl(r'^whatever', direct_to_template, \n { 'template':'foo.html', 'extra_context': {'files':myfiles} }\n name='whatever' ),\n\nWhere myfiles above is a list... | [
0
] | [] | [] | [
"django",
"image",
"python"
] | stackoverflow_0003228342_django_image_python.txt |
Q:
Using PIL and NumPy to convert an image to Lab array, modify the values and then convert back
I am trying to convert a PIL image into an array using NumPy. I then want to convert that array into Lab values, modify the values and then convert the array back in to an image and save the image. I have the following code:
import Image, color, numpy
# Open the image file
src = Image.open("face-him.jpg")
# Attempt to ensure image is RGB
src = src.convert(mode="RGB")
# Create array of image using numpy
srcArray = numpy.asarray(src)
# Convert array from RGB into Lab
srcArray = color.rgb2lab(srcArray)
# Modify array here
# Convert array back into Lab
end = color.lab2rgb(srcArray)
# Create image from array
final = Image.fromarray(end, "RGB")
# Save
final.save("out.jpg")
This code is dependent on PIL, NumPy and color. color can be found in the SciPy trunk here. I downloaded the color.py file along with certain colordata .txt files. I modified the color.py so that it can run independently from the SciPy source and it all seems to work fine - values in the array are changed when I run conversions.
My problem is that when I run the above code which simply converts an image to Lab, then back to RGB and saves it I get the following image back:
What is going wrong? Is it the fact I am using the functions from color.py?
For reference:
Source Image - face-him.jpg
All source files required to test - colour-test.zip
A:
Without having tried it, scaling errors are common in converting colors:
RGB is bytes 0 .. 255, e.g. yellow [255,255,0],
whereas rgb2xyz() etc. work on triples of floats, yellow [1.,1.,0].
(color.py has no range checks: lab2rgb( rgb2lab([255,255,0]) ) is junk.)
In IPython, %run main.py, then print corners of srcArray and end ?
Added 13July: for the record / for google, here are NumPy idioms to pack, unpack and convert RGB image arrays:
# unpack image array, 10 x 5 x 3 -> r g b --
img = np.arange( 10*5*3 ).reshape(( 10,5,3 ))
print "img.shape:", img.shape
r,g,b = img.transpose( 2,0,1 ) # 3 10 5
print "r.shape:", r.shape
# pack 10 x 5 r g b -> 10 x 5 x 3 again --
rgb = np.array(( r, g, b )).transpose( 1,2,0 ) # 10 5 3 again
print "rgb.shape:", rgb.shape
assert (rgb == img).all()
# rgb 0 .. 255 <-> float 0 .. 1 --
imgfloat = img.astype(np.float32) / 255.
img8 = (imgfloat * 255).round().astype(np.uint8)
assert (img == img8).all()
A:
As Denis pointed out, there are no range checks in lab2rgb or rgb2lab, and rgb2lab appears to expect values in the range [0,1].
>>> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> color.lab2rgb(color.rgb2lab(a))
array([[ -1.74361805e-01, 1.39592186e-03, 1.24595808e-01],
[ 1.18478213e+00, 1.15700655e+00, 1.13767806e+00],
[ 2.62956273e+00, 2.38687422e+00, 2.21535897e+00]])
>>> from __future__ import division
>>> b = a/10
>>> b
array([[ 0.1, 0.2, 0.3],
[ 0.4, 0.5, 0.6],
[ 0.7, 0.8, 0.9]])
>>> color.lab2rgb(color.rgb2lab(a))
array([[ 0.1, 0.2, 0.3],
[ 0.4, 0.5, 0.6],
[ 0.7, 0.8, 0.9]])
In color.py, the xyz2lab and lab2xyz functions are doing some math that I can't deduce at a glance (I'm not that familiar with numpy or image transforms).
Edit (this code fixes the problem):
PIL gives you numbers [0,255], try scaling those down to [0,1] before passing to the rgb2lab function and back up when coming out. e.g.:
#from __future__ import division # (if required)
[...]
# Create array of image using numpy
srcArray = numpy.asarray(src)/255
# Convert array from RGB into Lab
srcArray = color.rgb2lab(srcArray)
# Convert array back into Lab
end = color.lab2rgb(srcArray)*255
end = end.astype(numpy.uint8)
| Using PIL and NumPy to convert an image to Lab array, modify the values and then convert back | I am trying to convert a PIL image into an array using NumPy. I then want to convert that array into Lab values, modify the values and then convert the array back in to an image and save the image. I have the following code:
import Image, color, numpy
# Open the image file
src = Image.open("face-him.jpg")
# Attempt to ensure image is RGB
src = src.convert(mode="RGB")
# Create array of image using numpy
srcArray = numpy.asarray(src)
# Convert array from RGB into Lab
srcArray = color.rgb2lab(srcArray)
# Modify array here
# Convert array back into Lab
end = color.lab2rgb(srcArray)
# Create image from array
final = Image.fromarray(end, "RGB")
# Save
final.save("out.jpg")
This code is dependent on PIL, NumPy and color. color can be found in the SciPy trunk here. I downloaded the color.py file along with certain colordata .txt files. I modified the color.py so that it can run independently from the SciPy source and it all seems to work fine - values in the array are changed when I run conversions.
My problem is that when I run the above code which simply converts an image to Lab, then back to RGB and saves it I get the following image back:
What is going wrong? Is it the fact I am using the functions from color.py?
For reference:
Source Image - face-him.jpg
All source files required to test - colour-test.zip
| [
"Without having tried it, scaling errors are common in converting colors:\nRGB is bytes 0 .. 255, e.g. yellow [255,255,0],\nwhereas rgb2xyz() etc. work on triples of floats, yellow [1.,1.,0].\n(color.py has no range checks: lab2rgb( rgb2lab([255,255,0]) ) is junk.)\nIn IPython, %run main.py, then print corners of s... | [
10,
7
] | [] | [] | [
"color_space",
"colors",
"numpy",
"python",
"python_imaging_library"
] | stackoverflow_0003228361_color_space_colors_numpy_python_python_imaging_library.txt |
Q:
google app engine ApplicationError: 2 nonnumeric port: ''
I am getting the ApplicationError: 2 nonnumeric port: '' randomly for about 1/10th of my url request, the rest work fine, I seen this is a bug but I have yet to find any solutions, anyone have any thoughts in why this is occurring? I am running python 2.5.4 and google app engine 1.3.3
here is some generic code the error is occuring when requesting pages randomly
def overview(page):
try:
page = "http://www.url.com%s.json?" %page
u = urllib.urlopen(page.encode('utf-8'))
bytes = StringIO(u.read())
u.close()
except Exception, e:
print e
return None
try:
JSON_data = json.load(bytes)
return JSON_data
except ValueError:
print "Couldn't get .json for %s" % page
return None
A:
Couple of things with your code that could be problems. One is that you aren't doing anything with the incoming value of page, but it is being over-written by the assignment fort thing inside your try block. Also, as I noted in my comment, the %s in the assignment wants to have a variable to substitute in its place. That's probably what you are meant to to with the value coming in the page parameter. Try this:
def overview(page_to_get):
try:
page = "http://www.url.com%s.json?" % page_to_get
u = urllib.urlopen(page.encode('utf-8'))
bytes = StringIO(u.read())
u.close()
except Exception, e:
print e
return None
try:
JSON_data = json.load(bytes)
return JSON_data
except ValueError:
print "Couldn't get .json for %s" % page
return None
EDIT:
@user291071: I would guess that some of that values that are coming in through overview's parameter page do not start with a leading slash. The only way to make sure that the URL parser doesn't try to interpret the added-on information as a port-number is to make sure that it starts with a / or a ?. perhaps this will work better for you:
page = "http://www.url.com/%s.json?" % page_to_get
but it may cause other URLs that are currently working to fail. The best thing to do would be to log the URLs that are being created and visually inspect the ones that are failing.
| google app engine ApplicationError: 2 nonnumeric port: '' | I am getting the ApplicationError: 2 nonnumeric port: '' randomly for about 1/10th of my url request, the rest work fine, I seen this is a bug but I have yet to find any solutions, anyone have any thoughts in why this is occurring? I am running python 2.5.4 and google app engine 1.3.3
here is some generic code the error is occuring when requesting pages randomly
def overview(page):
try:
page = "http://www.url.com%s.json?" %page
u = urllib.urlopen(page.encode('utf-8'))
bytes = StringIO(u.read())
u.close()
except Exception, e:
print e
return None
try:
JSON_data = json.load(bytes)
return JSON_data
except ValueError:
print "Couldn't get .json for %s" % page
return None
| [
"Couple of things with your code that could be problems. One is that you aren't doing anything with the incoming value of page, but it is being over-written by the assignment fort thing inside your try block. Also, as I noted in my comment, the %s in the assignment wants to have a variable to substitute in its plac... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003229019_google_app_engine_python.txt |
Q:
Checking whether a link is dead or not using Python without downloading the webpage
For those who know wget, it has a option --spider, which allows one to check whether a link is broke or not, without actually downloading the webpage. I would like to do the same thing in Python. My problem is that I have a list of 100'000 links I want to check, at most once a day, and at least once a week. In any case this will generate a lot of unnecessary traffic.
As far as I understand from the urllib2.urlopen() documentation, it does not download the page but only the meta-information. Is this correct? Or is there some other way to do this in a nice manner?
Best,
Troels
A:
You should use the HEAD Request for this, it asks the webserver for the headers without the body. See How do you send a HEAD HTTP request in Python 2?
| Checking whether a link is dead or not using Python without downloading the webpage | For those who know wget, it has a option --spider, which allows one to check whether a link is broke or not, without actually downloading the webpage. I would like to do the same thing in Python. My problem is that I have a list of 100'000 links I want to check, at most once a day, and at least once a week. In any case this will generate a lot of unnecessary traffic.
As far as I understand from the urllib2.urlopen() documentation, it does not download the page but only the meta-information. Is this correct? Or is there some other way to do this in a nice manner?
Best,
Troels
| [
"You should use the HEAD Request for this, it asks the webserver for the headers without the body. See How do you send a HEAD HTTP request in Python 2?\n"
] | [
9
] | [
"Not sure how to do this in python but generally you could check 'Response Header' and check 'Status-Code' for code 200. at that point you could stop reading the page and continue with your next link that way you don't have to download the whole page just the 'Response Header'\nList of Status Codes\n"
] | [
-1
] | [
"python",
"urllib2"
] | stackoverflow_0003229607_python_urllib2.txt |
Q:
import pyodbc results in DLL load failed with error code 193 on Win7
I am running 64-bit Windows 7 and the ActiveState Python 2.5 installation (64-bit version). I just downloaded and installed the pyodbc 2.1.7 win32 package. When I run the installer as an admin it proceeds with no problem. When I run python and try
import pyodbc
I receive the following error:
ImportError: DLL load failed with
error code 193
I'm thinking it has to do with having the 64-bit version of ActiveState Python installed. Do I need to remove that and replace it with the 32-bit ActiveState Python installation? Would that be the preferred way of doing things until more python packages have 64-bit support?
A:
It shouldn't be too difficult to build yourself. I know pyodbc supports 64 bit (I worked with the author a bit adding 64 bit support a couple years ago). If unzip the source zip, you can run:
setup.py bdist_wininst
Of course for Python 2.5, I think you'll need Visual Studio 2003, that's probably a deal-breaker. With python>=2.6, you could do it with Visual Studio Express 2008.
| import pyodbc results in DLL load failed with error code 193 on Win7 | I am running 64-bit Windows 7 and the ActiveState Python 2.5 installation (64-bit version). I just downloaded and installed the pyodbc 2.1.7 win32 package. When I run the installer as an admin it proceeds with no problem. When I run python and try
import pyodbc
I receive the following error:
ImportError: DLL load failed with
error code 193
I'm thinking it has to do with having the 64-bit version of ActiveState Python installed. Do I need to remove that and replace it with the 32-bit ActiveState Python installation? Would that be the preferred way of doing things until more python packages have 64-bit support?
| [
"It shouldn't be too difficult to build yourself. I know pyodbc supports 64 bit (I worked with the author a bit adding 64 bit support a couple years ago). If unzip the source zip, you can run:\nsetup.py bdist_wininst \n\nOf course for Python 2.5, I think you'll need Visual Studio 2003, that's probably a deal-brea... | [
1
] | [] | [] | [
"64_bit",
"pyodbc",
"python",
"windows_7"
] | stackoverflow_0003229471_64_bit_pyodbc_python_windows_7.txt |
Q:
Python Language Nuances
Possible Duplicate:
Common Pitfalls in Python
I'm learning Python and I come from a diverse background of programming languages. In the last five years, I've written quite a bit of Java, C++, VB.Net, and PHP. As many of you might agree, once you learn one programming language, learning another is just a mater of learning the differences in syntax and best practices.
Coming down from PHP, I've become very accustomed to a lot of script-style language features. For instance, stuff like this tickles me insides:
# Retrieve the value from the cache; otherwise redownload.
if(!($value = $cache->get($key)))
# Redownload the value and store in the cache.
$cache->set($key, $value = redownload($key));
Python, though, doesn't consider assignment to be an expression. OTOH, it does support nice things like the in construct, which I find to be one of the greatest inventions of all time. x in y is so much nicer than !empty($y[$x]).
What other nuances, "missing" features, and performance bottlenecks should I watch out for? I'm hoping to make as seamless a transition into Python development as possible, and hope to learn some of the secrets that will help to smooth out development time and eliminate trial and error. Your insight is appreciated!
A:
This one took me a few hours to figure out when I first encountered it in a real program:
A default argument to a function is a mutable, static value.
def foo(bar = []):
bar.append(1)
print(bar)
foo()
foo()
This will print
[1]
[1, 1]
A:
For your example, the usual way would be something like this
try:
value = cache[key]
except KeyError:
value = cache[key] = redownload(key)
A:
Threads do not do what you think they do, and probably shouldn't be used how you're used to using them. This is a huge gotcha for many people, especially for those used to Java where the custom is to subclass Thread implement the Runnable interface to do asynchronous work, and where there is language support for running threads in parallel (on machines with multiple CPU cores).
In general you probably don't want threads at all, but subprocesses. See my answer to the question "python threading and performace?".
(In more general, there might be a better way altogether.)
A:
Exceptions are your friend.
In contrast with languages like C and PHP which use the return value to indicate errors, Python uses exceptions to interrupt the program instead of allowing the errors to cause further problems down the line.
A:
Pythonic code is usually much faster than C-like code.
Something like:
new_list=[]
for i in xrange(len(old_list)):
new_list.append(some_function(old_list[i]))
is better written as:
new_list=[some_function(x) for x in old_list]
or
new_list=map(some_function,old_list)
| Python Language Nuances |
Possible Duplicate:
Common Pitfalls in Python
I'm learning Python and I come from a diverse background of programming languages. In the last five years, I've written quite a bit of Java, C++, VB.Net, and PHP. As many of you might agree, once you learn one programming language, learning another is just a mater of learning the differences in syntax and best practices.
Coming down from PHP, I've become very accustomed to a lot of script-style language features. For instance, stuff like this tickles me insides:
# Retrieve the value from the cache; otherwise redownload.
if(!($value = $cache->get($key)))
# Redownload the value and store in the cache.
$cache->set($key, $value = redownload($key));
Python, though, doesn't consider assignment to be an expression. OTOH, it does support nice things like the in construct, which I find to be one of the greatest inventions of all time. x in y is so much nicer than !empty($y[$x]).
What other nuances, "missing" features, and performance bottlenecks should I watch out for? I'm hoping to make as seamless a transition into Python development as possible, and hope to learn some of the secrets that will help to smooth out development time and eliminate trial and error. Your insight is appreciated!
| [
"This one took me a few hours to figure out when I first encountered it in a real program:\nA default argument to a function is a mutable, static value.\ndef foo(bar = []):\n bar.append(1)\n print(bar)\n\nfoo()\nfoo()\n\nThis will print\n[1]\n[1, 1]\n\n",
"For your example, the usual way would be something like... | [
4,
3,
2,
1,
0
] | [] | [] | [
"pep8",
"performance",
"python"
] | stackoverflow_0003226650_pep8_performance_python.txt |
Q:
HTTP Auth coordinated by web application rather than server
I'm working with Django on Linux and I have an application that integrates with Active Directory. I'm seeking opinions and advice about whether or not it would be feasible or reasonable to access the HTTP headers from within the application to coordinate HTTP authentication.
The end goal would be to perform NTLM authentication without a password, which I accept may be quite a bit of work and research.
Note, this is a more general version of my original question, which received no answers.
A:
Sure. Just return a HttpResponse with a 401 status code, and tell your web server-Django connector to let the auth headers through.
| HTTP Auth coordinated by web application rather than server | I'm working with Django on Linux and I have an application that integrates with Active Directory. I'm seeking opinions and advice about whether or not it would be feasible or reasonable to access the HTTP headers from within the application to coordinate HTTP authentication.
The end goal would be to perform NTLM authentication without a password, which I accept may be quite a bit of work and research.
Note, this is a more general version of my original question, which received no answers.
| [
"Sure. Just return a HttpResponse with a 401 status code, and tell your web server-Django connector to let the auth headers through.\n"
] | [
1
] | [] | [] | [
"authentication",
"django",
"http",
"http_authentication",
"python"
] | stackoverflow_0003229783_authentication_django_http_http_authentication_python.txt |
Q:
Debugger for google appengine python
I am developing for appengine python on windows 7. I am looking for a set up that will allow me to debug my python scripts. I would prefer a GUI based defugger as opposed to command line one. Something like eclipse provides.
A:
If non-free (as beer) is a option, WingIDE is a very powerful Python IDE, especially It's new version 4 (still in beta) puts focus on Django Debug support.
It's a GUI based Debugger as you want, and has a how-to for "Using Wing IDE with the Google App Engine"
A:
Aptana is an Eclipse modification, you can use it for several languages.
Aptana ( http://www.aptana.com/products/studio2/download) + pydev (aptana/myaptana/plugins/Aptana Pydev/Get It).
And Netbeans is Able to debug python too... http://netbeans.org , but a little bit complicated to download the nbm...
A:
http://www.gnu.org/software/ddd/
| Debugger for google appengine python | I am developing for appengine python on windows 7. I am looking for a set up that will allow me to debug my python scripts. I would prefer a GUI based defugger as opposed to command line one. Something like eclipse provides.
| [
"If non-free (as beer) is a option, WingIDE is a very powerful Python IDE, especially It's new version 4 (still in beta) puts focus on Django Debug support.\nIt's a GUI based Debugger as you want, and has a how-to for \"Using Wing IDE with the Google App Engine\"\n",
"Aptana is an Eclipse modification, you can us... | [
2,
1,
0
] | [] | [] | [
"debugging",
"google_app_engine",
"python"
] | stackoverflow_0003229702_debugging_google_app_engine_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.