text
stringlengths 226
34.5k
|
---|
Accessing Local Variables Inside a Python Generator
Question: How would you access a local variable defined inside a Python generator from
outside the generator?
I have a case where my generator manipulates a local state, and for unittests
I want to inspect this state to ensure it contains the correct values.
I can't store the state to an instance variable (e.g. self.state = blah),
because I might be creating multiple generators from the same class instance,
meaning the generators might overwrite each other's state. I also can't return
the state in the yield expression, because the state name may change or vary
because individual generator instances.
e.g. I want to do something like this (albeit this code doesn't work)
from random import random
class MyIter(object):
def __iter__(self):
context = {}
for i in xrange(10):
context[random()] = random()
yield i
obj = MyIter()
i1 = iter(obj)
i2 = iter(obj)
while 1:
try:
i1.next()
i2.next()
print i1.context
print i2.context
except StopIteration:
break
Is there anyway to access local variables by inspecting Python's execution
stack?
Answer: Sorry to answer my own question, but after digging into the generator
interface, I found the exact path I need to access the generator's local
variables:
from random import random
class MyIter(object):
def __iter__(self):
context = {}
for i in xrange(10):
context[random()] = random()
yield i
obj = MyIter()
i1 = iter(obj)
i2 = iter(obj)
while 1:
try:
i1.next()
i2.next()
print i1.gi_frame.f_locals['context']
print i2.gi_frame.f_locals['context']
except StopIteration:
break
|
Inversion of Control: Have you ever had to decide what Dependency Injection framework is best for a project? Which one did you pick and why?
Question: Rather than triggering a flamewar on what DI framework is "best" (I don't
think there's a definitive general solution), this question is meant to
discuss good alternatives for projects of different kinds, no matter the
programming language, based on professional experience.
Some issues I'd like to lean about:
* What were the most important features you were looking for in a DI framework? Why was it what best fitted your project?
* What does the DI framework have that others do not? What makes it special?
* Why would you not pick the same DI framework for other different projects?
* How did the DI framework improve the testability and configuration flexibility of the application (especially on different environments: development, staging, production, etc.)?
* Many DI frameworks are said to be simple. But how easy is it to maintain the configuration of dependencies? (For example: Is it too verbose or difficult to read and modify?)
I may eventually accept one answer, but there is no "best answer" on this
topic. I would appreciate anyone's experience that is useful to share.
I'm particularly interested in experience with DI frameworks in Python and
PHP, where I think the choice isn't very straight-forward. The question is
language-agnostic, though.
Answer: I usually choose frameworks, whether DI or otherwise, using the following
criteria:
1. Pick a framework that has the required functionality for the job at hand
2. Prefer frameworks that are simple - The less "extra" stuff not required for 1., the better.
3. Prefer frameworks "built-in" to the language/framework you're already using.
4. Prefer frameworks that I already know and have used
Usually, by working through the above, it's pretty obvious. For example, the
last DI framework I choose was MEF, mainly because it was a C# project (point
3.), it's simple, and it did what I needed it to do.
|
Any easy way to plot a 3d scatter in Python that I can rotate around?
Question: Currently I'm using matplotlib to plot a 3d scatter and while it gets the job
done, I can't seem to find a way to rotate it to see my data better.
Here's an example:
import pylab as p
import mpl_toolkits.mplot3d.axes3d as p3
#data is an ndarray with the necessary data and colors is an ndarray with
#'b', 'g' and 'r' to paint each point according to its class
...
fig=p.figure()
ax = p3.Axes3D(fig)
ax.scatter(data[:,0], data[:,2], data[:,3], c=colors)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
fig.add_axes(ax)
p.show()
I'd like a solution that lets me do it during execution time but as long as I
can rotate it and it's short/quick I'm fine with it.
Here's a comparison of the plots produced after applying a PCA to the iris
dataset:
1\. mayavi
![alt text](http://i.stack.imgur.com/HkWkm.jpg)
2\. matplotlib
![alt text](http://i.stack.imgur.com/McrY1.jpg)
Mayavi makes it easier to visualize the data, but MatPlotLib looks more
professional. Matplotlib is also lighter.
Answer: Well, first you need to define what you mean by "see my data better"...
You can rotate and zoom in on the plot using the mouse, if you're wanting to
work interactively.
If you're just wanting to rotate the axes programatically, then use
`ax.view_init(elev, azim)` where `elev` and `azim` are the elevation and
azimuth angles (in degrees) that you want to view your plot from.
Alternatively, you can use the `ax.elev`, `ax.azim`, and `ax.dist` properties
to get/set the elevation, azimuth, and distance of the current view point.
Borrowing the
[source](http://matplotlib.sourceforge.net/plot_directive/mpl_examples/mplot3d/scatter3d_demo.py)
from [this
example](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#scatter-
plots):
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def randrange(n, vmin, vmax):
return (vmax-vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zl, zh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
We get a nice scatterplot: ![alt text](http://i.stack.imgur.com/CeGTY.png)
You can rotate the axes programatically as shown:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def randrange(n, vmin, vmax):
return (vmax-vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zl, zh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.azim = 200
ax.elev = -45
plt.show()
![alt text](http://i.stack.imgur.com/4TcqZ.png)
Hope that helps a bit!
|
Specify action to be performed at the end of many functions
Question: I have a python object in which a bunch of functions need to perform the same
action at the end of execution, just before the `return` statement. For
example:
def MyClass(object):
def __init__(self):
pass
def update_everything(self):
'''update everything'''
pass
def f1(self):
#do stuff
self.update_everything()
return result
def f2(self):
#do stuff
self.update_everything()
return result
def f3(self):
#do stuff
self.update_everything()
return result
What is the best (pythonic?) way to do this, except for the explicit calls at
the end of each function?
Answer: I think that any solution to your problem would be unpythonic, because (as Tim
Peters says in the Zen of Python (`import this`)):
Explicit is better than implicit.
|
Python class is a subclass of itself, is this ok? Pitfalls?
Question: I am wrapping a large C library using ctypes.
[ctypesgen](http://code.google.com/p/ctypesgen/) generated the wrapping code
(not too far from how I do it myself). As a part of the ctypes wrapping C
structures get made as objects, some of these have "setters" in C that would
be handy to just subclass itself to use. What are the possible dangers here?
Or this this fine to do as it seems to work but feels scary. Or is there a
better way? I do not want to modify the ctypesgen generated python.
class some_struct(ctypes.Structure):
_fields_ = [ ('a', ctypes.c_int), ('b', ctypes.c_double) ]
Then there is a c function set_some_struct_defaults() that I them implement
this way:
class some_struct(some_struct):
def __init__(self):
set_some_struct_defaults(self)
So the idea is that the "new" some_struct has an init function that calls the
C "setter" and so then when I initialize a python object I get all the
defaults (which are of course a lot more complicated than this toy example):
val = some_struct.some_struct()
Observations I have had:
* Order of the imports now matters, if you import some_struct from the wrapping.py and later from the class that extends it all is well, in the other order is an error. Not ideal.
Answer: You should do this simply by assigning `some_struct` a new `__init__`
function.
def new_init(self):
self._old_init()
set_some_struct_defaults(self)
some_struct.__dict__["_old_init"] = some_struct.__init__
some_struct.__init__ = new_init
This has the advantage that the original `__init__` still gets called.
|
Python code reflection and modification
Question: Perhaps I'm not using the proper term, but I'm looking to take a block of
Python code (in Python), get the token tree for the code, make some kind of
modification, and re-assemble it to Python.
For instance, consider this block of code:
def x(y):
b = 2
if y == b:
foo(y)
I would like to be able to take this and programmatically do this:
def x(y):
b = 2
if y == b:
bar(y)
I can't imagine that there's not a library that does something like this.
Thanks in advance.
**EDIT**
Perhaps I wasn't entirely clear. I'm looking for a tool to read and manipulate
_arbitrary_ code, not code that I'm writing. I'd like to be able to modify
code on-the-fly. The project I'm working on is a test app: it uses the
[Netflix philosophy](http://www.readwriteweb.com/cloud/2010/12/chaos-monkey-
how-netflix-uses.php) to try to randomly break the functionality of an app in
as many ways as it can, running the test suite each time. When the tests don't
fail, there's an indication that there's either a gap in code coverage and/or
the code is dead.
Answer: I was curious about this so I looked into the link Apalala posted, here is
what I came up with:
from token import NAME
from tokenize import generate_tokens, untokenize
from StringIO import StringIO
source = """def x(y):
b = 2
if y == b:
foo(y)"""
result = []
tokens = generate_tokens(StringIO(source).readline)
for toknum, tokval, _, _, _ in tokens:
if toknum == NAME and tokval == "foo":
tokval = "bar"
result.append((toknum, tokval))
print untokenize(result)
And the result is:
def x (y ):
b =2
if y ==b :
bar (y )
Yeah I know, the spacing is ugly. I could not figure out how to maintain the
format from the original code, but as far as functionality goes, this does
what you want.
|
Parameterising an import statement
Question: I maintain a Python module that wraps and exposes the functionality of a DLL
(also maintained by me). The interfacing with the DLL uses ctypes.
This all works wonderfully thanks to the wonders of ctypes. However, as I am
by no means a Python expert, there are some parts of the Python that I feel
are not _idiomatic_.
In particular I offer control of the DLL location to the user of the module.
The DLL is loaded during the import of the module. I do this because I want to
switch behaviour based on the capability of the DLL, and I need to load the
DLL in order to query its behaviour.
By default, the DLL load relies of the DLL search path to locate the DLL. I
would like to be able to allow the user to specify a full path to the DLL,
should they wish to pick out a particular version.
At the moment I do this by using an environment variable but I recognise that
this is a rather grotesque way to do it. What I'm looking for is a _canonical_
or _idiomatic_ Python way for the module importer to pass some information to
the module which can be accessed at module import time.
Answer: You should defer loading the DLL to the point where it's actually used for the
first time, and offer an optional function initialize:
_initialized=False
def initialize(path=None):
if _initialized:
if path:
raise ValueError, "initialize called after first use"
return
if path is None:
path = default_path
load_dll(path)
determine_features()
Then, call `initialized()` in all API you offer. This gives the user a chance
to override it, but if they don't, it will continue to work as it does today
(you can even preserve support for the environment variable).
If you are willing to change the API, use classes:
class DLLAPI:
def __init__(self, path=None):
...
Users would have to create a DLLAPI instance, and may or may not pass a DLL
path. That should allow to even use different DLLs simultaneously.
|
How do you play ogg files in Python in Linux?
Question: Could someone provide a short code or pseudocode example of how to play ogg
files in Python 2.7.1 or Python 3.1.3 in Linux (along with a list of any
dependencies from the Synaptic Package Manager, or elsewhere)?
Answer: If you don't mind depending on numpy, my package audiolab works pretty well
and supports oggfile out of the box as long as libsndfile itself supports it
(it should on linux if you version is recent enough):
# the dependencies
sudo apt-get install libsndfile-dev python-numpy cython python-setuptools
# install audiolab
cd audiolab-0.11 && python setup.py install --user
The basic API is straightforward:
from scikits.audiolab.pysndfile.matapi import oggread
data, fs, enc = oggread("myfile.ogg")
A more complete API for controlling output dtype, range, etc... is also
available. You can found releases on pypi, and the code on
[github](http://github.com/cournape/audiolab)
|
Icon overlay issue with Python
Question: I found some examples and topics on this forum about the way to implement an
icon overlay handler with Python 2.7 & the win32com package but it does not
work for me and I don't understand why.
I create the DLL and I have no error when I register it. I have also tried
directly with the script but it's the same. It's like the class is never
called.
Here is the code:
import win32traceutil
from win32com.shell import shell, shellcon
import pythoncom
import winerror
import os
REG_PATH =r'Software\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers'
REG_KEY = "GdIconOverlayTest"
class GdClass:
_reg_clsid_='{512AE200-F075-41E6-97DD-48ECA4311F2E}'
_reg_progid_='GD.TestServer'
_reg_desc_='gd desc'
_public_methods_ = ['GetOverlayInfo','GetPriority','IsMemberOf']
_com_interfaces_=[shell.IID_IShellIconOverlayIdentifier, pythoncom.IID_IDispatch]
def __init__(self):
pass
def GetOverlayInfo(self):
return (os.path.abspath(r'C:\icons\test.ico'), 0, shellcon.ISIOI_ICONFILE)
def GetPriority(self):
return 0
def IsMemberOf(self, fname, attributes):
print('ismemberOf', fname, os.path.basename(fname))
if os.path.basename(fname) == "hello.text":
return winerror.S_OK
return winerror.E_FAIL
def DllRegisterServer():
print "Registering %s" % REG_KEY
import _winreg
key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, REG_PATH)
subkey = _winreg.CreateKey(key, GdClass._reg_progid_)
_winreg.SetValueEx(subkey, None, 0, _winreg.REG_SZ, GdClass._reg_clsid_)
print "Registration complete: %s" % GdClass._reg_desc_
def DllUnregisterServer():
print "Unregistering %s" % REG_KEY
import _winreg
try:
key = _winreg.DeleteKey(_winreg.HKEY_LOCAL_MACHINE, r"%s\%s" % (REG_PATH, GdClass._reg_progid_))
except WindowsError, details:
import errno
if details.errno != errno.ENOENT:
raise
print "Unregistration complete: %s" % GdClass._reg_desc_
if __name__=='__main__':
from win32com.server import register
register.UseCommandLine(GdClass,
finalize_register = DllRegisterServer,
finalize_unregister = DllUnregisterServer)
* * *
Hi and thanks for your answer. I have tested with a log file and also
win32traceutil. The registration/unregitration messages are logged. The
registry entries are also created under:
1/HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers\GD.TestServer
2/ HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell
Extensions\Approved 3/ directly under class root.
I have also added some logs inside the methods getOverlayInfo, GetPriority and
isMemberOf but I can't see a trace when I browse through the explorer.
My configuration is: Python 2.7 pywin32-214.win32-py2.7.exe Windows XP SP 2
You can download all the code
[here](http://kobiarts.free.fr/python/iconoverlay.zip):
Answer: problem solved. i guess something was badly initialized but now it works.
My wish is to make something like the dropBox service.
i need to be able to update the icon of a given file according to its upload
status. I will create a class for each state (uploading, uploaded, failed)
that will implements the IID_IShellIconOverlayIdentifier interface. But
then...
should i write the list of files that are currently uploading/failed_to_upload
in local files the check the presence of each file into the isMemberOf method
to determine the good icon to display? Is it the best way to do that or it
would be better for instance to store all the file path inside a key in the
registry?
Thanks for your help.
|
Matching and merging text files programmatically
Question: I would like to merge an EDL (edit decision list) text file with another text
file that contains subtitles. The EDL is generated from a video editing
program, Final Cut Pro, while the text file is just regular text. While this
particular request is for a specific end-use, I would like to learn the
general method one can follow for doing this sort of processing. I am familiar
with Python but am quite ok with examples in other languages so long as they
are clear and easy to utilize on a UNIX/Mac workstation.
Here is an example of the first several lines of the EDL file:
TITLE: SAMPLE EDL
FCM: NON-DROP FRAME
001 GEN V C 00:01:03:16 00:01:04:29 01:00:03:06 01:00:04:19
* FROM CLIP NAME: TITLE 3D
* COMMENT:
* FROM CLIP IS A GENERATOR
002 GEN V C 00:01:04:15 00:01:08:03 01:00:04:29 01:00:08:17
* FROM CLIP NAME: TITLE 3D
* COMMENT:
* FROM CLIP IS A GENERATOR
003 GEN V C 00:01:04:15 00:01:09:05 01:00:10:19 01:00:15:09
* FROM CLIP NAME: TITLE 3D
* COMMENT:
* FROM CLIP IS A GENERATOR
004 GEN V C 00:01:04:15 00:01:07:03 01:00:17:17 01:00:20:05
* FROM CLIP NAME: TITLE 3D
* COMMENT:
* FROM CLIP IS A GENERATOR
Here is an example of the four "companion" lines from the subtitle text file:
001
If we think about climate change,
002
most of society's focused on fossil fuel combustion.
003
But what humans release on an annual basis is just one part of the carbon cycle.
004
Carbon dioxide concentrations also go up and down
Last, here is an example of the desired end result:
[00:00:03.06]
If we think about climate change,
[00:00:04.19]
[00:00:04.29]
most of society's focused on fossil fuel combustion.
[00:00:08.17]
[00:00:10.19]
But what humans release on an annual basis is just one part of the carbon cycle.
[00:00:15.09]
[00:00:17.17]
Carbon dioxide concentrations also go up and down
[00:00:20.05]
Looking at the example EDL file, the important bits of text are:
1. The line number i.e. `001` `002` `003` ...
2. The third and fourth columns of timecode numbers i.e.
01:00:03:06 01:00:04:19
01:00:04:29 01:00:08:17
01:00:10:19 01:00:15:09
From the subtitle text file, the line number corresponds with the line number
in the EDL file. This is a one-to-one match with no offsets or gaps in the
sequence. Each line of text should go into the desired end result as an entire
line without line breaks.
The end result essentially sandwiches each numbered line of subtitle text
between the first and second timecode numbers. The timecode numbers also need
to be reformatted slightly by:
1. Surrounding each set in square brackets i.e. `[]`
2. Making sure that the first set of numbers (the hours) are zeroed out i.e. `01:00:03:06` becomes `00:00:03:06` and `07:06:15:22` becomes `00:06:15:22`
3. The last colon '`:`' (prior to the frame number) gets converted into a period '`.`' i.e. `00:00:03:06` becomes `00:00:03.06`
And that is pretty much it. There can be about 100 to 120 lines of text in the
subtitle text file and correspondingly 100 to 120 'decisions' in the EDL text
file. If any further explanation is needed, please just ask. The main problem
I am having is finding out how to start off on this even. While I can wrap my
head around manipulating a single line of text within a single file
programmatically, I'm a bit flummoxed as to how to manage many lines between
multiple files.
Thanks in advance all.
Answer: Roughly this should be the plan.
* Read the files
* Make parser for each type of files
* Store the data in useful data structures/objects
* Output in appropriate format
Break up each step until, it is just a matter of writing down in code. Test at
each step.
|
How to enable the use of the gui resources on mac
Question: I am having a problem with tkinter.ttk on mac. I am using macports and
python3.1. When I try to use tkinter.ttk I get very old looking gui elements.
eg: I get this
![enter image description here](http://i.stack.imgur.com/Cexre.png)
Instead of this:
![enter image description here](http://i.stack.imgur.com/AL2pv.png)
The code I used is:
from tkinter import *
from tkinter import ttk
root = Tk()
button = ttk.Button(root, text="Hello World").grid()
root.mainloop()
I would be happy to provide any information from my computer needed to answer
this question. As I am a novice programer please tell me where to find said
information.
> After a bit of digging I found this: Python 3.1.2 (r312:79147, Jan 16 2011,
> 08:02:01) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help",
> "copyright", "credits" or "license" for more information.
>
>
> ->>> import tkinter.test.test_ttk.test_style
>
>
> Traceback (most recent call last):
> File "", line 1, in
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/test/test_ttk/test_style.py",
> line 8, in requires('gui') File
> "/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/test/support.py",
> line 215, in requires raise ResourceDenied(msg) test.support.ResourceDenied:
> Use of the `gui' resource not enabled
> ->>> The error I have has something to do with the fact that "Use of
> the`gui' resource is not enabled".
**If two more people confirm that the code in blockquotes has nothing to do
with the problem I will delete it from the question.**
I have a Macbook 5,2 with Snow Leopard installed. Any help would be
appreciated.
Thanks, Marlen
Answer: It's highly unlikely that this is related. You run the test from the Python
command line, it needs to be enabled first, which is done by:
from test import support
support.use_resources = ['gui']
Then you can:
import tkinter.test.test_ttk.test_style
And see what it says (mine says nothing, but I'm on Ubuntu).
|
How to move old libraries of previous version python to new version of python
Question: I am using Ubuntu. I install newer version of python. But all my installed
libraries such as imdbPy, NumPy, Cython etc. can run in previous version of
python whose version number is 2.6.6.
When I import Cython in 2.6.6, tt works, but I try same thing in 2.7.0+
version of python
import cython
occurs an error as following:
import cython
ImportError: No module named cython
What I need is to change default version of python which is used in bash. I
think, I can handle it by modifying bash profile file. I also want to move all
of these libs to appropriate place so that new version of python can reach
them permanently.
Answer: Don't mess with your system installs - the package manager should be
responsible for that. Make sure that when you install from source, you do it
in a separate directory.
I install things in my home directory. I like jhbuild so this is what I use to
maintain different versions of python side by side:
<https://thomas.apestaart.org/thomas/trac/browser/jhbuild/python>
Running make from that checkout will build python 2.3-2.7 and create scripts
to go into their environment:
[thomas@level ~]$ py-2.4
Entering interactive py shell /bin/bash
[py-2.4] [thomas@level ~]$ python
Python 2.4.5 (#1, Dec 16 2010, 18:51:06)
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
|
Install tkinter for Python
Question: I am trying to import Tkinter. However, I get an error stating that Tkinter
has not been installed:
> ImportError: No module named _tkinter, please install the python-tk package
I could probably install it using synaptic manager (can I?), however, I would
have to install it on every machine I program on. Would it be possible to add
the Tkinter library into my workspace and reference it from there?
Answer: It is not very easy to install Tkinter locally to use with system-provided
Python. You may build it from sources, but this is usually not the best idea
with a binary package-based distro you're apparently running.
It's safer to `apt-get install python-tk` on your machine(s). (Works on
Debian-derived distributions like for Ubuntu; refer to your package manager
and package list on other distributions.)
|
Importing a script into another script
Question: I am trying to import this file
<http://pastebin.com/bEss4J6Q>
Into this file
def MainLoop(self): #MainLoop is used to make the commands executable ie !google !say etc;
try:
while True:
# This method sends a ping to the server and if it pings it will send a pong back
#in other clients they keep receiving till they have a complete line however mine does not as of right now
#The PING command is used to test the presence of an active client or
#server at the other end of the connection. Servers send a PING
#message at regular intervals if no other activity detected coming
#from a connection. If a connection fails to respond to a PING
#message within a set amount of time, that connection is closed. A
#PING message MAY be sent even if the connection is active.
#PONG message is a reply to PING message. If parameter <server2> is
#given, this message will be forwarded to given target. The <server>
#parameter is the name of the entity who has responded to PING message
#and generated this message.
self.data = self.irc.recv( 4096 )
print self.data
if self.data.find ( 'PING' ) != -1:
self.irc.send(( "PONG %s \r\n" ) % (self.data.split() [ 1 ])) #Possible overflow problem
if "!chat" in self.data:
.....
So that I can successfully call upon the imported file (ipibot) whenever
'!chat' in self.data: # is called.
But I'm not sure how to write it. This is what I have so far
if "!chat" in self.data:
user = ipibot.ipibot()
user.respond
I'd like to state I have taken a look at the module portion of Python as well
as Importing I just can't seem to grasp it I guess?
file -> class -> function is what I understand it to be.
Answer: A module is nothing but a python source file. You keep that python source file
in the same directory as other source file and you can import that module in
other source files. When you are importing that module, the classes and
functions defined in that module are available for you to use. For e.g. in
your case, you would just do
import ipibot
At the top of your source, provided that ipibot.py (your pastebin) file is
present in the same directory or `PYTHONPATH` (a standard directory where
python programs can lookup for a module) and then start using
`ipibot.ipibot()` to use the function `ipibot()`from that module. Thats it.
|
PyQt4 - "See the log file for details" error
Question: I have made an application using Python and recently i found that i can use
py2exe to make executables for windows.
The problem is that a library i am using (xmpppy) produces this error
> DeprecationWarning: the md5 module is deprecated; use hashlib instead
and when i try to run the executable a dialog appears saying this
> See the logfile 'C:\Python26\P2E\MyApp\dist\MyApp.exe.log' for details
any ideas how to fix that?
Answer: You can try including the following lines down `import sys`
sys.stdout = open(“my_stdout.log”, “w”)
sys.stderr = open(“my_stderr.log”, “w”)
For more information you can read
[this](http://www.py2exe.org/index.cgi/StderrLog)
|
Pass variable to subprocess call in python
Question: I am trying to pass my variables from raw_input to my subprocess command. I am
new to python. Any help would he appreciated.
#!/usr/bin/python
import subprocess
print "\nWhat user name"
username = str(raw_input('username: '))
print "\nWhat is the user id"
userid = int(raw_input('Enter user id: '))
print "\nWhat is the user\'s primary group?"
primarygroup = int(raw_input('Enter group: '))
print "\nWhat is the user\'s secondary group?"
secondarygroup = int(raw_input('Enter group: '))
subprocess.call(['useradd' '-m' '-g' _primarygroup '-G' _secondarygroup '-u' _userid _username])
print"\nThe user has been added"
Answer: Try separating the values with commas:
subprocess.call(['useradd', '-m', '-g', _primarygroup, '-G', _secondarygroup, '-u', _userid, _username])
See <http://docs.python.org/library/subprocess.html#subprocess.call> \- It
takes an array where the first argument is the program and all other arguments
are passed as arguments to the program.
Also don't forget to check the return value of the function for a zero return
code which means "success" unless it doesn't matter for your script if the
user was added successfully or not.
|
Django version in GAE
Question: In the Google App Engine
[documentation](http://code.google.com/intl/en/appengine/docs/python/tools/libraries.html#Django),
it is said that we can use different versions of Django:
from google.appengine.dist import use_library
use_library('django', '1.1')
So do we really need to download any other (>0.96) Django versions and to put
them in the application directory, or any other place, because only Django
0.96 is included with the App Engine SDK? Also, do we need to remove them
before uploading the project to the server?
Can someone describe this process?
Answer: Django 0.96, 1.0.2, and 1.1 are available on AppEngine, but only 0.96 comes
with the AppEngine SDK download. You can still use 1.0.2 or 1.1, you just need
to download and install it separately. You don't need to put it in your app
directory; when you upload to the AppEngine environment it will pick up the
copy they have.
|
Python CouchDB/httplib - error: [Errno 61] Connection refused
Question: Did any one get this error? Please advice! There seems to be some problem with
httplib python library.
Python 2.7 (r27:82508, Jul 3 2010, 20:17:05)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> import couchdb
>>> couch = couchdb.Server()
>>> couch.create("foo")
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
couch.create("foo")
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/couchdb/client.py", line 193, in create
self.resource.put_json(validate_dbname(name))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/couchdb/http.py", line 405, in put_json
status, headers, data = self.put(*a, **k)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/couchdb/http.py", line 384, in put
return self._request('PUT', path, body=body, headers=headers, **params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/couchdb/http.py", line 419, in _request
credentials=self.credentials)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/couchdb/http.py", line 239, in request
resp = _try_request_with_retries(iter(self.retry_delays))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/couchdb/http.py", line 205, in _try_request_with_retries
raise e
error: [Errno 61] Connection refused
Answer: Are you behind a proxy ? check by doing: python -c "import urllib; print
urllib.getproxies()"
|
win32com + Excel + Django + Apache = problem
Question: I have some problem with opening Excel document in web application running
under Apache(mod_wsgi)/Windows 2008 Server (there is no problem when the
application is running on django developer server - one thread).
My code:
def my_view(request):
import pythoncom
from win32com.client import DispatchEx
pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
xl = win32com.client.dynamic.Dispatch('Excel.Application')
xl.DisplayAlerts = False
xl.Visible = 0
doc = xl.Workbooks.Open("C:\\path\\to\\file.xlsx")
doc.Saved = True
...
wb.Close(SaveChanges=0)
xl.Quit()
pythoncom.CoUninitialize()
Error message:
(-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel',
u"Microsoft Office Excel cannot access the file 'C:\path\to \file.xlsx'. There
are several possible reasons: The file name or path does not exist. The file
is being used by another program. The workbook you are trying to save has the
same name as a currently open workbook.", u'C:\Program Files (x86)\Microsoft
Office\Office12\ \1033\XLMAIN11.CHM', 0, -2146827284), None)
I know that problem is localized somewhere in threading, but where? I'm using
pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED). Maybe changing the
server will solve the problem?
Libs: Django 1.2, Apache 2.2 (mod_wsgi), win32com (latest)
I hope somebody can help me.
Thank You, regards.
Answer: After hours of researching the exact same problem I found the solution. It has
nothing to do with pythoncom / win32com, but with the fact that the apache is
running as a service. The solution can be found here:
<http://social.msdn.microsoft.com/Forums/en/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91>
The solution consists of simply making one folder and giving it write
permissions from the relevant (apache) user:
64-bit windows - create this folder:
C:\Windows\SysWOW64\config\systemprofile\Desktop
32-bit windows - create this folder:
C:\Windows\System32\config\systemprofile\Desktop
|
Tab key not indenting in Python
Question: I recently upgraded to python2.7 and noticed that the tab key does not
function appropriately in the shell. Instead, it appears to search through the
underlying directory (the standard unix behavior).
If I change back over to python2.6, it works appropriately. Is there a way to
add this functionality back to 2.7?
For example:
> if foo:
> (tab here) print 'bar' #desired behavior is that tab key adds indentation
> here
**Solution:**
This is a known issue with python2.7 on Mac OSX. I used the following
workaround to correct it:
$ cat > $HOME/.pystartup
import readline
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I ed-insert")
^D
$ export PYTHONSTARTUP=$HOME/.pystartup
Answer: This is a known bug with python 2.7 on Mac OSX. More details (including a fix)
can be found in [the bug report](http://bugs.python.org/issue10472).
|
subprocess.check_output() doesn't seem to exist (Python 2.6.5)
Question: I've been reading the Python documentation about the subprocess module (see
[here](http://docs.python.org/library/subprocess.html#subprocess-
replacements)) and it talks about a `subprocess.check_output()` command which
seems to be exactly what I need.
However, when I try and use it I get an error that it doesn't exist, and when
I run `dir(subprocess)` it is not listed.
I am running Python 2.6.5, and the code I have used is below:
import subprocess
subprocess.check_output(["ls", "-l", "/dev/null"])
Does anyone have any idea why this is happening?
Answer: It was introduced in 2.7 See the
[docs](http://docs.python.org/library/subprocess.html#subprocess.check_output).
Use
[subprocess.Popen](http://docs.python.org/library/subprocess.html#subprocess.Popen)
if you want the output:
>>> import subprocess
>>> output = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0]
|
How to create a setup.py that consumes a tar file
Question: Our systems people bundle source up in git and do not support pip. The git
repository contains a compressed tar file. And the tar file has a setup.py
within it. I figure the easiest way to expose this in my project is to add a
`-e git...` line to my pip requirements.txt and add a setup.py in the root of
the git repository for pip to use. The last step is how to write a setup.py
that installs a tar file as a source distribution.
/package
/SOURCES
package.tar.gz
/SPECS
site-specific-server-installation-script
* * *
In the alternative, I could just get a setup.py that does these things:
cd package/SOURCES
tar xzfv package-1.0.6.tar.gz
cd package-1.0.6/
python setup.py
Answer: I went with writing a pseudo setup.py file in the root of the git package:
import os
import subprocess
if __name__ == '__main__':
package_name = 'package'
short_package_name = 'package-1.0.6'
print "Changing to SOURCES"
os.chdir('SOURCES')
tar_file = '.'.join([short_package_name, 'tar', 'gz'])
print "Untarring ", tar_file
p = subprocess.Popen(['tar', 'xzfv', tar_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, errors = p.communicate()
print "Changing to ", short_package_name
os.chdir(short_package_name)
print "Setting up source distribution"
p = subprocess.Popen(['python', 'setup.py', 'install'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, errors = p.communicate()
It does not use the setup API at all but relies on using the setup.py name to
get invoke at install-time.
* * *
I am reliably informed, however, that easy_install supports installation from
a tar file: 'easy_install SOURCES/source.tar.gz'. So, is there a pip `-e
...git` directive that allows pulling a git repository from git and install
from a nested tar file?
|
SSL wrap socket: AttributeError: 'module' object has no attribute 'wrap_socket'
Question: I'm creating a very simple example on OSX with python 2.6 but I keep getting:
Traceback (most recent call last):
File "ssl.py", line 1, in <module>
import socket, ssl
File "/Users/Dennis/ssl.py", line 5, in <module>
sslSocket = ssl.wrap_socket(s)
AttributeError: 'module' object has no attribute 'wrap_socket'
Code:
import socket, ssl
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('irc.freenode.net', 7000))
sslSocket = ssl.wrap_socket(s)
print repr(sslSocket.server())
print repr(sslSocket.issuer())
sslSocket.write('Hello secure socket\n')
s.close()
What am I doing terribly wrong?
Thanks!
Dennis
Answer: Don't name your script `ssl.py`, because when you name your script `ssl.py`
and you do `import ssl` you're importing this same script .
|
Python Algorithm- For the game "Ghost"- need a way to intelligently look up all 'winning' permutation of letters
Question: I'm writing a computer program to play the word game
["Ghost."](http://en.wikipedia.org/wiki/Ghost_%28game%29)
Here's how the current programs works:
\--User selects a letter (right now it only works if the user moves first)
\--Computer has a list of all possible odd-numbered words in its dictionary
(this is so that the user will have to complete each word and therefore lose).
After each letter the user selects, the list of words that the computer has is
trimmed via this loop:
wordList = [w for w in wordList if w.startswith(currentWord)]
so that it only has words in its "wordList" that conform to the currentWord
that is collaboratively being spelled.
\--The computer then randomly selects a word from its current list of words
and returns the appropriate letter of the word via It then updates its list to
include the letter it selected via this code sample:
randomnumber = random.randint(0, len(wordList)-1)
currentWord+=wordList[randomnumber][len(currentWord)]
wordList = [w for w in wordList if w.startswith(currentWord)]
\--This then continues until either the user spells a word and that is
detected via the checkLoss function, or if the computer is unable to continue
a word without losing and triggers the checkBluff function. The checkBluff
function requires the user to write what word he is thinking to make sure he
isn't making one up.
\--*_HERE'S THE PROBLEM: *_ obviously, because the computer randomly selects
which character to pick there are certain words that will force a loss. For
example, if the the first player selects the word "d", there is a very high
probability that the computer will select an "e" because there are so many
words that have "de" and the very beginning. However, if the user on the third
turn selects the letter "e" such that the current spelling is "dee" the
computer has no words in its list (there is only one word in the english
language that fits that form: 'deed' and it is even-numbered and thus losing),
so the bluff function is triggered and the computer loses when the user
reveals he was thinking of a real word "deed."
**SO, I would like an algorithm that makes the computer think in advance such
that it does not ever pick a follow-up letter for which the first player can
force a loss.** So, if a "d" is picked, the computer should never pick an "e",
because that would force a loss with a subequent e. Similarly, if the user
selects an "h" the computer should never follow with an "o" because the user
can then say "c" which forces a "k" spelling the word "hock."
I cannot think of a way to do this.
If needed, here's the program in its full incarnation:
import os, random, sys, math, string
def checkBluff(currentWord, choice, fullList):
if choice.startswith(currentWord):
#print "this is accurate"
for line in fullList:
if line == choice:
return 1
return 0
def checkLoss(currentWord, fullList):
for line in fullList:
if currentWord == line:
return 1
return 0
def instantiateWordList(dictionary, wordList):
for line in dictionary:
wordList.append(line.strip())
return wordList
def main():
fullDict = open("wordlist.txt", "r") #fullDict contains all possible words
winFirst = open("firstwin.txt", "r") #winFirst contains all odd-numbered words
winSecond = open("secondwin.txt", "r")#winSecond contains all even-numbered words
turn = "Human"
currentWord = ""
wordList = []
fullList= []
bluff = ""
#Instantiates a list with every word for use in evaluating win/loss
for line in fullDict:
fullList.append(line.strip())
#Decide who goes first
choice = raw_input("1. I will go first \n2. I will go second\n>>")[0]
if choice == "1":
wordList = instantiateWordList(winSecond, wordList)
turn == "Human"
else:
wordList = instantiateWordList(winFirst, wordList)
turn == "Computer"
while True:
if turn == "Human":
choice = raw_input("Choose a letter: ")[0]
currentWord+=choice
if checkLoss(currentWord, fullList) == 1:
print "You have lost by spelling the word "+ currentWord
break
print "**Current Word**"+ currentWord
wordList = [w for w in wordList if w.startswith(currentWord)]
turn = "Computer"
if turn == "Computer":
try:
randomnumber = random.randint(0, len(wordList)-1)
currentWord+=wordList[randomnumber][len(currentWord)]
print "I am thinking of the word: "+ str(wordList[randomnumber])
wordList = [w for w in wordList if w.startswith(currentWord)]
print "**Current word**: "+ currentWord
print "length: "+ str(len(wordList))
turn = "Human"
except StandardError:
bluff = raw_input("I call bluff. What word were you thinking of?\n>>")
if checkBluff(currentWord, bluff, fullList) == 1:
print "You actually won!"
break
else:
print "You lost. You lying son of a bitch."
break
if __name__ == "__main__":
main()
Answer: You want the computer to look ahead, and yet choose randomly? :-)
This game is predictable enough and simple enough for you to make the computer
always win, if you want. In fact, you can have it pre-generate strategy trees
to guarantee a win. [They aren't even that
big](http://blog.xkcd.com/2007/12/31/ghost/), you could learn them by heart if
you want.
If you don't want that, you should only look one round ahead. In your deed
example, one round a head would show that the opponent can force a win in one
round, so it would avoid "de". But it would not avoid something that would
force a loss in two rounds.
But for that you need to go through all possibilities. You can then choose
randomly between the remaining choices.
|
Reading first line of an uploaded text file in python/django
Question: I am trying to process text files in a django app. Before I try to import the
data, I need to evaluate the first line to determine the file type.
i tried file[0], but of course that doesn't work. that did give me an error
saying its a "'InMemoryUploadedFile' object" but I can't find much
documentation about that.
So, does anyone know how to get the first line of a file?
Answer: Django's UploadedFile has a `content_type` attribute which returns MIME type
of the uploaded file supplied by user.
If you want to read the first line anyway, then you could use `readline()`
method on the uploaded file object to get the first line. As Django's
UploadedFile objects are file like objects, they support the commonly used
methods of file objects.
[Django docs on
UploadedFile](http://docs.djangoproject.com/en/dev/topics/http/file-
uploads/?from=olddocs#uploadedfile-objects)
|
Python search list of objects that contain objects, partial matches
Question: I'm trying to build a simple search engine for a small website. My initial
thought is to avoid using larger packages such as Solr, Haystack, etc. because
of the simplistic nature of my search needs.
My hope is that with some guidance I can make my code more pythonic,
efficient, and most importantly function properly.
Intended functionality: return product results based on full or partial
matches of item_number, product name, or category name (currently no
implementation of category matching)
Some code:
import pymssql
import utils #My utilities
class Product(object):
def __init__(self, item_number, name, description, category, msds):
self.item_number = str(item_number).strip()
self.name = name
self.description = description
self.category = category
self.msds = str(msds).strip()
class Category(object):
def __init__(self, name, categories):
self.name = name
self.categories = categories
self.slug = utils.slugify(name)
self.products = []
categories = (
Category('Food', ('123', '12A')),
Category('Tables', ('354', '35A', '310', '31G')),
Category('Chemicals', ('845', '85A', '404', '325'))
)
products = []
conn = pymssql.connect(...)
curr = conn.cursor()
for Category in categories:
for c in Category.categories:
curr.execute('SELECT item_number, name, CAST(description as text), category, msds from tblProducts WHERE category=%s', c)
for row in curr:
product = Product(row[0], row[1], row[2], row[3], row[4])
products.append(product)
Category.products.append(product)
conn.close()
def product_search(*params):
results = []
for product in products:
for param in params:
name = str(product.name)
if (name.find(param.capitalize())) != -1:
results.append(product)
item_number = str(product.item_number)
if (item.number.find(param.upper())) != -1:
results.append(product)
print results
product_search('something')
MS SQL database with tables and fields I cannot change.
At most I will pull in about 200 products.
Some things that jump out at me. Nested for loops. Two different if statements
in the product search which could result in duplicate products being added to
the results.
My thought was that if I had the products in memory (the products will rarely
change) I could cache them, reducing database dependence and possibly
providing an efficient search.
...posting for now... will come back and add more thoughts
Edit: The reason I have a Category object holding a list of Products is that I
want to show html pages of Products organized by Category. Also, the actual
category numbers may change in the future and holding a tuple seemed like
simple painless solution. That and I have read-only access to the database.
The reason for a separate list of products was somewhat of a cheat. I have a
page that shows all products with the ability to view MSDS (safety sheets).
Also it provided one less level to traverse while searching.
Edit 2:
def product_search(*params):
results = []
lowerParams = [ param.lower() for param in params ]
for product in products:
item_number = (str(product.item_number)).lower()
name = (str(product.name)).lower()
for param in lowerParams:
if param in item_number or param in name:
results.append(product)
print results
Answer: Prepare all variables outside of the loops and use `in` instead of `.find` if
you don't need the position of the substring:
def product_search(*params):
results = []
upperParams = [ param.upper() for param in params ]
for product in products:
name = str(product.name).upper()
item_number = str(product.item_number).upper()
for upperParam in upperParams:
if upperParam in name or upperParam in item_number:
results.append(product)
print results
|
Is Rails much better for interactive website compare to Django?
Question: Just got a new website project for my company internal use. The whole website
isn't that complicating but requires quite a lot of real time interaction.
Basically, it's an interactive time line table where we can freely drag and
drop each elements to move and resize them.
At first I wanted to use this opportunity to learn Python+Django (I'm given a
huge amount of time) but then I read around and a lot of people mentioned
Rails is better for creating rich interactive website.
So, for a website with a lot of drag & drop interaction like this, is Rails
really the better choice? Is Rails built-in ajax that much easier to work with
compare to Django+jQuery? How flexible and customizable is Rails' built-in
ajax? I want to learn RoR just as much as Python by thee way.
Answer: I don't think AJAX functionality will define which framework you find yourself
preferring.
I can't answer most of your question relating to ajax, but still think this
post could be useful for you: it's highlighting a huge difference between ROR
and django -- mainly RoR uses magic, django doesn't.
I prefer django for exactly that. Others may prefer RoR for the same reason I
don't.
[What's wrong with "magic"?](http://stackoverflow.com/questions/441717/whats-
wrong-with-magic/442088#442088)
> Rails' developers are of the opinion that this sort of "magic" is a good
> thing because it makes it easier to quickly get something working, and
> doesn't bore you with lots of details unless you want to reach in and start
> overriding things.
>
> Django's developers are of the opinion that this sort of "magic" is a bad
> thing because doesn't really save all that much time (a few import
> statements isn't a big deal in the grand scheme of things), and has the
> effect of hiding what's really going on, making it harder to work out how to
> override stuff, or harder to debug if something goes wrong.
>
> Both of these are, of course, valid stances to take, and generally it seems
> that people just naturally gravitate to one or the other; those who like the
> "magic" congregate around Rails or frameworks which try to emulate it, those
> who don't congregate around Django or frameworks which try to emulate it
> (and, in a broader sense, these stances are somewhat stereotypical of Ruby
> and Python developers; Ruby developers tend to like doing things one way,
> Python developers tend to like doing things another way).
So I think one will click for you regardless of out of the box ajax support.
|
Matplotlib not displaying figures
Question: This must be a really basic question: I am trying to use Matplotlib. Here's
the basic example from the
[documentation](http://matplotlib.sourceforge.net/api/pyplot_api.html).
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,5,0.1)
y = np.sin(x)
plt.plot(x,y)
I have tried this in `ipython`, `bpython` and the default interpreter (Ubuntu
10.10, 64 bit) and all I get are messages like:
[<matplotlib.lines.Line2D object at 0x3f14a90>]
What am I doing wrong?
Answer: You're missing `plt.show()` to order matplotlib to show a window with the
graph.
|
Does Python have a built in function for string natural sort?
Question: Using Python 3.x, I have a list of strings for which I would like to perform a
natural alphabetical sort.
**Natural sort:** The order by which files in Windows are sorted.
For instance, the following list is naturally sorted (what I want):
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
And here's the "sorted" version of the above list (what I have):
['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
I'm looking for a sort function which behaves like the first one.
Answer: Try this:
import re
def natural_sort(l):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(l, key = alphanum_key)
Output:
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
See it working online: [ideone](http://ideone.com/W0HUe).
Code adapted from here: [Sorting for Humans : Natural Sort
Order](http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-
sort-order.html).
|
Django: How to make an unique, blank models.CharField?
Question: Imagine that I have a model that describes the printers that an office has.
They could be ready to work or not (maybe in the storage area or it has been
bought but not still in th office ...). The model must have a field that
represents the phisicaly location of the printer ("Secretary's office",
"Reception", ... ). There cannot be two repeated locations and if it is not
working it should not have a location.
I want to have a list in which all printers appear and for each one to have
the locations where it is (if it has). Something like this:
ID | Location
1 | "Secretary's office"
2 |
3 | "Reception"
4 |
With this I can know that there are two printers that are working (1 and 3),
and others off line (2 and 4).
The first approach for the model, should be something like this:
class Printer(models.Model):
brand = models.CharField( ...
...
location = models.CharField( max_length=100, unique=True, blank=True )
But this doesn't work properly. You can only store one register with one blank
location. It is stored as an empty string in the database and it doesn't allow
you to insert more than one time (the database says that there is another
empty string for that field). If you add to this the "null=True" parameter, it
behaves in the same way. This is beacuse, instead of inserting NULL value in
the corresponding column, the default value is an empty string.
Searching in the web I have found
<http://www.maniacmartin.com/2010/12/21/unique-nullable-charfields-django/>,
that trys to resolve the problem in differnt ways. He says that probably the
cleanest is the last one, in which he subclass the CharField class and
override some methods to store different values in the database. Here is the
code:
from django.db import models
class NullableCharField(models.CharField):
description = "CharField that obeys null=True"
def to_python(self, value):
if isinstance(value, models.CharField):
return value
return value or ""
def get_db_prep_value(self, value):
return value or None
This works fine. You can store multiple registers with no location, because
instead of inserting an empty string, it stores a NULL. The problem of this is
that it shows the blank locations with Nones instead of empty string.
ID | Location
1 | "Secretary's office"
2 | None
3 | "Reception"
4 | None
I supposed that there is a method (or multiple) in which must be specify how
the data must be converted, between the model and the database class manager
in the two ways (database to model and model to database).
Is this the best way to have an unique, blank CharField?
Thanks,
Answer: Try to check this thread.
[Unique fields that allow nulls in
Django](http://stackoverflow.com/questions/454436/unique-fields-that-allow-
nulls-in-django)
|
Python APNs does not process request
Question: I'm trying to implement a server side script for sending push notifications to
apple push notification server. I create the ssl connection, I send the
payload - but am unable to get a response from the APNs. Here is my code:
import socket, ssl, pprint, struct, time, binascii
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# require a certificate from the server
ssl_sock = ssl.wrap_socket( s,
keyfile="/Users/Jeff/Desktop/pickmeup-key2-noenc.pem",
certfile="/Users/Jeff/Desktop/pickmeup-cert2.pem",
server_side=False,
do_handshake_on_connect=True,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs="/Users/Jeff/Desktop/entrustrootcert.pem",)
#ciphers="ALL")
ssl_sock.connect(('gateway.sandbox.push.apple.com', 2195))
print repr(ssl_sock.getpeername())
print ssl_sock.cipher()
print pprint.pformat(ssl_sock.getpeercert())
command = '\x00'
identifier = 1987
expiry = time.time()
deviceToken = "9858d81caa236a86cc67d01e1a07ba1df0982178dd7c95aae115d033b93cb3f5"
alert = "This is a test message"
sound = "UILocalNotificationDefaultSoundName"
payload = "{\"aps\":{\"alert\":\"%s\",\"sound\":\"%s\"}}" %(alert, sound)
packetFormat = "!cIIH%dsH%ds" %(32, len(payload))
packet = struct.pack(packetFormat,
command,
identifier,
int(expiry),
32,
binascii.unhexlify(deviceToken),
len(payload),
payload)
nBytesWritten = ssl_sock.write(packet)
print "nBytesWritten = %d" %(nBytesWritten)
data = ssl_sock.read(1024)
print len(data)
ssl_sock.close()
Running this script, I generate the following output:
('17.149.34.132', 2195)
('AES256-SHA', 'TLSv1/SSLv3', 256)
{'notAfter': 'May 31 00:04:27 2012 GMT',
'subject': ((('countryName', u'US'),),
(('stateOrProvinceName', u'California'),),
(('localityName', u'Cupertino'),),
(('organizationName', u'Apple Inc'),),
(('organizationalUnitName', u'Internet Services'),),
(('commonName', u'gateway.sandbox.push.apple.com'),))}
nBytesWritten = 133
0
Any ideas on what might be going wrong? (I am sending enhanced push
notifications so I am expecting a response from apple push notification
server)
Answer: The key thing to note is that read() is returning no data. In Python, read()
is supposed to block until data is available or the connection closes. _Apple
is closing your connection._
Why? Well, probably because you sent a malformed request. `command=0` is a
normal push notification; `command=1` is enhanced. The big-endian `1987` will
be interpreted as a 0-byte device token and a 1987-byte payload, neither of
which are valid.
(And FWIW, I'd use `B` instead of `c` for the command ID; it seems to make
more sense.)
|
Python: PyQt Popup Window
Question: So I've been creating my GUI with Qt for my Python application. I've now come
to a situation where after a button has been pushed the appropriate deferred
gets executed, we perform some tasks then I need to open up a separate window
that contains one or two things. But I can't seem to figure out how to create
this new separate window. Could anyone give me an example of how to create
one?
Answer: A common error that can drive you crazy is forgetting to store the handle of
the popup window you create in some python variable that will remain alive
(e.g. in a data member of the main window).
The following is a simple program that creates a main window with a button
where pressing the button opens a popup
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
from PyQt4.Qt import *
class MyPopup(QWidget):
def __init__(self):
QWidget.__init__(self)
def paintEvent(self, e):
dc = QPainter(self)
dc.drawLine(0, 0, 100, 100)
dc.drawLine(100, 0, 0, 100)
class MainWindow(QMainWindow):
def __init__(self, *args):
QMainWindow.__init__(self, *args)
self.cw = QWidget(self)
self.setCentralWidget(self.cw)
self.btn1 = QPushButton("Click me", self.cw)
self.btn1.setGeometry(QRect(0, 0, 100, 30))
self.connect(self.btn1, SIGNAL("clicked()"), self.doit)
self.w = None
def doit(self):
print "Opening a new popup window..."
self.w = MyPopup()
self.w.setGeometry(QRect(100, 100, 400, 200))
self.w.show()
class App(QApplication):
def __init__(self, *args):
QApplication.__init__(self, *args)
self.main = MainWindow()
self.connect(self, SIGNAL("lastWindowClosed()"), self.byebye )
self.main.show()
def byebye( self ):
self.exit(0)
def main(args):
global app
app = App(args)
app.exec_()
if __name__ == "__main__":
main(sys.argv)
What I think can be surprising for Python users and may be is the problem you
are facing is the fact that if you don't store a reference to the new widget
in the main e.g. by using `w = MyPopup(...)` instead of `self.w =
MyPopup(...)` the window apparently doesn't appear (actually it's created and
it's immediately destroyed).
The reason is that when the local variable `w` goes out of scope as no one is
explicitly referencing the widget the widget gets deleted. This can be seen
clearly because if you press again the button you'll see that as the second
popup appears the first one is closed.
This also means that if you need to create several popups you have for example
to put them in a python list and you should remove them from this list once
the popups are closed by the user. The equivalent in the example could be
changing to `self.w = []` in constructor and then doing
`self.w.append(MyPopup(...))`. Doing that would allow you to open several
popups.
|
Eclipse environment for Maya's python modules
Question: I'm trying to set up the Eclipse IDE to recognize the **maya.cmds** module, an
all modules associated with the **maya** module. The following code are tests
run in Eclipse, and Maya's script editor.
import maya
print 'maya:\n', dir(maya)
from maya import cmds
print 'cmds:\n', len(dir(cmds)) # too many to print
print 'sphere: ', cmds.sphere
In Maya's script editor the code results in
maya:
['OpenMaya', '_OpenMaya', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'app', 'cmds', 'mel', 'standalone', 'stringTable', 'utils']
cmds:
3190
sphere: <built-in method sphere of module object at 0x0000000019F0EEE8>
In Eclipse the code results in
maya:
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
cmds:
6
sphere:
Traceback (most recent call last):
AttributeError: 'module' object has no attribute 'sphere'
I've done a lot of searching, on the google group "python inside maya", and
web searches. The best I've found was the following link, however this did not
solve my issue at all, and in the end gave the same result. <http://www.luma-
pictures.com/tools/pymel/docs/1.0/eclipse.html>
I've read that I should be setting my environment paths in Eclipse, rather
than my machine, and I've also read the opposite opinion. What environment
vars should I set, to where, and in Eclipse, Windows, or both?
Answer: The solution is to import maya.standalone and initialize it. This gives you
access to the maya packages and modules therein.
import maya.standalone
maya.standalone.initialize()
import maya
print 'maya:\n', dir(maya)
from maya import cmds
print 'cmds:\n', len(dir(cmds)) # too many to print
print 'sphere: ', cmds.sphere
output:
maya:
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'__path__', 'app', 'cmds', 'mel', 'standalone', 'stringTable', 'test', 'utils']
cmds:
2945
sphere: <built-in method sphere of module object at 0xf33948>
|
can python function smart enough to show it's capability?
Question: I want to define a function cluster can be chained and invoked in-a-go with
the initial parameter given then get the final result, I want it may acting as
Linux command pipe chain:
test01() | test02() | test03() | test04()
[init_parameter] ----------------------------------------------------> [final result]
I am in condsidering the functions sequence can be added/reduced/remixed, for
example:
test02() | test03() | test01() | test04()
[init_parameter] ----------------------------------------------------> [final result]
test03()| test01() | test04() | test01()
[init_parameter] ----------------------------------------------------> [final result]
I also want those functions may come with its ability indicator embedded which
can be used for smart parameter pre-detected, for example, if input is not the
type this function can accept or input exceed its max process ability, the
chain can be just ignored on this calculation stream instead of using
"try...except..." to catch those "logic" error.
See below code, untested, just for describing my idea:
def test01(f_inspect=false, a, **b):
my_capability = {
"function_cluster": "A01",
"input_acceptable": type([]),
"input_element_acceptable": type(1),
"input_length_max": 100,
"return_type": type([]),
"return_element": type(1),
"return_length_max": 100,
}
if f_inspect:
return my_capability
return [x+1 for x in a] # just sample and may raise error by python such as div 0
def test02(f_inspect=false, a, **b):
# similiar as test01
def test03(f_inspect=false, a, **b):
# similiar as test01
def test04(f_inspect=false, a, **b):
# similar as test01
#==========================================
#test if function chain is compatible
def f_capability_compatible(current_,next_):
return True if
next_["function_cluster"] == current_["function_cluster"] and
next_["input_acceptable"] is current_["return_type"] and
next_["input_length_max"] >= current_["return_element"] and
next_["input_length_max"] >= current_["return_length_max"]
return False
foos = [test01,test02,test03,test04]
from itertools import permutations
mypermutations = permutations(foos, 3) # get permutations of testXX
init_parameter = [x for x in range(1,100)]
dummy_function_parameter = {
"function_cluster": "A01",
"input_acceptable": type([]),
"input_element_acceptable": type(1),
"input_length_max": 100,
"return_type": type([]),
"return_element": type(1)
"return_length_max": 100,
}
chain_flag = [True for x in range(len(mypermutations))]
#[True, True, True, ..... True, True, True, True, True, True, True]
for x in len(mypermutations):
tmp_para = dummy_function_parameter
for y in mypermutations[x]:
test_result = f_capability_compatible(tmp_para,y(f_inspect=true))
chain_flag[x] = test_result
tmp_para = y(f_inspect=true)
if test_result == False :
print "this can not be chained due to parameter incompatible at position %s" %x
break
#==========================================
result_of_chain = []
# to invoke:
for x in len(mypermutations):
if chain_flag[x] == True:
try :
# invoking my_capability[x] chain in a go
tmp_return = init_parameter
for f in mypermutations[x]:
tmp_return = f(tmp_return) #parameter of testXX(a)
except :
result_of_chain[x] = "Error"
else:
result_of_chain[x] = "Incomp"
**Here is my question, It is possible to make this function chain and
combination idea more simple?**
=======================================================================================
**update why I need to predicate the parameter and return type:**
In linux command line, we can using command like this:
$ cat sometfile | grep something | awk '{print $0}' | grep something > file
this works because the data stream between those command can be think as the
"text" type.
in python, however, for those unknown function, basically there's variety type
possibility of the input parameter and return result. If I want to invoking
those functions, I have to know the definition of it. For example
>>> def str_in_asciiout_out(str):
return ord(str)
>>>
>>> str_in_asciiout_out("a")
97
>>> str_in_asciiout_out(100)
# oops, I have to, try… expect…
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
str_in_asciiout_out(100)
File "<pyshell#0>", line 2, in str_in_asciiout_out
return ord(str)
TypeError: ord() expected string of length 1, but int found
Try... except... is right and proper way to code.
But if I want to combine hundreds of str_in_asciiout_out() alike functions and
put them into an unknown sequence, what I focused is the best final result the
sequence can delivered in short time.
For example, just example Suppose I have 1000 functions defined, each function
may need to run one day to get the output by given input, I random picked 200
functions into a chain, and the str_in_asciiout_out(100) just on the last
position by bad luck, I may got an oops until wasted 199 hours.
That’s why I want to know if the function can show it’s ability before the
time-wasting invoking.
Above code is an ugly solution I known, so I paste the idea to see if there’s
better solution for my problem.
Answer: I recently saw a slide presentation on [Python
generators](http://www.dabeaz.com/generators/Generators.pdf) that went through
a lot of neat things you can do with generator functions that allows you to
use them like a pipe-and-filter system. They're also evaluated "lazily", so
when you process, say, a very long list, it will only process the portion that
it needs to of the first list in order to give you the first output of the
resulting generator.
It looks here like you're kind of trying to shoehorn static typing into
Python. While there are cases for static typing, I'm not sure it's such a good
idea to try and force it into a dynamic language at the application level in
this manner. The kind of thing you're trying to prevent can be improved by
testing your code on small inputs
And lastly, if you're trying to annotate functions with metadata about their
return types, it would be better to use a
[decorator](http://www.artima.com/weblogs/viewpost.jsp?thread=240808) for the
function. For instance, if you were heartset on using types, you could use
something like this [example decorator from the Decorators
PEP](http://www.python.org/dev/peps/pep-0318/#examples):
def attrs(**kwds):
def decorate(f):
for k in kwds:
setattr(f, k, kwds[k])
return f
return decorate
@attrs(argument_types=(int, int,),
returns=int)
def add(a, b):
return a + b
Then, rather than calling the function with a `f_inspect` parameter, you could
just access the `add.argument_types` and `add.returns` member variables of
`add`.
|
run as administrator problem with py2exe
Question: I am having this problem that we compiled our python project into an exe with
py2exe and the resulting exe does not work unless it is executed as an
administrator.
I wanted to ask that is this supposed to happen ?? As in there are so many
applications that we can run as not an administrator so is there any way I can
convert my python code to such an application ...
Thanks a lot..
Answer: It sounds like your application is attempting to write to a directory for
which the basic user doesn't have access; most likely the "Program Files"
directory. I believe in Vista/Win7 this is not allowed, and the standard
convention is to write to the user's appdata folder, for any user data you
might wish to store.
You can reliably obtain the location of this directory using the `ctypes`
module, here's an example:
import ctypes
from ctypes import wintypes
def get_appdata_directory():
CSIDL_APPDATA = 0x001a
dll = ctypes.windll.shell32
app_data_directory = ctypes.create_unicode_buffer(wintypes.MAX_PATH)
found = dll.SHGetFolderPathW(0, CSIDL_APPDATA, 0, 0, app_data_directory)
# FYI: if `found` is False, then it failed to locate the appdata directory
# and app_data_directory.value is empty. So you might want to add some
# code here to verify that a valid path is going to be returned.
# This would probably only happen on older versions of windows,
# but, this is just a guess as I don't have any older OSs available
# for testing. (see my note below)
return app_data_directory.value
appdata = get_appdata_directory()
print(appdata)
# outputs something such as: 'C:\Users\bob\AppData'
Note: I believe the `appdata` folder was introduced with WinXP/Win2k. Not sure
about WinME and prior, however, I don't believe you have to worry about the
administrator restrictions on these earlier OSs. If you really care to support
them, you could use python's builtin `platform` module along with some
conditionals, then simply write user data to the "Program Files" directory for
the archaic versions of Windows.
|
Free image analysis libraries?
Question: I'm looking for some Free (preferably LGPL'd) image analysis/comparison
libraries. The most important thing they should be able to do, is compare two
different images and say if they're similar, with adjustable sensibility (i.e
the higher the sensibility the more they have to look like each other to get a
positive result) I'm thinking either C/++/# or eventually Python. So far the
only solution I've come across is OpenCV, which is under the BSD license. I
have yet to study how much of what I need is already implemented in the
library, and what I may need to write myself, but I would really like to hear
some other options before I start work on my project, so any opinions are
welcome.
Answer: Comparing if two images are "similar" is an extremely hard, research-class
problem. The approach you'd use will depend heavily on the types of
similarities/differences that you are expecting between your images.
It will be hard to find something that works off-the-shelf, unless your
comparison requirements are very specific.
Related questions that might be helpful:
* [Image comparison - fast algorithm](http://stackoverflow.com/questions/843972/image-comparison-fast-algorithm)
* [Image comparison algorithm](http://stackoverflow.com/questions/1819124/image-comparison-algorithm)
|
Laying out MVC classes in Python
Question: I'm working on a project in Python, and I'm trying to follow a somewhat-strict
MVC pattern for practice. My idea was to separate things out into packages
named `model`, `view` and `controller`, plus have a `Model`, `View` and
`Controller` class for each. Each package would have the supporting files for
each piece.
My problem is that I want to be able to use them like:
from controller import Controller
And then in the file with the Controller class I can:
from controller.someclass import SomeClass
But if I put them in packages with the same name, I get problems. I read up
about how modules work, and realized I needed to name them
`controller/__init__.py`, `model/__init__.py` and `view/__init__.py`, but it
seems weird to put them in that file, and it's kind of annoying that all of
them show up gedit as `__init__.py`
Is there any better way of doing this? Am I going about this the right way?
Answer: I've seen some black magic in the django source that pulls classes from a
`base.py` file into the `__init__.py` namespace. However I'm not sure how
that's done. ( See comments for how to do this. )
From what I do know, you can do one of two things.
A - inside `bar/controller/__init__.py`
import os,sys
# Make sure the interpreter knows were your files are.
sys.path.append(os.path.join(os.path.dirname(__file__),'../')
from bar.controller import Controller
from bar.model import Model
from bar.view import View
class Controller(object):
model = Model()
view = View()
And now you make `bar/model/__init__.py` and `bar/view/__init__.py`
B - inside `bar/controller/__init__.py`
class Model(object):
pass
class View(object):
pass
class Controller(object):
model = Model()
view = View()
Edit:... After reading your comment, a third option comes to mind. A package
doesn't litertly translate into a module in python. I think your desired
result is to create a directory structure like this:
bar/
__init__.py
controller.py
model.py
view.py
Then inside `controller.py`
import os,sys
from bar.controller import Controller
from bar.model import Model
from bar.view import View
class Controller(object):
model = Model()
view = View()
This was a huge hurdle for me to get coming from java. Your class file names
do not have to match the class name. Think of them as a step, you step into
the folder(module) and then into the file(.py) and then you import your
class.(Model(object))
|
Handling of ConnectionLost exception in twisted
Question: I can not handle a ConnectionLost exception. Brief example of what I have.
First of all iIset up connection to jabber server and ping it. I use wokkel
library for that. Then I add errback to the method that is sending ping. In
the errback I handle the ConnectionLost error. After that, I close the
internet connection. But I can not see if that ConnectionLost is handled. I
close connection in my application and all exception handlers are invoked.
Ping goes well.
[XmlStream,client] Ping to JID(u'jabber.ru') started at HivemindPingClientProtocol
[-] SEND: «iq to='jabber.ru' type='get' id='H_3'>/>»
[XmlStream,client] RECV: "/><feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>"
Internet connection is closed
[-] SEND: «iq to='jabber.ru' type='get' id='H_6'>/>»
[-] SEND: «iq to='jabber.ru' type='get' id='H_7'>/>»
Handlers of ConnectionLost are not invoked. "Stream closed at
HivemindXMPPClient" is printed in StreamManager in _disconnected method
[-] Protocol stopped
[-] Protocol closed
[-] Transport stopped
[XmlStream,client] Stream closed at HivemindXMPPClient
All exception are handled after closing stream.
[XmlStream,client] Failure [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionLost'>: Connection to the other side was lost in a non-clean fashion.
[XmlStream,client] Failure [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionLost'>: Connection to the other side was lost in a non-clean fashion.]
[XmlStream,client] Connection lost with [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionDone'>: Connection was closed cleanly.]
[XmlStream,client] Stopping factory <hivemind.network.network_core.HivemindXmlStreamFactory object at 0xa2e904c>>
Can anybody explain why errbacks are invoked after closing the stream?
Actually I want to implement a reconnect feature(I already use
ReconnectingFactory, but it does not react on ConnectionLost). Can someone
give me some example of reconnect implementation in twisted?
**Script example.** Run this script (make sure that ping work fine). Then
close your internet connection. When several ping has occured, you need to
terminate the script. As you can see, ConnectionLost errors are handled after
closing the connection.
import sys
from twisted.python import log
from twisted.words.protocols import jabber
from twisted.internet.error import ConnectionLost
from wokkel.client import XMPPClient
from wokkel.ping import PingClientProtocol
from twisted.internet.task import LoopingCall
JID = unicode('YOUR@JABBER.ID')
PASSWORD = 'PASSWORD'
INTERVAL = 3
class SpecialPingClientProtocol(PingClientProtocol):
def __init__(self, entity, interval):
self.__entity = jabber.jid.internJID(entity)
self.__interval = interval
self.__pingLoop = None
def _onError(self, failure):
log.msg('Failure %s at %s' % (failure, self.__class__.__name__))
error = failure.trap(jabber.error.StanzaError, ConnectionLost)
if error == jabber.error.StanzaError:
if failure.value.condition == 'feature-not-implemented':
return None
elif error == ConnectionLost:
# Do some beautiful things
log.msg('Connection is lost. I want to reconnect NOW')
return failure
def _sendPing(self):
defer = self.ping(self.__entity)
defer.addErrback(self._onError)
def stopPing(self):
log.msg('Ping to %s stopped at %s' % (self.__entity, self.__class__.__name__))
if self.__pingLoop is not None and self.__pingLoop.running:
self.__pingLoop.stop()
self.__pingLoop = None
def startPing(self):
log.msg('Ping to %s started at %s ' % (self.__entity, self.__class__.__name__))
self.__pingLoop = LoopingCall(self._sendPing)
self.__pingLoop.start(self.__interval, now = False)
def main():
log.startLogging(sys.stdout)
transport = XMPPClient(jabber.jid.internJID(JID), PASSWORD)
transport.logTraffic = True
pinger = SpecialPingClientProtocol(JID, INTERVAL)
pinger.setHandlerParent(transport)
transport.startService()
pinger.startPing()
reactor.run()
if __name__ == '__main__':
from twisted.internet import reactor
main()
Answer: Protocol has:
clientConnectionFailed(self, connector, reason)
clientConnectionLost(self, connector, reason)
you can override both and call PingClientProtocol.clientConnectionFailed and
PingClientProtocol.clientConnectionLost
assuming that PingClientProtocol inherit somehow from Protocol
|
Python: Downloading files from HTTP server
Question: I have written some python scripts to download images off an HTTP website, but
because I'm using urllib2, it closes the existing connection and then opens
another before opening another. I don't really understand networking all that
much, but this probably slows things down considerably, and grabbing 100
images at a time would take a considerable amount of time.
I started looking at other alternatives like pycurl or httplib, but found them
complicated to figure out compared to urllib2 and haven't found a lot of code
snippets that I could just take and use.
Simply, how would I establish a persistent connection to a website and
download a number of files and then close the connection only when I am done?
(probably an explicit call to close it)
Answer: since you asked for an httplib snippet:
import httplib
images = ['img1.png', 'img2.png', 'img3.png']
conn = httplib.HTTPConnection('www.example.com')
for image in images:
conn.request('GET', '/images/%s' % image)
resp = conn.getresponse()
data = resp.read()
with open(image, 'wb') as f:
f.write(data)
conn.close()
this would issue multiple (sequential) GET requests for the images in the
list, then close the connection.
|
Python Regex Help
Question: I am trying to sort through HTML tags and I can't seem to get it right.
What I have done so far
import urllib
import re
s = raw_input('Enter URL: ')
f = urllib.urlopen(s)
s = f.read()
f.close
r = re.compile('<TAG\b[^>]*>(.*?)</TAG>',)
result = re.findall(r, s)
print(result)
Where I replace "TAG" with tag I want to see.
Thanks in advance.
Answer: You should really try using libraries which can perform HTML parsing out of
the box. Beautiful Soup is one of my favorites.
|
Django/python date aggregation by month and quarter
Question: I'm writing a feature that requires the average price of an item over
different times (week, month, quarter etc.) Here's the model:
class ItemPrice(models.Model):
item = models.ForeignKey(Item)
date = models.DateField()
price = models.FloatField()
This model tracks the price of the item over time, with new Items being added
at frequent, but not regular, intervals. Finding the average `price` over the
last week is easy enough:
ItemPrice.objects.filter(item__id = 1)
.filter(date_lt = TODAY)
.filter(date_gte = TODAY_MINUS_7_DAYS)
.filter(date_.aggregate(Avg('value'))
As a week always has 7 days, but what about month and quarter? They have
different numbers of days...?
Thanks!
EDIT: The app is for a finance org, 30-day months wont cut it I'm afraid,
thanks for the suggestion!
Answer: The solution is two-part, first using the
[aggregation](http://docs.djangoproject.com/en/dev/topics/db/aggregation/)
functions of django ORM, the second using
[datutil](http://niemeyer.net/python-dateutil).
from dateutil.relativedelta import relativedelta
A_MONTH = relativedelta(months=1)
month = ItemPrice.objects \
.filter(date__gte = date - A_MONTH) \
.filter(date__lt = date) \
.aggregate(month_average = Avg('price'))
`month` equals:
{'month_average': 40}
It's worth noticing that you can change the key of the `month` dictionary by
changing the `.aggregate()` param.
`dateutil`'s relativedelta can handle days, weeks, years and lots more. An
excellent package, I'll be re-writing my home-grown hax.
|
Use python to connect to a php page and upload image
Question: I would like to know if its possible to use python to connect to a certain
site
(EX: <http://www.example.com/python> )
and upload an image from the computer. Basically I have a python script that
takes images from the webcam. Now after it takes the image how can i send that
image to a webpage. If you tell me how to get it to connect to the page I can
handle the rest. Thanks in advance!
THIS IS THE PYTHON SCRIPT AT HAND:
from VideoCapture import Device
cam = Device(devnum=1)
cam.saveSnapshot('image.jpg', timestamp=3, boldfont=1)
Answer: Use `urllib2` for this. Basically build up a
[`urllib2.Request`](http://docs.python.org/library/urllib2.html#urllib2.Request)
with the URL to the PHP script, and then `add_data` to add the image data that
you want to submit.
**edit** : you can follow the examples
[here](http://www.doughellmann.com/PyMOTW/urllib2/), and specifically [this
example](http://www.doughellmann.com/PyMOTW/urllib2/#posting-form-data) to
help understand the full process
|
How do I import a third party module in Python?
Question: I've found a third party module which I would like to use. How do I
technically import that module?
Particularly, I want to use a module called
[context_manager](https://github.com/cool-RR/GarlicSim-for-
Python-3.x/blob/master/garlicsim_py3/garlicsim/general_misc/context_manager.py).
obviously, I cannot just `import
garlicsim.general_misc.context_manager`because it won't find `garlicsim`. So
what should I write to import the thing?
**EDIT:** I'm using both Python 3.x and Python 2.x and I'd like to get answers
relevant to both versions.
Answer: In garlicsim's case you'd want to install it following garlicsim's
[installation
instructions](http://docs.garlicsim.org/intro/installation/python-3.x.html).
You could also download the code and in the right directory run `python
setup.py install` for this and almost any other library.
One note, since you may be new to python, is that that's a python 3 library.
If you're using python 2 (more likely if you don't know) it won't work right.
You'll want to install the python 2 [version](https://github.com/cool-
RR/GarlicSim).
|
Passing Command line argument to Python program using IDLE?
Question: I have downloaded a python file xxxxxx.py that is supposed to run on the
command line by typing: `python xxxxxx.py filename1 filename2` and that should
take these two files as arguments.
I was wondering if there is a way I can use IDLE to pass in these arguments.
Is there a way other than setting `sys.argv` ?
Thanks
Answer: It depends on the content of your Python file. If it is well-written, like:
#! /usr/bin/env python
def process(files):
for file in files:
# ...
if __name__ == '__main__'
# some error checking on sys.argv
process(sys.argv[1:])
sys.exit(0)
Then you could simply import the python file and run it like:
import name_of_file
# ...
name_of_file.process([file1, file2, file3])
# ...
So, it really depends on how it is written. If it isn't written well but you
can edit it, I would refactor it so that it can be used as a library;
otherwise, I would use the subprocess module to invoke the program.
|
Python method or class to compare two video files?
Question: I'm trying to write a program to compare files and show the duplicates in
python. Anyone know any good functions or methods related to this? I am sorta
lost...
Answer: If you're just looking for exact duplicates, do an [MD5
hash](http://docs.python.org/library/hashlib.html#module-hashlib) on both and
see if they match:
import hashlib
file1 = open('file1.avi', 'r').read()
file2 = open('file2.avi', 'r').read()
if hashlib.sha512(file1).hexdigest() == hashlib.sha512(file2).hexdigest():
print 'They are the same'
else:
print 'They are different'
If not, I'd try [OpenCV's Python
Bindings](http://opencv.willowgarage.com/documentation/python/index.html) and
check if they match up frame by frame.
|
Using python win32com can't make two separate tables in MS Word 2007
Question: I am trying to create multiple tables in a new Microsoft Word document using
Python. I can create the first table okay. But I think I have the COM Range
object configured wrong. It is not pointing to the end. The first table is put
before "Hello I am a text!", the second table is put inside the first table's
first cell. I thought that returning a Range from wordapp will return the full
range, then collapse it using wdCollapseStart Enum which I think is 1. (I
can't find the constants in Python win32com.). So adding a table to the end of
the Range will add it to the end of the document but that is not happening.
Any ideas?
Thanks Tim
import win32com.client
wordapp = win32com.client.Dispatch("Word.Application")
wordapp.Visible = 1
worddoc = wordapp.Documents.Add()
worddoc.PageSetup.Orientation = 1
worddoc.PageSetup.BookFoldPrinting = 1
worddoc.Content.Font.Size = 11
worddoc.Content.Paragraphs.TabStops.Add (100)
worddoc.Content.Text = "Hello, I am a text!"
location = worddoc.Range()
location.Collapse(1)
location.Paragraphs.Add()
location.Collapse(1)
table = location.Tables.Add (location, 3, 4)
table.ApplyStyleHeadingRows = 1
table.AutoFormat(16)
table.Cell(1,1).Range.InsertAfter("Teacher")
location1 = worddoc.Range()
location1.Paragraphs.Add()
location1.Collapse(1)
table = location1.Tables.Add (location1, 3, 4)
table.ApplyStyleHeadingRows = 1
table.AutoFormat(16)
table.Cell(1,1).Range.InsertAfter("Teacher1")
worddoc.Content.MoveEnd
worddoc.Close() # Close the Word Document (a save-Dialog pops up)
wordapp.Quit() # Close the Word Application
Answer: The problem seems to be in the Range object that represents a part of the
document. In my original code the Range object contains the first cell and
starts at the first cell, where it will insert. Instead I want to insert at
the end of the range. So I got the following code replacement to work. I moved
the Collapse after the Add() call and gave it an argument of 0. Now there is
only one Collapse call per Range object.
location = worddoc.Range()
location.Paragraphs.Add()
location.Collapse(0)
Now the code works, I can read from a database and populate new tables from
each entry.
Tim
|
What's the difference between database object and cursor object in pysqlite2?
Question: In Python one may interact with an sqlite database using the `pysqlite2`
class.
`from pysqlite2 import dbapi2 as sqlite`
One way to send commands to the database is through the database object:
db = sqlite.connect('mydb.sqlite')
db.execute('CREATE TABLE IF NOT EXISTS t1(a, b, c)')
another way is through a cursor:
cur = db.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS t2(x, y, z)')
Both the ways work and do the job, however I suspect that there are cases
where one way is peferred over the another. What are those cases?
Answer: The `connection.execute` method is an SQLite API extension; it's not specified
by DB-API: <http://www.python.org/dev/peps/pep-0249/>. It's just shorthand for
creating a cursor and calling `execute` on it, returning the cursor.
You shouldn't use it if you want to be sure that your code will work with
other DB-API-based database libraries.
|
I need to generate urlencoded string in Python that is valid for PHP parser
Question: I need to generate same output in Python as I have in PHP, possible?
**Php code:**
<?php
$items = array(
array(
'item_key_a' => 'item_value_a')
);
$payload = array(
'i_key' => 'i_value',
'items' => $items,
);
echo http_build_query($payload);
?>
Output urlencoded:
i_key=i_value&items%5B0%5D%5Bitem_key_a%5D=item_value_a
Output urldecoded:
i_key=i_value&items[0][item_key_a]=item_value_a
**Python code:**
item = {}
item['item_key_a'] = 'item_value_a'
data = {}
data['i_key'] = 'i_value'
data['items'] = [item]
import urllib
print urllib.urlencode(data)
Output urlencoded:
items=%5B%7B%27item_key_a%27%3A+%27item_value_a%27%7D%5D&i_key=i_value
Output urldecoded:
items=[{'item_key_a':+'item_value_a'}]&i_key=i_value
So in Python I don't get valid urlencoding that I need for PHP app.
Answer: Python urlencode does not handle nested dict. You need to write it yourself in
a manner such as presented for this question:
* [urlencode a multidimensional dictionary in python](http://stackoverflow.com/q/4013838/64633)
|
Summing up digits !
Question: Hi I have been trying out this
[problem](http://mathalon.in/?page=show_problem.php&pid=133):
> Suppose P(n) is sum of digits of 2^n
> For example:
> As 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26,so
> P(15)=26.
> Catulate sum of the P(n) for n=1 to 10000.
Here is my [python code](http://ideone.com/7fAWQ) which is giving **67783431**
as answer but the judge doesn't seems to be agree on this:
def P(n):
n = int(1<<n)
S = 0
while n != 0:
S += (n%10)
n /= 10
return S
Sum = 0
for i in range(1,10001):
Sum += P(i)
else:
print(Sum)
Could anybody tell me what's wrong in my approach? I would be appreciate if
somebody points me to a mathematical solution for the same.
Answer: If you had shown the comments, you would've noticed that the site owners, or
problem maintainer, is a moron.
He meant to say from "0 to 10000", not "1 to 10000", but apparently the
problem cannot be edited, or the maintainer don't want to do it.
The sum is off by 1 since `1<<0` is 1, which adds 1 to the sum.
Try submitting 67783432.
**Note** : I realize that calling the site owners or the maintainer a moron
might sound harsh, but when posting content on a site about "Mathematics",
accuracy is kinda important. Having such a site without the ability, or the
requirement, to fix wrong problems, seems kinda stupid to me.
|
How to use Python/CGI for file uploading
Question: I'm trying to make a file uploader page that will prompt the user for a file
and will upload while displaying progress.
At the moment I've managed to make a simple HTML page that can calls my python
script. The python script will then get the file and upload in 1000 byte
chunks.
I have two main problem (mainly due to be completely new to this):
1) I can't get the file size to calculate percentage 2) I don't know how to
communicate between the server side python and whatever is in the page to
update the progress status;presumably javascript.
Am I going about everything the wrong way? Or is there a solution to my woes?
Here is my python code:
#!/usr/local/bin/python2.5
import cgi, os
import cgitb; cgitb.enable()
try:
import msvcrt
msvcrt.setmode (0, os.O_BINARY)
msvcrt.setmode (1, os.O_BINARY)
except ImportError:
pass
form = cgi.FieldStorage()
upload = form['file']
if upload.filename:
name = os.path.basename(upload.filename)
out = open('/home/oetzi/webapps/py/' + name, 'wb', 1000)
message = "The file '" + name + "' was uploaded successfully"
while True:
packet = upload.file.read(1000)
if not packet:
break
out.write(packet)
out.close()
else:
message = "Derp... could you try that again please?"
print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)
Answer: This is more complex than it seems, given how file uploading works in the HTTP
protocol. Most web servers will give control to the CGI script only when the
uploaded file has been completely transferred, so there's no way to give
feedback in the meanwhile.
There are some Python libraries that attempt to tackle this issue, though. For
example: [gp.fileupload](http://pypi.python.org/pypi/gp.fileupload/0.8) (works
with WSGI, not CGI).
The trick is to provide a way to query the upload progress via AJAX while
still transferring the uploaded file. This is of no use if the web server (for
example, Apache or nginx) is not configured to support the upload progress
feature because you will probably see a 0% to 100% jump in the progress bar.
I suggest you try [Plupload](http://www.plupload.com/), which works on the
client-side and is much simpler.
|
Make in-memory copy of a zip by iterrating over each file of the input
Question: Python, as far as know, does not allow modification of an archived file. That
is why I want to:
1. Unpack the zip in memory (zip_in).
2. Go over each file in the zip_in, and change it if needed, then copy it to zip_out. For now I'm happy with just making a copy of a file.
3. Save zip_out.
I was experimenting with `zipfile` and `io` but no luck. Partially because I'm
not sure how all that works and which object requires which output.
# Working Code
import os
import io
import codecs
import zipfile
# Make in-memory copy of a zip file
# by iterating over each file in zip_in
# archive.
#
# Check if a file is text, and in that case
# open it with codecs.
zip_in = zipfile.ZipFile(f, mode='a')
zip_out = zipfile.ZipFile(fn, mode='w')
for i in zip_in.filelist:
if os.path.splitext(i.filename)[1] in ('.xml', '.txt'):
c = zip_in.open(i.filename)
c = codecs.EncodedFile(c, 'utf-8', 'utf-8').read()
c = c.decode('utf-8')
else:
c = zip_in.read(i.filename)
zip_out.writestr(i.filename, c)
zip_out.close()
# Old Example, With a Problem
# Make in-memory copy of a zip file
# by iterating over each file in zip_in
# archive.
#
# This code below does not work properly.
zip_in = zipfile.ZipFile(f, mode='a')
zip_out = zipfile.ZipFile(fn, mode='w')
for i in zip_in.filelist:
bc = io.StringIO() # what about binary files?
zip_in.extract(i.filename, bc)
zip_out.writestr(i.filename, bc.read())
zip_out.close()
The error is `TypeError: '_io.StringIO' object is not subscriptable`
Answer: `ZipFile.extract()` expects a filename, not a file-like object to write to.
Instead, use `ZipFile.read(name)` to get the contents of the file. It returns
the byte string so will work fine with binary files. Text files may require
decoding to unicode.
|
Calculating EuropeanOptionImpliedVolatility in quantlib-python
Question: I have R code that uses RQuantlib library. In order to run it from python I am
using RPy2. I know python has its own bindings for quantlib (quantlib-python).
I'd like to switch from R to python completely.
Please let me know how I can run the following using quantlib-python
import rpy2.robjects as robjects
robjects.r('library(RQuantLib)')
x = robjects.r('x<-EuropeanOptionImpliedVolatility(type="call", value=11.10, underlying=100,strike=100, dividendYield=0.01, riskFreeRate=0.03,maturity=0.5, volatility=0.4)')
print x
Sample run:
$ python vol.py
Loading required package: Rcpp
Implied Volatility for EuropeanOptionImpliedVolatility is 0.381
Answer: You'll need a bit of setup. For convenience, and unless you get name clashes,
you better import everything:
from QuantLib import *
then, create the option, which needs an exercise and a payoff:
exercise = EuropeanExercise(Date(3,August,2011))
payoff = PlainVanillaPayoff(Option.Call, 100.0)
option = EuropeanOption(payoff,exercise)
(note that you'll need an exercise date, not a time to maturity.)
Now, whether you want to price it or get its implied volatility, you'll have
to setup a Black-Scholes process. There's a bit of machinery involved, since
you can't just pass a value, say, of the risk-free rate: you'll need a full
curve, so you'll create a flat one and wrap it in a handle. Ditto for dividend
yield and vol; the underlying value goes in a quote. (I'm not explaining what
all the objects are; comment if you need it.)
S = QuoteHandle(SimpleQuote(100.0))
r = YieldTermStructureHandle(FlatForward(0, TARGET(), 0.03, Actual360()))
q = YieldTermStructureHandle(FlatForward(0, TARGET(), 0.01, Actual360()))
sigma = BlackVolTermStructureHandle(BlackConstantVol(0, TARGET(), 0.20, Actual360()))
process = BlackScholesMertonProcess(S,q,r,sigma)
(the volatility won't actually be used for implied-vol calculation, but you
need one anyway.)
Now, for implied volatility you'll call:
option.impliedVolatility(11.10, process)
and for pricing:
engine = AnalyticEuropeanEngine(process)
option.setPricingEngine(engine)
option.NPV()
You might use other features (wrap rates in a quote so you can change them
later, etc.) but this should get you started.
|
FileField() Error when trying to upload file using GAE and Django
Question: Hello Stack Overflow community!!
I am attempting to upload a file to GAE and I'm using Django. When I run the
following code it returns this error:
Tried upload in module pathway.app.views.
Error was: 'module' object has no attribute 'FileField'
When googling for a solution I found
[this](http://groups.google.com/group/google-
appengine/browse_thread/thread/6e9ee27c1e6a8539), but this issue should have
been fixed by now right?
I am not sure at this point what I have done wrong, I am new to GAE,python and
Django so any help would be appreciated!
And if anyone has a better solution to this problem, please tell me. Seems too
much code for such a simple task.
models.py
class UploadModel(db.Model):
title = db.StringProperty()
file = db.BlobProperty()
blobl = db.BlobProperty()
modified_on = db.DateTimeProperty(auto_now_add= 1)
modified_by = db.UserProperty()
views.py
def upload(request):
if request.method == 'POST':
form = form.UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(models.db.Blob(request.FILES['file']))
return HttpResponseRedirect('/success/url/')
else:
form = form.UploadFileForm()
files = models.UploadModel.all().order('-modified_on').fetch(20)
payload = dict(files = files)
return render("upload.html",payload)
form.py
from django import newforms as forms import models
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
Answer: You are using the version of Django included with Google App Engine, 0.96.4,
which is four years old and comes from before the `newforms` library included
support for file fields (and before it was renamed to simply `forms`).
Install an up-to-date Django version in your GAE project's directory and use
that instead.
|
Uploading files from a Cyrillic path using pycurl
Question: I've recently designed an upload dialog backed by PyCURL which I'm using in a
few of my applications.
I have run into an issue when setting pycurl's HTTPPOST option. I am setting
it like so:
self.curl.setopt(self.curl.HTTPPOST, [(field, (self.curl.FORM_FILE,
filename))])
If filename is a string, all is fine. If I pass it a unicode, however, it
raises a TypeError. Is there any way for me to be able to give it a Cyrillic
path? I tried UTF-8 encoding it, but that was unsuccessful. Thank you for your
time
Update:
I'm actually getting the filename from a WX control, so it's unicode before I
even touch it. When I then encode it to UTF-8, (using filename =
filename.encode('UTF-8')) the setopt goes fine but everything blows up on
perform:
* About to connect() to example.com port 80 (#0)
* Trying 123.123.123.123... * connected
* Connected to example.com (123.123.123.123) port 80 (#0)
* failed creating formpost data
* Connection #0 to host example.com left intact
Traceback (most recent call last):
File "c:\python27\lib\site-packages\transfer_dialogs-0.28-py2.7.egg\transfer_dialogs\transfer_dialogs.py", line 64, in perform_transfer
self.curl.perform()
error: (26, 'failed creating formpost data')
Update 2:
As requested, a bit more data. filename contains the result of a GetValue()
from the open dialog.
logging.debug("Filename: %r encoded filename: %r" % (filename,
filename.encode('UTF-8')))
result:
Sat Feb 05, 2011 03:33:56 core.dialogs.upload_audio DEBUG: Filename:
u'C:\Users\Q\test\\\u0422\u0435\u0441\u0442\u043e\u0432\u0430\u044f
\u043f\u0430\u043f\u043a\u0430\test.mp3' encoded filename:
'C:\Users\Q\test\\\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbe\xd0\xb2\xd0\xb0\xd1\x8f
\xd0\xbf\xd0\xb0\xd0\xbf\xd0\xba\xd0\xb0\test.mp3'
Answer: Filename should be in UTF-8, _and_ the host you upload it to should support
UTF-8 file names. If it supports a different, non-Unicode encoding, try to
encode the filename KOI8-R or WIN1251 (but this, of course, is not nice and
standards-compliant).
**EDIT** , having seen the comments: Probably it should have been
`ur"C:\Users\Q\test\Тестовая папка\test.mp3".encode("UTF-8")`. That `u` bit it
important; without it, the Cyrillic letters are taken encoded in your console
encoding. I did just try it, and it worked (not upload, just `setopt`).
|
Find all list permutations of a string in Python
Question: I have a string of letters that I'd like to split into all possible
combinations (the order of letters must be remain fixed), so that:
s = 'monkey'
becomes:
combinations = [['m', 'onkey'], ['mo', 'nkey'], ['m', 'o', 'nkey'] ... etc]
Any ideas?
Answer: <http://wordaligned.org/articles/partitioning-with-python> contains an
interesting post about sequence partitioning, here is the implementation they
use:
#!/usr/bin/env python
# From http://wordaligned.org/articles/partitioning-with-python
from itertools import chain, combinations
def sliceable(xs):
'''Return a sliceable version of the iterable xs.'''
try:
xs[:0]
return xs
except TypeError:
return tuple(xs)
def partition(iterable):
s = sliceable(iterable)
n = len(s)
b, mid, e = [0], list(range(1, n)), [n]
getslice = s.__getitem__
splits = (d for i in range(n) for d in combinations(mid, i))
return [[s[sl] for sl in map(slice, chain(b, d), chain(d, e))]
for d in splits]
if __name__ == '__main__':
s = "monkey"
for i in partition(s):
print i
Which would print:
['monkey']
['m', 'onkey']
['mo', 'nkey']
['mon', 'key']
['monk', 'ey']
['monke', 'y']
['m', 'o', 'nkey']
['m', 'on', 'key']
['m', 'onk', 'ey']
['m', 'onke', 'y']
['mo', 'n', 'key']
['mo', 'nk', 'ey']
['mo', 'nke', 'y']
['mon', 'k', 'ey']
['mon', 'ke', 'y']
['monk', 'e', 'y']
...
['mo', 'n', 'k', 'e', 'y']
['m', 'o', 'n', 'k', 'e', 'y']
|
Python: Converting GIF frames to PNG
Question: I'm very new to python, trying to use it to split the frames of a GIF into PNG
images.
# Using this GIF: http://www.videogamesprites.net/FinalFantasy1/Party/Before/Fighter-Front.gif
from PIL import Image
im = Image.open('Fighter-Front.gif')
transparency = im.info['transparency']
im.save('test1.png', transparency=transparency)
im.seek(im.tell()+1)
transparency = im.info['transparency']
im.save('test2.png', transparency=transparency)
# First frame comes out perfect, second frame (test2.png) comes out black,
# but in the "right shape", i.e.
# http://i.stack.imgur.com/5GvzC.png
Is this specific to the image I'm working with or am I doing something wrong?
Thanks!
Answer: I don't think you're doing anything wrong. See a similar issue here: [animated
GIF problem](http://code.activestate.com/lists/python-image-sig/5245/). It
appears as if the palette information isn't correctly treated for later
frames. The following works for me:
def iter_frames(im):
try:
i= 0
while 1:
im.seek(i)
imframe = im.copy()
if i == 0:
palette = imframe.getpalette()
else:
imframe.putpalette(palette)
yield imframe
i += 1
except EOFError:
pass
for i, frame in enumerate(iter_frames(im)):
frame.save('test%d.png' % i,**frame.info)
|
How do I get the python package "gtk"?
Question: I can't import it right now, but my library imports it.
I don't want the full Windows gtk thing. I just want the package that can be
imported by this script:
<http://www.koders.com/python/fid798D591F71AC2C5F462B7BFFF0D84E1EA8D5759F.aspx?s=timer>
Answer: Go to the [PyGTK
website](http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.22/) and choose
the all-in-one .msi that matches your Python version. Save it and then open
the .msi to install GTK for Python.
|
Python CSV search for specific values after reading into dictionary
Question: I need a little help reading specific values into a dictionary using Python. I
have a csv file with User numbers. So user 1,2,3... each user is within a
specific department 1,2,3... and each department is in a specific building
1,2,3... So I need to know how can I list all the users in department one in
building 1 then department 2 in building 1 so on. I have been trying and have
read everything into a massive dictionary using csv.ReadDict, but this would
work if I could search through which entries I read into each dictionary of
dictionaries. Any ideas for how to sort through this file? The CSV has over
150,000 entries for users. Each row is a new user and it lists 3 attributes,
user_name, departmentnumber, department building. There are a 100 departments
and 100 buildings and 150,000 users. Any ideas on a short script to sort them
all out? Thanks for your help in advance
Answer: A brute-force approach would look like
import csv
csvFile = csv.reader(open('myfile.csv'))
data = list(csvFile)
data.sort(key=lambda x: (x[2], x[1], x[0]))
It could then be extended to
import csv
import collections
csvFile = csv.reader(open('myfile.csv'))
data = collections.defaultdict(lambda: collections.defaultdict(list))
for name, dept, building in csvFile:
data[building][dept].append(name)
buildings = data.keys()
buildings.sort()
for building in buildings:
print "Building {0}".format(building)
depts = data[building].keys()
depts.sort()
for dept in depts:
print " Dept {0}".format(dept)
names = data[building][dept]
names.sort()
for name in names:
print " ",name
|
Determining if a given Python module is a built-in module
Question: I am doing some parsing and introspection of various modules, but I don't want
to parse built-in modules. Now, there is no special type for built-in modules
like there is a `types.BuiltinFunctionType`, so how do I do this?
>>> import CornedBeef
>>> CornedBeef
<module 'CornedBeef' from '/meatish/CornedBeef.pyc'>
>>> CornedBeef.__file__
'/meatish/CornedBeef.pyc'
>>> del CornedBeef.__file__
>>> CornedBeef
<module 'CornedBeef' (built-in)>
According to Python, a module is apparently built-in if it doesn't have a
`__file__` attribute. Does this mean that `hasattr(SomeModule, '__file__')` is
the way to check if a module is built in? Surely, it isn't exactly common to
`del SomeModule.__file__`, but is there a more solid way to determine if a
module is built-in?
Answer: ###
[`sys.builtin_module_names`](http://docs.python.org/library/sys.html#sys.builtin_module_names)
> A tuple of strings giving the names of all modules that are compiled into
> this Python interpreter. (This information is not available in any other way
> — modules.keys() only lists the imported modules.)
|
Problem with Python server and Ajax on Firefox
Question: I have a simple Python server,
import BaseHTTPServer
import SimpleHTTPServer
PORT = 8080
class TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
self.wfile.write("ok")
def start_server():
"""Start the server."""
server_address = ("", PORT)
server = BaseHTTPServer.HTTPServer(server_address, TestHandler)
server.serve_forever()
if __name__ == "__main__":
start_server()
and I want to communicate with Ajax:
$.ajax({
type: "GET",
url: 'http://localhost:8080',
data: dataString,
success: function(data) {
alert(data)
}
});
But due to the cross-domain problem, URL = 'http://localhost:8080' doesn't
work with Firefox or Chrome. My code is OK on Internet Explorer.
How can I do to resolve my pb? My HTML file is on local
<http://localhost/test/> and my Python server is on <http://localhost:8080>,
and I want to communicate on the same domain.
Answer: Can't you just serve the local file via the same small Python server on
another URL? This will put them both in the same domain.
If you use Apache to serve your HTML page, you can proxy ([see
`ProxyPass`](http://httpd.apache.org/docs/2.0/mod/mod_proxy.html#proxypass))
your Python server so that it appears on the same domain and on the same port,
just under different URL.
|
Why won't my python code run properly?
Question: My python code is the following but it won't work.
import random
secret = random.randint (1, 99)
guess = 0
tries = 0
print "AHOY! I'm the Dread Pirate Oliver and I have a secret!"
print "I will tell you where my treasure is buried if you can guess the number that I'm thinking of."
print "It is a number from 1 to 99. I'll give you 6 tries."
while guess != secret and tries < 6:
guess = input ("What's yer guess? ")
if guess < secret:
print "Too low ye scurvy dog!"
elif guess > secret:
print "Too high, landlubber!"
tries = tries + 1
if guess == secret:
print "Avast! Ye got it! Found ma secret number, ye did!"
print "THE FIRST WORD IS: Awesome"
else:
print "No more guesses! Better luck next time, Matey!"
print "Ma secret number wuz", secret
raise SystemExit()
import random
secret = random.randint (1, 99)
guess = 0
tries = 0
print "AHOY THERE!"
print "ME AGAIN"
print "I will tell you the second word if you can guess the number that I'm thinking of."
print "It is a number from 1 to 99. I'll give you 6 tries."
while guess != secret and tries < 6:
guess = input ("What's yer guess? ")
if guess < secret:
print "Too low ye scurvy dog!"
elif guess > secret:
print "Too high, landlubber!"
tries = tries + 1
if guess == secret:
print "Avast! Ye got it! Found ma secret number, ye did!"
print "THE SECOND WORD IS: Land"
else:
print "No more guesses! Better luck next time, Matey!"
print "Ma secret number wuz", secret
raise SystemExit()
import random
secret = random.randint (1, 3)
guess = 0
tries = 0
print "AHOY! One more thing"
print "It is a number from 1 to 3. I'll give you 1 try."
while guess != secret and tries < 1:
guess = input ("What's yer guess? ")
if guess < secret:
print "Too low ye scurvy dog!"
elif guess > secret:
print "Too high, landlubber!"
tries = tries + 1
if guess == secret:
print "Avast! Ye got it! Found ma secret number, ye did!"
print "It's buried in the sand at 36 degrees North, 48 degrees east."
else:
print "No more guesses! Better luck next time, Matey!"
print "Ma secret number wuz", secret
raise SystemExit()
import random
secret = random.randint (1, 99)
guess = 0
tries = 0
print "Congratz. You won!"
In the raise SystemExit() part, I want the person to not be able to continue
if they didn't guess the last bit. It doesn't even start, but when I take out
the raise SystemExit(), it works but it keeps going, even if they didn't guess
it correctly. What do I put instead to do what I want?
Answer: This line should be indented so that it is part of the else block, otherwise
it will always be executed even if the guess is correct:
raise SystemExit()
It might also be better to call `sys.exit()` instead.
Also if you want to do something twice, instead of copying and pasting your
code you should create a function and call it twice:
def play():
# ...
number_of_games = 2
for i in range(number_of_games):
play()
|
Loading a pickled list just once - Django\Python
Question: I have a pickle file that contains a list of compiled regexes and other data.
It takes about 1-1.5 seconds to load.
**What could a good way of using this list into my views, but have pickle work
on the file just once?**
## Edit:
would importing into settings.py be considered ok?
* * *
Any ideas?
Answer: I'd write a python module - a singleton class with an init method that reads
the pickled data into a python object, and then whatever 'get' methods you
need to get the info out.
Then in your settings.py you just call the initialisation method. Anything
that needs to get info from it just imports the module and uses the get
methods.
|
Get, or calculate the entropy of an image with Ruby and imagemagick
Question: How to find the "entropy" with imagemagick, preferably mini_magic, in Ruby? I
need this as part of a larger project, _finding "interestingness" in an image
so to crop it_.
I found a good [example in
Python/Django](http://stackoverflow.com/questions/1516736/django-sorl-
thumbnail-crop-picture-head), which gives the following pseudo-code:
image = Image.open('example.png')
histogram = image.histogram() # Fetch a list of pixel counts, one for each pixel value in the source image
#Normalize, or average the result.
for each histogram as pixel
histogram_recalc << pixel / histogram.size
endfor
#Place the pixels on a logarithmic scale, to enhance the result.
for each histogram_recalc as pixel
if pixel != 0
entropy_list << log2(pixel)
endif
endfor
#Calculate the total of the enhanced pixel-values and invert(?) that.
entropy = entroy_list.sum * -1
This would translate to the formula `entropy = -sum(p.*log2(p))`.
My questions: Did I interprete the Django/Python code correct? How can I fetch
a histogram in ruby's mini_magick if at all?
Most important question: is this algorithm any good in the first place? Would
you suggest a better one to find the "entropy" or "amount of changing pixels"
or "gradient depth" in (parts of) images?
**Edit** : Using a.o. the resources provided by the answer below, I came up
with the working code:
# Compute the entropy of an image slice.
def entropy_slice(image_data, x, y, width, height)
slice = image_data.crop(x, y, width, height)
entropy = entropy(slice)
end
# Compute the entropy of an image, defined as -sum(p.*log2(p)).
# Note: instead of log2, only available in ruby > 1.9, we use
# log(p)/log(2). which has the same effect.
def entropy(image_slice)
hist = image_slice.color_histogram
hist_size = hist.values.inject{|sum,x| sum ? sum + x : x }.to_f
entropy = 0
hist.values.each do |h|
p = h.to_f / hist_size
entropy += (p * (Math.log(p)/Math.log(2))) if p != 0
end
return entropy * -1
end
Where image_data is an `RMagick::Image`.
This is used in the [smartcropper gem](http://smartcropper.berk.es/), which
allows smart slicing and cropping for images with e.g. paperclip.
Answer: Entropy is explained here (with MATLAB source, but hopefully the qualitative
explanation helps):
[Introduction to Entropy (Data Mining in
MATLAB)](http://matlabdatamining.blogspot.com/2006/11/introduction-to-
entropy.html)
For a more formal explanation, see:
["Elements of Information Theory" (Chapter
2)](http://www1.cs.columbia.edu/~vh/courses/LexicalSemantics/Association/Cover&Thomas-
Ch2.pdf), by Cover and Thomas
|
Trouble parsing HTML using BeautifulSoup
Question: I'm trying to use BeautifulSoup to parse some HTML in Python. Specifically,
I'm trying to create two arrays of soup objects: one for the dates of postings
on a website, and one for the postings themselves. However, when I use findAll
on the div class that matches the postings, only the initial tag is returned,
not the text inside the tag. On the other hand, my code works just fine for
the dates. What is going on??
# store all texts of posts
texts = soup.findAll("div", {"class":"quote"})
# store all dates of posts
dates = soup.findAll("div", {"class":"datetab"})
The first line above returns only
<div class="quote">
which is not what I want. The second line returns
<div class="datetab">Feb<span>2</span></div>
which IS what I want (pre-refining).
I have no idea what I'm doing wrong. [Here](http://harvardfml.com) is the
website I'm trying to parse. This is for homework, and I'm really really
desperate.
Answer: Which version of BeautifulSoup are you using? Version 3.1.0 [performs
significantly
worse](http://www.crummy.com/software/BeautifulSoup/3.1-problems.html) with
real-world HTML (read: invalid HTML) than 3.0.8. This code works with 3.0.8:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen("http://harvardfml.com/")
soup = BeautifulSoup(page)
for incident in soup.findAll('span', { "class" : "quote" }):
print incident.contents
|
Problem bulk loading a csv file in Mysql using Python
Question: I am loading a file called 'rec.csv' to my Mysql DB. I use the code below:
import MySQLdb,os
path='testData'
absPath = os.path.abspath(path)
print absPath
conn = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='iens')
db_cursor = conn.cursor()
query = "LOAD DATA INFILE '"+ absPath + "/rec.csv" +"' INTO TABLE iens.recensies FIELDS TERMINATED BY ' ' LINES TERMINATED BY '\n' "
db_cursor.execute(query)
connection.commit()
For some reason it can't find the file! I can see the file exists, and the
when print the path it is printing it correctly. but in the end it generates
this error:
File "Load_Data.py", line 18, in <module>
db_cursor.execute(query)
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 166, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.InternalError: (29, "File '/home/hossein/Documents/Parabots/DataBase/testData/rec.csv' not found (Errcode: 13)")
hossein@hossein-laptop:~/Documents/Parabots/DataBase$ python Load_Data.py
/home/hossein/Documents/Parabots/DataBase/testData
Traceback (most recent call last):
File "Load_Data.py", line 18, in <module>
db_cursor.execute(query)
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 166, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.InternalError: (29, "File '/home/hossein/Documents/Parabots/DataBase/testData/rec.csv' not found (Errcode: 13)")
Can someone tell me, what I am doing wrong? Thanks
Answer: Make a slight change in your load query.
LOAD DATA LOCAL INFILE
i.e., add LOCAL in the query.
As per MySQL docs: If LOCAL is specified, the file is read by the client
program on the client host and sent to the server. The file can be given as a
full path name to specify its exact location. If given as a relative path
name, the name is interpreted relative to the directory in which the client
program was started.
Check this [link](http://dev.mysql.com/doc/refman/5.0/en/load-data.html) for
more information.
|
Is there somewhere an index of Py3k-only libraries?
Question: I'm curious if there are important libraries that support only Python 3, since
it appears that many libraries that do support it, also happen to support
Python 2.
Answer: No, there is no such index, but you could create one from the classifier data
on PyPI.
You could make a list of all packages that has "Programming Language :: Python
:: 3" or Programming Language :: Python :: 3.0" or "Programming Language ::
Python 3.1", but none of the Python 2 classifiers.
[http://pypi.python.org/pypi?:action=browse&c=214](http://pypi.python.org/pypi?:action=browse&c=214)
Possibly the XML interface can be useful:
<http://wiki.python.org/moin/PyPiXmlRpc>
|
PyXML on Ubuntu
Question: I just completed a fresh install of Ubuntu 10.10 and I'm trying to run some
scripts that use xml and xpath. I get an error from inside PyXML.
I think this is an install error. To get this installed I did the following:
prompt> sudo apt-get install python2.6-dev # The next line wouldn't install without this.
prompt> sudo easy_install PyXML
\-------BEGIN ERROR--------- username@ubuntu:~/data/code$ MyScript.py
Traceback (most recent call last):
File "/home/username/data/code/app/trunk/MyScript.py", line 17, in <module>
from xml import xpath
File "/usr/local/lib/python2.6/dist-packages/PyXML-0.8.4-py2.6-linux-i686.egg/_xmlplus/xpath/__init__.py", line 112, in <module>
from pyxpath import ExprParserFactory
File "/usr/local/lib/python2.6/dist-packages/PyXML-0.8.4-py2.6-linux-i686.egg/_xmlplus/xpath/pyxpath.py", line 59, in <module>
from xml.xpath.ParsedAbbreviatedRelativeLocationPath import ParsedAbbreviatedRelativeLocationPath
File "/usr/local/lib/python2.6/dist-packages/PyXML-0.8.4-py2.6-linux-i686.egg/_xmlplus/xpath/ParsedAbbreviatedRelativeLocationPath.py", line 31
as = ParsedAxisSpecifier.ParsedAxisSpecifier('descendant-or-self')
^
SyntaxError: invalid syntax
\-------------END ERROR-------------------
I'm about at my limits with PyXML. I simply want to read an xml file and
read/write data with xpath. Is there a simpler library that will easily work
out of the box? Or any ideas on how to fix this?
Answer: Just for the record, if you really need PyXML (i.e. legacy code that you don't
have the time to port right now), just changing `as` in the two places it is
used to some other variable name will do.
Additionally, I noticed that Gentoo added the method `use_pyxml()` to PyXML
which explicitly needs to be called; so the standard library XML modules are
not used. See [here](http://www.gossamer-threads.com/lists/gentoo/dev/230817)
if that is of interest.
|
Changing Date format in MySql
Question: I have a large Csv file that I wanna bulk-load it to my table. A column of
this csv file keeps the dates but in the DD-MM-YYYY format. When I am loading
this file to my table, it does not accept it, since MySQL DATE format only
accepts YYYY-MM-DD. Is there any way I could change this in MySQL. I am using
python to create my tables and to load my file into the table, which doesn't
matter for this problem actually.If there is a command for this, please tell
me where I should put it exactly? thanks This is the complete code
import MySQLdb,os
path='data_files'
absPath = os.path.abspath(path)
print absPath
#connecting to the new database
conn = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='iens')
db_cursor = conn.cursor()
query = "LOAD DATA LOCAL INFILE '"+ absPath + "/recencies" +"' INTO TABLE iens.recensies FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\r\n' (restaurantID,Naam,Date,RecensieText) "
db_cursor.execute(query)
conn.commit()
Answer: Assuming your table has two columns named `column1` and `column2`, the date is
in `column2` and that is the second column in the CSV file:
LOAD DATA INFILE 'filename' (column1, @var1)
SET column2 = STR_TO_DATE(@var1, '%d-%m-%Y')
The `(column1, @var1)` part says:
* The first column of the CSV file goes directly into the database column `column1`
* The second column of the CSV file goes into a variable `@var1`
The `SET column2 =` part says:
* Set the database column `column2` to whatever comes out of the expression following the `=` sign.
|
understanding OptionParser
Question: I was trying out `optparse` and this is my initial script.
#!/usr/bin/env python
import os, sys
from optparse import OptionParser
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser.add_option("-d", "--dir", type="string",
help="List of directory",
dest="inDir", default=".")
parser.add_option("-m", "--month", type="int",
help="Numeric value of the month",
dest="mon")
options, arguments = parser.parse_args()
if options.inDir:
print os.listdir(options.inDir)
if options.mon:
print options.mon
def no_opt()
print "No option has been given!!"
Now, this is what I'm trying to do:
1. If no argument is given with the option, it will take the "default" value. i.e `myScript.py -d` will just list the present directory or `-m` without any argument will take the current month as an argument.
2. For the "--month" only 01 to 12 are allowed as an argument
3. Want to combine more than one option for performing different tasks i.e. `myScript.py -d this_dir -m 02` will do different thing than -d and -m as individual.
4. It will print "_No option has been given!!_ " ONLY if no option is supplied with the script.
Are these doable? I did visit the doc.python.org site for possible answers,
but as a python-beginner, I found myself lost in the pages. It's very much
appreciated your help; thanks in advance. Cheers!!
* * *
**Update: 16/01/11**
I think I'm still missing something. This is the thing in my script now.
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser.add_option("-m", "--month", type="string",
help="select month from 01|02|...|12",
dest="mon", default=strftime("%m"))
parser.add_option("-v", "--vo", type="string",
help="select one of the supported VOs",
dest="vos")
options, arguments = parser.parse_args()
These are my goal:
1. run the script without any option, will return `option.mon` [_working_]
2. run the script with -m option, with return `option.mon` [_working_]
3. run the script with ONLY -v option, will ONLY return `option.vos` [_not working at all_]
4. run the script with -m and -v opting, will do different thing [_yet to get to the point_]
When I run the script with only -m option, it's printing `option.mon` first
and then `option.vos`, which I don't want at all. Really appreciate if anyone
can put me in the right direction. Cheers!!
* * *
**3rd Update**
#!/bin/env python
from time import strftime
from calendar import month_abbr
from optparse import OptionParser
# Set the CL options
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser.add_option("-m", "--month", type="string",
help="select month from 01|02|...|12",
dest="mon", default=strftime("%m"))
parser.add_option("-u", "--user", type="string",
help="name of the user",
dest="vos")
options, arguments = parser.parse_args()
abbrMonth = tuple(month_abbr)[int(options.mon)]
if options.mon:
print "The month is: %s" % abbrMonth
if options.vos:
print "My name is: %s" % options.vos
if options.mon and options.vos:
print "I'm '%s' and this month is '%s'" % (options.vos,abbrMonth)
This is what the script returns when run with various options:
# ./test.py
The month is: Feb
#
# ./test.py -m 12
The month is: Dec
#
# ./test.py -m 3 -u Mac
The month is: Mar
My name is: Mac
I'm 'Mac' and this month is 'Mar'
#
# ./test.py -u Mac
The month is: Feb
My name is: Mac
I'm 'Mac' and this month is 'Feb'
I like to see only:
1. `I'm 'Mac' and this month is 'Mar'` - as *result #3*
2. `My name is: Mac` - as *result #4*
what am I doing wrong? Cheers!!
* * *
**4th Update:**
Answering to myself: this way I can get what I'm looking for but I'm still not
impressed though.
#!/bin/env python
import os, sys
from time import strftime
from calendar import month_abbr
from optparse import OptionParser
def abbrMonth(m):
mn = tuple(month_abbr)[int(m)]
return mn
# Set the CL options
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser.add_option("-m", "--month", type="string",
help="select month from 01|02|...|12",
dest="mon")
parser.add_option("-u", "--user", type="string",
help="name of the user",
dest="vos")
(options, args) = parser.parse_args()
if options.mon and options.vos:
thisMonth = abbrMonth(options.mon)
print "I'm '%s' and this month is '%s'" % (options.vos, thisMonth)
sys.exit(0)
if not options.mon and not options.vos:
options.mon = strftime("%m")
if options.mon:
thisMonth = abbrMonth(options.mon)
print "The month is: %s" % thisMonth
if options.vos:
print "My name is: %s" % options.vos
and now this gives me exactly what I was looking for:
# ./test.py
The month is: Feb
# ./test.py -m 09
The month is: Sep
# ./test.py -u Mac
My name is: Mac
# ./test.py -m 3 -u Mac
I'm 'Mac' and this month is 'Mar'
Is this the only way of doing so? Doesn't look the "best way" to me. Cheers!!
Answer: Your solution looks reasonable to me. Comments:
* I don't understand why you turn `month_abbr` into a tuple; it should work fine without the `tuple()`
* I'd recommend checking for invalid month value (`raise OptionValueError` if you find a problem)
* if you really want the user to input exactly "01", "02", ..., or "12", you could use the "choice" option type; see [option types documentation](https://docs.python.org/2/library/optparse.html#standard-option-types)
|
Python "global name 'x' is not defined"
Question:
from dionaea.core import ihandler, incident, g_dionaea
from dionaea.util import md5file, sha512file
from dionaea import pyev
import logging
import json
import uuid
logger = logging.getLogger('submit_http')
logger.setLevel(logging.DEBUG)
class submmithttp_report:
def __init__(self, sha512h, md5, filepath):
self.sha512h, self.md5h, self.filepath = sha512h, filepath
self.saddr, self.sport, self.daddr, self.dport = ('', )*4
self.download_url = ''
class handler(ihandler):
def __init__(self, path):
logger.debug("%s ready!" % (self.__class__.__name__))
ihandler.__init__(self, path)
mwsconfig = g_dionaea.config()['modules']['python']['submit_http']
self.backendurl = mwsconfig['url']
self.email = 'email' in mwsconfig and mwsconfig['email'] or 'dionaea@carnivore.it'
self.user = 'user' in mwsconfig and mwsconfig['user'] or ''
self.password = 'pass' in mwsconfig and mwsconfig['pass'] or ''
self.cookies = {}
# heartbeats
dinfo = g_dionaea.version()
self.software = 'dionaea {0} {1}/{2} - {3} {4}'.format(
dinfo['dionaea']['version'],
dinfo['compiler']['os'],
dinfo['compiler']['arch'],
dinfo['compiler']['date'],
dinfo['compiler']['time'],
)
self.loop = pyev.default_loop()
def handle_incident(self, icd):
pass
def handle_incident_dionaea_download_complete_unique(self, icd):
cookie = str(uuid.uuid4())
i = incident("dionaea.upload.request")
i._url = self.backendurl
i.sha512 = sha512file(icd.file)
i.md5 = md5file(icd.file)
i.email = self.email
i.user = self.user
i.password = self.password
mr = submithttp_report(i.sha512, i.md5, icd.file)
if hasattr(icd, 'con'):
i.source_host = icd.con.remote.host
i.source_port = str(icd.con.remote.port)
i.target_host = icd.con.local.host
i.target_port = str(icd.con.local.port)
mr.saddr, mr.sport, mr.daddr, mr.dport = i.saddr, i.sport, i.daddr, i.dport
if hasattr(icd, 'url'):
i.download_url = icd.url
mr.download_url = icd.url
i._callback = "dionaea.modules.python.submithttp.result"
i._userdata = cookie
self.cookies[cookie] = mr
i.report()
# handle agains in the same way
handle_incident_dionaea_download_complete_again = handle_incident_dionaea_download_complete_unique
def handle_incident_dionaea_modules_python_submithttp_result(self, icd):
fh = open(icd.path, mode="rb")
c = fh.read()
logger.info("submithttp result: {0}".format(c))
cookie = icd._userdata
mr = self.cookies[cookie]
# does backend want us to upload?
if b'UNKNOWN' in c or b'S_FILEREQUEST' in c:
i = incident("dionaea.upload.request")
i._url = self.backendurl
i.sha512 = mr.sha512h
i.md5 = mr.md5h
i.email = self.email
i.user = self.user
i.password = self.password
i.set('file://data', mr.filepath)
i.source_host = mr.saddr
i.source_port = mr.sport
i.target_host = mr.daddr
i.target_port = mr.dport
i.download_url = mr.download_url
i._callback = "dionaea.modules.python.submithttp.uploadresult"
i._userdata = cookie
i.report()
def handle_incident_dionaea_modules_python_submithttp_uploadresult(self, icd):
fh = open(icd.path, mode="rb")
c = fh.read()
logger.info("submithttp uploadresult: {0}".format(c))
del self.cookies[icd._userdata]
When the honeypot call this module the following error appears:
NameError at NameError("global name 'submithttp_report' is not defined",)
[11022011 00:27:30] python module.c:984: /opt/dionaea/lib/dionaea/python/dionaea/submit_http.py:57 in handle_incident_dionaea_download_complete_unique
[11022011 00:27:30] python module.c:985: mr = submithttp_report(i.sha512, i.md5, icd.file)
[11022011 00:27:30] python module.c:984: binding.pyx:975 in dionaea.core.c_python_ihandler_cb (binding.c:8605)
Thanck you guys!
Answer: Class name is `submmithttp_report` but you are calling `submithttp_report`
|
How to get the size of a string in Python?
Question: For example, I get a string:
str = "please answer my question"
I want to write it to a file.
But I need to know the size of the string before writing the string to the
file. What function can I use to calculate the size of the string?
Answer: If you are talking about the length of the string, you can use
[`len()`](https://docs.python.org/2/library/functions.html#len):
>>> s = 'please answer my question'
>>> len(s) # number of characters in s
25
If you need the size of the string in bytes, you need
[`sys.getsizeof()`](http://docs.python.org/library/sys.html#sys.getsizeof):
>>> import sys
>>> sys.getsizeof(s)
58
Also, don't call your string `str`. It shadows the built-in
[`str()`](https://docs.python.org/2/library/functions.html#str) function.
|
Django - python manage.py send_mail - Unknown command: 'send_mail'
Question:
jafte@11156:~/django/sp$ python manage.py shell
Python 2.5.2 (r252:60911, Jan 20 2010, 21:48:48)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import mailer
>>> mailer.get_version()
'0.2a1.dev3'
>>> mailer.__file__
'/usr/lib/python2.5/site-packages/django_mailer-0.2a1.dev3-py2.5.egg/mailer/__init__.pyc'
>>> from django.conf import settings
>>> 'mailer' in settings.INSTALLED_APPS
True
>>>
jafte@11156:~/django/sp$ python manage.py send_mail
Unknown command: 'send_mail'
Type 'manage.py help' for usage.
what is wrong?
Answer: thanks Tommaso Barbugli.
[how to use django mailer without
PINAX](http://stackoverflow.com/questions/1819524/how-to-use-django-mailer-
without-pinax)
**>>use git clone and python ./setup.py install to re-install the mailer, and
it worked! Maybe the easy_install won't work here**
|
Virtualenv issue with flask-werkzeug
Question: I have installed virtualenv along with flask, werkzeug, jinja2 and SQLAlchemy.
I was following the tutorial mentioned on the flask website and i came across
the below error when executing flask code
Traceback (most recent call last):
File "hello.py", line 1, in ?
from flask import Flask
File "/root/myproject/env/lib/python2.4/site-packages/Flask-0.7dev_20110211-py2.4.egg/flask/__init__.py", line 18
from .app import Flask, Request, Response
^
What i feel is that virtualenv contains python 2.4 and in the documentation of
flask it is mentioned that flask supports python 2.5. So maybe that might be
the problem or it might be someother issue. Please help me out on this.
Secondly i would like to know the process of getting the latest virtualenv
which has Python 2.7 or any tips on how to install it on virtualenv.
I am using CentOS
Thank You in Advance
Answer: The `import .module` syntax is introduced in Python 2.5 ([relative
import](http://docs.python.org/release/2.5/whatsnew/pep-328.html)). So you
have to use at least 2.5 for this thing.
|
processing an image using CUDA implementation, python (pycuda) or C++?
Question: I am in a project to process an image using CUDA. The project is simply an
addition or subtraction of the image.
May I ask your professional opinion, which is best and what would be the
advantages and disadvantages of those two?
I appreciate everyone's opinions and/or suggestions since this project is very
important to me.
Answer: _General answer:_ It doesn't matter. Use the language you're more comfortable
with.
Keep in mind, however, that pycuda is only a wrapper around the CUDA C
interface, so it may not always be up-to-date, also it adds another potential
source of bugs, …
Python is great at rapid prototyping, so I'd personally go for Python. You can
always switch to C++ later if you need to.
|
escaping characters in a xml file with python
Question: I need to escape special characters in an ugly XML file (5000 lines or so
long). Here's an example of XML I have to deal with:
<root>
<element>
<name>name & surname</name>
<mail>name@name.org</mail>
</element>
</root>
Here the problem is the character "&" in the name. How would you escape
special characters like this with a Python library? I didn't find the way to
do it with [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/).
Answer: If you don't care about invalid characters in the xml you could use XML
parser's `recover` option (see [Parsing broken XML with
lxml.etree.iterparse](http://stackoverflow.com/q/2352840/4279)):
from lxml import etree
parser = etree.XMLParser(recover=True) # recover from bad characters.
root = etree.fromstring(broken_xml, parser=parser)
print etree.tostring(root)
### Output
<root>
<element>
<name>name surname</name>
<mail>name@name.org</mail>
</element>
</root>
|
Python's os.path libraries equivalent in C#
Question: Let's say I have a binary in C# code ae /a/b/c/xyz.exe and it expects the
/a/b/c/hello.txt in the same directory. How can I get the /a/b/c/hello.txt in
full path?
In python, I can get the running program's path with
`os.path.abspath(sys.argv[0])`, and I can get the directory info with
dirname(), and I can use join() to have the new full path.
import sys
from os.path import *
newName = join(dirname(abspath(sys.arg[0]), "hello.txt")
How can C# do the same thing?
Answer: You can use [Environment.CurrentDirectory](http://msdn.microsoft.com/en-
us/library/system.environment.currentdirectory.aspx),
[Environment.GetCommandLineArgs](http://msdn.microsoft.com/en-
us/library/system.environment.getcommandlineargs.aspx) and the classes in
[System.IO.Path](http://msdn.microsoft.com/en-us/library/system.io.path.aspx)
to do the same things. Your code would translate as:
// using System.IO;
string newPath = Path.Combine(
Path.GetDirectoryName(
Path.GetFullPath(Environment.GetCommandLineArgs[0])
), "hello.txt");
This, however, will fail if the current directory has changed before you call
this. (It would in python, as well...) It might be better to use the
following:
// using System.IO;
// using System.Reflection;
string newPath = Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
, "hello.txt");
|
pylint balks on reference to __package__
Question: I'm using `__package__` in setup.py to refer to the top-level name of the
package it's supposed to test, build, install, etc.. However, pylint objects:
Module 'mian.mian' has no '__package__' member
This works fine in `ipython`:
from mian import mian as package
package.__dict__
...
'__package__': 'mian',
Is pylint doing the right thing here, ignoring PEP 366's "When the import
system encounters an explicit relative import in a module without __package__
set (or with it set to None), it will calculate and store the correct value"?
If so, what do I need to change?
Workaround: Use `package.__name__.rpartition('.')[0]` instead of
`package.__package__`.
Answer: This is now a ticket on Pylint's tracker:
<http://www.logilab.org/ticket/73668>
|
python and django: execute python script from django web form?
Question: I have fully functional python program which I run from shell. All arguments
and options are supplied using option parser. What I would like to do is to
create simple web interface for this program using django.
I am stacked on transferring values received from web form to python script ))
Actually how can I execute python script in this way?
Thanks in advance!
Answer: If your python program has a bit that looks like this:
import sys
if __name__ == "__main__":
args = sys.argv
main(args)
Then just import it, and call it's main() method with your args in the same
format as sys.argv. Sorted. That would be the pythonic way of doing things.
Otherwise you need a general way of executing an external program from python
- os.system and its friends. This is covered elsewhere.
|
What can you do with Lisp macros that you can't do with first-class functions?
Question: I think I understand Lisp macros and their role in the compilation phase.
But in Python, you can pass a function into another function
def f(filename, g):
try:
fh = open(filename, "rb")
g(fh)
finally:
close(fh)
So, we get lazy evaluation here. What can I do with macros and not with
functions as first class objects?
Answer: First of all Lisp has first-class functions too, so you could as well ask:
"Why do I need macros in Lisp if I already have first-class functions". The
answer to that is that first-class functions don't allow you to play with
syntax.
On a cosmetic level, first-class functions allow you to write `f(filename,
some_function)` or `f(filename, lambda fh: fh.whatever(x))`, but not
`f(filename, fh, fh.whatever(x))`. Though arguably that's a good thing because
in that last case it is a lot less clear where `fh` suddenly comes from.
More importantly functions can only contain code that is valid. So you can't
write a higher-order function `reverse_function` that takes a function as an
argument and executes it "in reverse", so that `reverse_function(lambda:
"hello world" print)` would execute `print "hello world"`. With a macro you
can do this. Of course this particular example is quite silly, but this
ability is enormously useful when embedding domain specific languages.
For example you couldn't implement common lisp's `loop` construct in python.
Hell, you couldn't even implement python's `for ... in` construct in python if
it wasn't really built-in - at least not with that syntax. Sure you could
implement something like `for(collection, function)`, but that's a lot less
pretty.
|
Django model field max_length 3x varchar size?
Question: I just realized that with a legacy table I'm using in a django app that a
varchar(5) field (for example) is rendered in python as a
models.CharField(max_length=15) field. This 3x size for the max length is very
consistent across many other fields.
Why? or more importantly if I changed the django definition to be
models.CharField(max_length=5) would I break anything?
Answer: It is probably a manual error by someone who tried to write models.
No. It doesn't break anything if you change it to 5. Not only that, you should
change it to 5, so your form validation itself will take care of that length
where you have that field.
|
Using text in one file to search for match in second file
Question: I'm using python 2.6 on linux.
I have two text files first.txt has a single string of text on each line. So
it looks like
lorem
ipus
asfd
The second file doesn't quite have the same format. it would look more like
this
1231 lorem
1311 assss 31 1
etc
I want to take each line of text from first.txt and determine if there's a
match in the second text. If there isn't a match then I would like to save the
missing text to a third file. I would like to ignore case but not completely
necessary. This is why I was looking at regex but didn't have much luck.
So I'm opening the files, using readlines() to create a list.
Iterating through the lists and printing out the matches.
Here's my code
first_file=open('first.txt', "r")
first=first_file.readlines()
first_file.close()
second_file=open('second.txt',"r")
second=second_file.readlines()
second_file.close()
while i < len(first):
j=search[i]
while k < len(second):
m=compare[k]
if not j.find(m):
print m
i=i+1
k=k+1
exit()
It's definitely not elegant. Anyone have suggestions how to fix this or a
better solution?
Answer: My approach is this: Read the second file, convert it into lowercase and then
create a list of the words it contains. Then convert this list into a
[set](http://docs.python.org/library/stdtypes.html#set), for better
performance with large files.
Then go through each line in the first file, and if it (also converted to
lowercase, and with extra whitespace removed) is not in the set we created,
write it to the third file.
with open("second.txt") as second_file:
second_values = set(second_file.read().lower().split())
with open("first.txt") as first_file:
with open("third.txt", "wt") as third_file:
for line in first_file:
if line.lower().strip() not in second_values:
third_file.write(line + "\n")
set objects are a simple container type that is unordered and cannot contain
duplicate value. It is designed to allow you to quickly add or remove items,
or tell if an item is already in the set.
`with` statements are a convenient way to ensure that a file is closed, even
if an exception occurs. They are enabled by default from Python 2.6 onwards,
in Python 2.5 they require that you put the line `from __future__ import
with_statements` at the top of your file.
The `in` operator does what it sounds like: tell you if a value can be found
in a collection. When used with a list it just iterates through, like your
code does, but when used with a set object it uses hashes to perform much
faster. `not in` does the opposite. (Possible point of confusion: `in` is also
used when defining a `for` loop (`for x in [1, 2, 3]`), but this is
unrelated.)
|
virtualenv --no-site-packages is not working for me
Question:
virtualenv --no-site-packages v1
cd v1\Scripts
activate.bat
python -c "import django" # - no problem here
Why does it see the Django package??? It should give me an import error,
right?
Answer: Just unset `PYTHONPATH` environment variable. The idea of virtualenv is that
you can create your own environment (fully isolated or extending the default
one) so you don't have to mess with that.
As someone noticed there's already been [a similar question on
SO](http://stackoverflow.com/questions/2961103/virtualenv-on-windows-not-over-
riding-installed-package/2963017#2963017). Read it if you need a better
explanation.
|
Generate a list of file names based on month and year arithmetic
Question: How can I list the numbers `01` to `12` (one for each of the 12 months) in
such a way so that the current month always comes last where the oldest one is
first. In other words, if the number is grater than the current month, it's
from the previous year.
e.g. `02` is Feb, 2011 (the current month right now), `03` is March, 2010 and
`09` is Sep, 2010 but `01` is Jan, 2011. In this case, I'd like to have `[09,
03, 01, 02]`. This is what I'm doing to determine the year:
for inFile in os.listdir('.'):
if inFile.isdigit():
month = months[int(inFile)]
if int(inFile) <= int(strftime("%m")):
year = strftime("%Y")
else:
year = int(strftime("%Y"))-1
mnYear = month + ", " + str(year)
I don't have a clue what to do next. What should I do here?
* * *
**Update:**
I think, I better upload the entire script for better understanding.
#!/usr/bin/env python
import os, sys
from time import strftime
from calendar import month_abbr
vGroup = {}
vo = "group_lhcb"
SI00_fig = float(2.478)
months = tuple(month_abbr)
print "\n%-12s\t%10s\t%8s\t%10s" % ('VOs','CPU-time','CPU-time','kSI2K-hrs')
print "%-12s\t%10s\t%8s\t%10s" % ('','(in Sec)','(in Hrs)','(*2.478)')
print "=" * 58
for inFile in os.listdir('.'):
if inFile.isdigit():
readFile = open(inFile, 'r')
lines = readFile.readlines()
readFile.close()
month = months[int(inFile)]
if int(inFile) <= int(strftime("%m")):
year = strftime("%Y")
else:
year = int(strftime("%Y"))-1
mnYear = month + ", " + str(year)
for line in lines[2:]:
if line.find(vo)==0:
g, i = line.split()
s = vGroup.get(g, 0)
vGroup[g] = s + int(i)
sumHrs = ((vGroup[g]/60)/60)
sumSi2k = sumHrs*SI00_fig
print "%-12s\t%10s\t%8s\t%10.2f" % (mnYear,vGroup[g],sumHrs,sumSi2k)
del vGroup[g]
When I run the script, I get this:
[root@serv07 usage]# ./test.py
VOs CPU-time CPU-time kSI2K-hrs
(in Sec) (in Hrs) (*2.478)
==================================================
Jan, 2011 211201372 58667 145376.83
Dec, 2010 5064337 1406 3484.07
Feb, 2011 17506049 4862 12048.04
Sep, 2010 210874275 58576 145151.33
As I said in the original post, I like the result to be in this order instead:
Sep, 2010 210874275 58576 145151.33
Dec, 2010 5064337 1406 3484.07
Jan, 2011 211201372 58667 145376.83
Feb, 2011 17506049 4862 12048.04
The files in the source directory reads like this:
[root@serv07 usage]# ls -l
total 3632
-rw-r--r-- 1 root root 1144972 Feb 9 19:23 01
-rw-r--r-- 1 root root 556630 Feb 13 09:11 02
-rw-r--r-- 1 root root 443782 Feb 11 17:23 02.bak
-rw-r--r-- 1 root root 1144556 Feb 14 09:30 09
-rw-r--r-- 1 root root 370822 Feb 9 19:24 12
Did I give a better picture now? Sorry for not being very clear in the first
place. Cheers!!
* * *
**Update @Mark Ransom**
This is the result from Mark's suggestion:
[root@serv07 usage]# ./test.py
VOs CPU-time CPU-time kSI2K-hrs
(in Sec) (in Hrs) (*2.478)
==========================================================
Dec, 2010 5064337 1406 3484.07
Sep, 2010 210874275 58576 145151.33
Feb, 2011 17506049 4862 12048.04
Jan, 2011 211201372 58667 145376.83
As I said before, I'm looking for the result to b printed in this order: _Sep,
2010 -> Dec, 2010 -> Jan, 2011 -> Feb, 2011_ Cheers!!
Answer: **Third Update:**
import os, sys
from time import strftime
from calendar import month_abbr
thismonth = int(strftime("%m"))
sortedmonths = ["%02d" % (m % 12 + 1) for m in range(thismonth, thismonth + 12)]
inFiles = [m for m in sortedmonths if m in os.listdir('.')]
for inFile in inFiles:
readFile = open(inFile, 'r')
# [ ... everything else is the same from here (but reindented)... ]
List comprehensions are preferable but if something I've done isn't kosher in
2.3, try this:
inFiles = filter(lambda x: x.isdigit(), os.listdir('.'))
sortedmonths = map(lambda x: "%02d" % (x % 12 + 1), range(thismonth, thismonth + 12))
inFiles = filter(lambda x: x in inFiles, sortedmonths)
**Second Update:**
Ok, based on your edit, here's what I think is the simplest solution:
import os, sys
from time import strftime
from calendar import month_abbr
thismonth = int(strftime("%m"))
inFiles = []
for inFile in os.listdir('.'):
if inFile.isdigit():
inFiles.append(inFile)
inFiles.sort(key=lambda x: (int(x) - thismonth - 1) % 12)
for inFile in inFiles:
readFile = open(inFile, 'r')
# [ ... everything else is the same from here (but reindented)... ]
This way your main loop goes through the files in the correct order.
You could also replace the four-line loop above with a one-line comprehension:
inFiles = [inFile for inFile in os.listdir('.') if inFile.isdigit()]
Also, I recommend using `from datetime import datetime` and then
`datetime.now()`. Its interface is nicer than `strftime()` \--
`datetime.now().month` returns a numerical month (same for `.year`, `.min`,
`.second`, etc., and `str(datetime.now())` presents a nicely formatted date-
time string.
**Update:**
Ok, after some more fiddling, here's what I think works best -- this works
regardless of whether `Jan = 1` or `Jan = 0`:
>>> themonths = [1, 2, 3, 9]
>>> themonths.sort(key=lambda x: (x - thismonth - 1) % 12)
>>> themonths
[2, 3, 9, 1]
**Original Post:**
If I understand you correctly:
>>> thismonth = 1
>>> [m % 12 for m in range(thismonth + 1, thismonth + 13)]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1]
Or if you only want some months you could to this:
>>> thismonth = 1
>>> themonths = [0, 1, 2, 8]
>>> [m % 12 for m in range(thismonth + 1, thismonth + 13) if m % 12 in themonths]
[2, 8, 0, 1]
Note that in this scheme `Jan = 0 .... Dec = 11`. If you want `Jan = 1` you
could just add 1 to the resulting numbers (i.e. `[m % 12 + 1 for ... if m % 12
+ 1 in themonths]`) . But I think `Jan = 0` is a better system, at least for
the backend.
|
python, numpy boolean array: negation in where statement
Question: with:
import numpy as np
array = get_array()
I need to do the following thing:
for i in range(len(array)):
if random.uniform(0, 1) < prob:
array[i] = not array[i]
with array being a numpy.array.
I wish I could do something similar to:
array = np.where(np.random.rand(len(array)) < prob, not array, array)
but I obtain the following result (referring to 'not array'):
> The truth value of an array with more than one element is ambiguous. Use
> a.any() or a.all()
Why can I take the value of array but not its negation?
Currently I solved with:
array = np.where(np.random.rand(len(array)) < prob, - array + 1, array)
but it looks really clumsy to me.
Thank you for your help
p.s.: I don't care if the statement modifies array or not. I just need the
result of the operation.
just another question: I want to do this change for 2 reasons: readability and
efficiency. Is there a real performance improvement with it? Thank you again
Answer: I suggest using
array ^= numpy.random.rand(len(array)) < prob
This is probably the most efficient way of getting the desired result. It will
modify the array in place, using "xor" to invert the entries which the random
condition evaluates to `True` for.
> Why can I take the value of array but not its negation?
You can't take the truth value of the array either:
>>> bool(array)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The `not` operator implicitly tries to convert its operand to `bool`, and then
returns the opposite truth value. It is not possible to overload `not` to
perform any other behaviour. To negate a NumPy array of `bool`s, you can use
~array
or
numpy.logical_not(array)
or
numpy.invert(array)
though.
|
Does Jython support Tkinter
Question: Does Jython support Tkinter ? If I code a program in Python and put a GUI
front end on it with Tkinter, how hard would it be to do the same program in
Jython? Or is there a better solution for Jython GUI's?
When i try java -jar "jarname" It is showing error as : import Tkinter,
tkFileDialog, tkMessageBox, tempfile, shutil ImportError: No module named
Tkinter
How can i resolve this............ Thanks in advance.....:)
Answer: No, it does not. You'll have to rewrite your application using swt, swing,
etc. There is no Jython-CPython compatible gui, unless you are coding for the
web.
|
python unzip -- tremendously slow?
Question: Can somebody please explain the following mystery?
I created a binary file of size ~37[MB]. zipping it in Ubuntu -- using the
terminal -- took less than 1[sec]. I then tried python: zipping it
programatically (using the zipfile module) took also about 1[sec].
I then tried to unzip the zip file I created. In Ubuntu -- using the terminal
-- this took less than 1[sec].
In python, the code to unzip (used the zipfile module) took close to 37[sec]
to run! any ideas why?
Answer: I was struggling to unzip/decompress/extract zip files with Python as well and
that "create ZipFile object, loop through its .namelist(), read the files and
write them to file system" low-level approach didn't seem very Python. So I
started to dig [zipfile
objects](http://docs.python.org/library/zipfile.html#zipfile-objects) that I
believe not very well documented and covered all the object methods:
>>> from zipfile import ZipFile
>>> filepath = '/srv/pydocfiles/packages/ebook.zip'
>>> zip = ZipFile(filepath)
>>> dir(zip)
['NameToInfo', '_GetContents', '_RealGetContents', '__del__', '__doc__', '__enter__', '__exit__', '__init__', '__module__', '_allowZip64', '_didModify', '_extract_member', '_filePassed', '_writecheck', 'close', 'comment', 'compression', 'debug', 'extract', 'extractall', 'filelist', 'filename', 'fp', 'getinfo', 'infolist', 'mode', 'namelist', 'open', 'printdir', 'pwd', 'read', 'setpassword', 'start_dir', 'testzip', 'write', 'writestr']
There we go the "extractall" method works just like [tarfile's
extractall](http://docs.python.org/library/tarfile.html#tarfile.TarFile.extractall)
! (on python 2.6 and 2.7 but NOT 2.5)
Then the performance concerns; the file ebook.zip is **84.6 MB** (mostly pdf
files) and uncompressed folder is 103 MB, zipped by default "Archive Utility"
under MacOSx 10.5. So I did the same with Python's
[timeit](http://docs.python.org/library/timeit.html) module:
>>> from timeit import Timer
>>> t = Timer("filepath = '/srv/pydocfiles/packages/ebook.zip'; \
... extract_to = '/tmp/pydocnet/build'; \
... from zipfile import ZipFile; \
... ZipFile(filepath).extractall(path=extract_to)")
>>>
>>> t.timeit(1)
1.8670060634613037
which took less than 2 seconds on a heavy loaded machine that has 90% of the
memory is being used by other applications.
Hope this helps someone.
|
How to import Tkinter for distributed Jython jar formed from Python code
Question: I have tried the steps mentioned at
<http://wiki.python.org/jython/JythonFaq/DistributingJythonScripts> and formed
myapp.jar from my python code and my main.py script uses Tkinter for GUI...but
when i try to run it :
java -jar myapp.jar main.py it is showing
import Tkinter, tkFileDialog, tkMessageBox, tempfile, shutil ImportError: No
module named Tkinter
How to avoid it....Early response will be highly appreciated.
Thanks in advance.
Answer: Tkinter is not included with Jython, and to the best of my knowledge nobody
has ported it.
If you need to do a GUI in Jython, you'll probably need to use a Java library
like Swing or SWT.
|
OpenStreetMap generate georeferenced image
Question: I'm new to Openstreetmap and mapnick,
I'm trying to export map image which will be geo-referenced (So it can be used
in other applications)
I've installed osm and mapnik inside ubuntu virtual machine
I've tried using generate_image.py script, but generated image is not equal to
the bounding box. My python knowledge is not good enough for me to fix the
script.
I've also tried using nik2img.py script using verbose mode, for example:
nik2img.py osm.xml sarajevo.png --srs 900913 --bbox 18.227 43.93 18.511 43.765 --dimensions 10000 10000
and tried using the log bounding box
Step: 11 // --> Map long/lat bbox: Envelope(18.2164733537,43.765,18.5215266463,43.93)
Unfortunately generated image is not equal to the bounding box :(
How can I change scripts so I can georeference generated image? Or do you know
an easier way to accomplish this task? Image i'm getting using the
<http://www.openstreetmap.org/> export is nicely geo-referenced, but it's not
big enough :(
Answer: I've managed to change **generate_tiles.py** to generate 1024x1024 images
together with correct bounding box
Changed script is available bellow
#!/usr/bin/python
from math import pi,cos,sin,log,exp,atan
from subprocess import call
import sys, os
from Queue import Queue
import mapnik
import threading
DEG_TO_RAD = pi/180
RAD_TO_DEG = 180/pi
# Default number of rendering threads to spawn, should be roughly equal to number of CPU cores available
NUM_THREADS = 4
def minmax (a,b,c):
a = max(a,b)
a = min(a,c)
return a
class GoogleProjection:
def __init__(self,levels=18):
self.Bc = []
self.Cc = []
self.zc = []
self.Ac = []
c = 1024
for d in range(0,levels):
e = c/2;
self.Bc.append(c/360.0)
self.Cc.append(c/(2 * pi))
self.zc.append((e,e))
self.Ac.append(c)
c *= 2
def fromLLtoPixel(self,ll,zoom):
d = self.zc[zoom]
e = round(d[0] + ll[0] * self.Bc[zoom])
f = minmax(sin(DEG_TO_RAD * ll[1]),-0.9999,0.9999)
g = round(d[1] + 0.5*log((1+f)/(1-f))*-self.Cc[zoom])
return (e,g)
def fromPixelToLL(self,px,zoom):
e = self.zc[zoom]
f = (px[0] - e[0])/self.Bc[zoom]
g = (px[1] - e[1])/-self.Cc[zoom]
h = RAD_TO_DEG * ( 2 * atan(exp(g)) - 0.5 * pi)
return (f,h)
class RenderThread:
def __init__(self, tile_dir, mapfile, q, printLock, maxZoom):
self.tile_dir = tile_dir
self.q = q
self.m = mapnik.Map(1024, 1024)
self.printLock = printLock
# Load style XML
mapnik.load_map(self.m, mapfile, True)
# Obtain <Map> projection
self.prj = mapnik.Projection(self.m.srs)
# Projects between tile pixel co-ordinates and LatLong (EPSG:4326)
self.tileproj = GoogleProjection(maxZoom+1)
def render_tile(self, tile_uri, x, y, z):
# Calculate pixel positions of bottom-left & top-right
p0 = (x * 1024, (y + 1) * 1024)
p1 = ((x + 1) * 1024, y * 1024)
# Convert to LatLong (EPSG:4326)
l0 = self.tileproj.fromPixelToLL(p0, z);
l1 = self.tileproj.fromPixelToLL(p1, z);
# Convert to map projection (e.g. mercator co-ords EPSG:900913)
c0 = self.prj.forward(mapnik.Coord(l0[0],l0[1]))
c1 = self.prj.forward(mapnik.Coord(l1[0],l1[1]))
# Bounding box for the tile
if hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 800:
bbox = mapnik.Box2d(c0.x,c0.y, c1.x,c1.y)
else:
bbox = mapnik.Envelope(c0.x,c0.y, c1.x,c1.y)
render_size = 1024
self.m.resize(render_size, render_size)
self.m.zoom_to_box(bbox)
self.m.buffer_size = 128
# Render image with default Agg renderer
im = mapnik.Image(render_size, render_size)
mapnik.render(self.m, im)
im.save(tile_uri, 'png256')
print "Rendered: ", tile_uri, "; ", l0 , "; ", l1
# Write geo coding informations
file = open(tile_uri[:-4] + ".tab", 'w')
file.write("!table\n")
file.write("!version 300\n")
file.write("!charset WindowsLatin2\n")
file.write("Definition Table\n")
file.write(" File \""+tile_uri[:-4]+".jpg\"\n")
file.write(" Type \"RASTER\"\n")
file.write(" ("+str(l0[0])+","+str(l1[1])+") (0,0) Label \"Pt 1\",\n")
file.write(" ("+str(l1[0])+","+str(l1[1])+") (1023,0) Label \"Pt 2\",\n")
file.write(" ("+str(l1[0])+","+str(l0[1])+") (1023,1023) Label \"Pt 3\",\n")
file.write(" ("+str(l0[0])+","+str(l0[1])+") (0,1023) Label \"Pt 4\"\n")
file.write(" CoordSys Earth Projection 1, 104\n")
file.write(" Units \"degree\"\n")
file.close()
def loop(self):
while True:
#Fetch a tile from the queue and render it
r = self.q.get()
if (r == None):
self.q.task_done()
break
else:
(name, tile_uri, x, y, z) = r
exists= ""
if os.path.isfile(tile_uri):
exists= "exists"
else:
self.render_tile(tile_uri, x, y, z)
bytes=os.stat(tile_uri)[6]
empty= ''
if bytes == 103:
empty = " Empty Tile "
self.printLock.acquire()
print name, ":", z, x, y, exists, empty
self.printLock.release()
self.q.task_done()
def render_tiles(bbox, mapfile, tile_dir, minZoom=1,maxZoom=18, name="unknown", num_threads=NUM_THREADS):
print "render_tiles(",bbox, mapfile, tile_dir, minZoom,maxZoom, name,")"
# Launch rendering threads
queue = Queue(32)
printLock = threading.Lock()
renderers = {}
for i in range(num_threads):
renderer = RenderThread(tile_dir, mapfile, queue, printLock, maxZoom)
render_thread = threading.Thread(target=renderer.loop)
render_thread.start()
#print "Started render thread %s" % render_thread.getName()
renderers[i] = render_thread
if not os.path.isdir(tile_dir):
os.mkdir(tile_dir)
gprj = GoogleProjection(maxZoom+1)
ll0 = (bbox[0],bbox[3])
ll1 = (bbox[2],bbox[1])
for z in range(minZoom,maxZoom + 1):
px0 = gprj.fromLLtoPixel(ll0,z)
px1 = gprj.fromLLtoPixel(ll1,z)
# check if we have directories in place
zoom = "%s" % z
if not os.path.isdir(tile_dir + zoom):
os.mkdir(tile_dir + zoom)
for x in range(int(px0[0]/1024.0),int(px1[0]/1024.0)+1):
# Validate x co-ordinate
if (x < 0) or (x >= 2**z):
continue
# check if we have directories in place
str_x = "%s" % x
if not os.path.isdir(tile_dir + zoom + '/' + str_x):
os.mkdir(tile_dir + zoom + '/' + str_x)
for y in range(int(px0[1]/1024.0),int(px1[1]/1024.0)+1):
# Validate x co-ordinate
if (y < 0) or (y >= 2**z):
continue
str_y = "%s" % y
tile_uri = tile_dir + zoom + '_' + str_x + '_' + str_y + '.png'
# Submit tile to be rendered into the queue
t = (name, tile_uri, x, y, z)
queue.put(t)
# Signal render threads to exit by sending empty request to queue
for i in range(num_threads):
queue.put(None)
# wait for pending rendering jobs to complete
queue.join()
for i in range(num_threads):
renderers[i].join()
if __name__ == "__main__":
home = os.environ['HOME']
try:
mapfile = "/home/emir/bin/mapnik/osm.xml" #os.environ['MAPNIK_MAP_FILE']
except KeyError:
mapfile = "/home/emir/bin/mapnik/osm.xml"
try:
tile_dir = os.environ['MAPNIK_TILE_DIR']
except KeyError:
tile_dir = home + "/osm/tiles/"
if not tile_dir.endswith('/'):
tile_dir = tile_dir + '/'
#-------------------------------------------------------------------------
#
# Change the following for different bounding boxes and zoom levels
#
#render sarajevo at 16 zoom level
bbox = (18.256, 43.785, 18.485, 43.907)
render_tiles(bbox, mapfile, tile_dir, 16, 16, "World")
|
Use IronPython to access COM object in a browser?
Question: I am trying to use a COM object by IronPython in a browser. I have tried the
following code in ipy.exe and it works fine:
from System import Type, Activator
Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"))
But if I use the code a a browser like this:
<html>
<script type="text/python">
from System import Type, Activator
Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"))
</script>
</html>
It just doesn't work.
I want to know if there are restrictions when using IronPython in a browser.
Did I miss something?
Answer: Silverlight, which is what allows IronPython in the browser has strict
security. Silverlight's sandbox requires the IronPython code to run in an
internet domain (localhost included), but not the local domain (directly from
the file-system). You might find some more information from Jimmy Schementi's
[blog](http://blog.jimmy.schementi.com/2010/03/pycon-2010-python-in-
browser.html).
|
python feedparser
Question: How would you parse xml data as follows with python feedparser
<Book_API>
<Contributor_List>
<Display_Name>Jason</Display_Name>
</Contributor_List>
<Contributor_List>
<Display_Name>John Smith</Display_Name>
</Contributor_List>
</Book_API>
Answer: That doesn't look like any sort of RSS/ATOM feed. I wouldn't use feedparser at
all for that, I would use lxml. In fact, feedparser can't make any sense of it
and drops the "Jason" contributor in your example.
from lxml import etree
data = <fetch the data somehow>
root = etree.parse(data)
Now you have a tree of xml objects. How to do it in lxml more specifically is
impossible to say until you actually give valid XML data. ;)
|
constants in Python: at the root of the module or in a namespace inside the module?
Question: I'm building a Python module with about a hundred constants.
I would like to avoid naming issues when people import my module so I was
wondering what would be the best way to do it.
MY_CONSTANT = 1
MY_SECOND_CONSTANT = 2
...
MY2_CONSTANT = "a"
MY2_SECOND_CONSTANT = "b"
...
Or
class My:
CONSTANT = 1
SECOND_CONSTANT = 2
...
class My2
CONSTANT = "a"
SECOND_CONSTANT = "b"
...
Or maybe another of your suggestions?
Coming from Java, I surely prefer the second way, but some might find it
overkill...
Answer: Well, it depends. Usually, constants are defined at module level. But if you
have many constants for `category_a` and `category_b`, it might even make
sense to add a subpackage `constants` with modules `constants.category_a` and
`constants.category_b`.
I would refrain from using a `class` \- it could be instanciated, which
wouldn't make sense, and it has no advantage over a module apart from allowing
you to cram more than one into one physical file (which you propably shouldn't
if there are so many constants). The Java version would propably use a static
class, but the Python equivalent is a module.
Name clashes aren't an issue in Python except when you `import *` \- [but you
shouldn't do that anyway](http://docs.python.org/howto/doanddont.html#from-
module-import). As long as there are no name clashes inside the module, rest
assured that the user will neither pull out all the names from your module
into his own nor import it under a name that clashes with another module.
|
Submit without the use of a submit button, Mechanize
Question: So, I started out with Mechanize, and apparently the first thing I try it on
is a monkey-rhino-level high JavaScript navigated site.
Now the thing I'm stuck on is submitting the form.
Normally I'd do a submit using the Mechanize built-in submit() function.
import mechanize
browser = mechanize.Browser()
browser.select_form(name = 'foo')
browser.form['bar'] = 'baz'
browser.submit()
This way it'd use the submit button that's available in the HTML form.
However, the site I'm stuck on had to be one that doesn't use HTML submit
buttons... No, they're trying to be JavaScript gurus, and do a submit via
JavaScript.
The usual submit() doesn't seem to work with this.
So... Is there a way to get around this?
Any help is appreciated. Many thanks!
\--[Edit]--
The JavaScript function I'm stuck on:
function foo(bar, baz) {
var qux = document.forms["qux"];
qux.bar.value = bar.split("$").join(":");
qux.baz.value = baz;
qux.submit();
}
What I did in Python (and what doesn't work):
def foo(browser, bar, baz):
qux = browser.select_form("qux")
browser.form[bar] = ":".join(bar.split("$"))
browser.form[baz] = baz
browser.submit()
Answer: Three ways:
The first method is preferable if the form is submitted using the POST/GET
method, otherwise you'll have to resort to second and third method.
1. Submitting the form manually and check for POST/GET requests, their parameters and the post url required to submit the form. Popular tools for checking headers are the Live HTTP headers extension and Firebug extension for Firefox, and Developer Tools extension for Chrome. An example of using the POST/GET method:
import mechanize
import urllib
browser = mechanize.Browser()
#These are the parameters you've got from checking with the aforementioned tools
parameters = {'parameter1' : 'your content',
'parameter2' : 'a constant value',
'parameter3' : 'unique characters you might need to extract from the page'
}
#Encode the parameters
data = urllib.urlencode(parameters)
#Submit the form (POST request). You get the post_url and the request type(POST/GET) the same way with the parameters.
browser.open(post_url,data)
#Submit the form (GET request)
browser.open(post_url + '%s' % data)
2. Rewrite the javascript and execute it in Python. Check out spidermonkey.
3. Emulate a full browser. Check out Selenium and Windmill.
|
Python Parameter pass to prevent sql injection. Why is this giving an error?
Question:
from django.db import connection, transaction
def pk_dt_catalog(p_CAT_ID,p_COMMONS_ID):
c1 = connection.cursor()
sql = "SELECT COMMONS_ID, CAT_ID, CAT_NAME
FROM DT_CATALOG"
sql = sql + " WHERE CAT_ID = %s
AND COMMONS_ID = %s "
param =(p_CAT_ID, p_COMMONS_ID)
c1.execute(sql, param)
return c1
>>> c = dt_catalog.pk_dt_catalog(513704,401)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "dt_catalog.py", line 24, in pk_dt_catalog
c1.execute(sql,(p_CAT_ID, p_COMMONS_ID,))
cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number
Answer: In your code, you're using `%s` which is python substition string syntax,
which expects the substitution values on the same line, e.g.
sql = sql + " WHERE CAT_ID = %s
AND COMMONS_ID = %s " % (p_CAT_ID, p_COMMONS_ID)
However, this (as stated already) is not the best way because (a) it can be a
SQL injection vulnerability; and (b) it will probably cause poor database
performance due to each call requiring a hard parse of a new SQL statement.
Instead, you should use Oracle Bind variable syntax, e.g.:
c1 = connection.cursor()
sql = "SELECT COMMONS_ID, CAT_ID, CAT_NAME
FROM DT_CATALOG"
sql = sql + " WHERE CAT_ID = :foo
AND COMMONS_ID = :bar "
param = (p_CAT_ID, p_COMMONS_ID)
c1.execute(sql, param)
return c1
More info: <http://guyharrison.squarespace.com/blog/2010/1/17/best-practices-
with-python-and-oracle.html>
The above example uses positional binding, i.e. the first parameter is bound
to the first bind placeholder, and the second parameter in the list is bound
to the second placeholder.
A nicer method is using a dict to assign values to specific bind variables by
name. This is useful when it is difficult to know the order in which the
placeholders have been added to the query, and makes the code easier to read
and maintain:
c1 = connection.cursor()
sql = "SELECT COMMONS_ID, CAT_ID, CAT_NAME
FROM DT_CATALOG"
sql = sql + " WHERE CAT_ID = :foo
AND COMMONS_ID = :bar "
param = {"foo": p_CAT_ID, "bar": p_COMMONS_ID}
c1.execute(sql, param)
return c1
More examples and tutorials: <http://st-
curriculum.oracle.com/obe/db/11g/r2/prod/appdev/opensrclang/pythonhol2010_db/python_db.htm>
|
Mocking out methods on any instance of a python class
Question: I want to mock out methods on any instance of some class in the production
code in order to facilitate testing. Is there any library in Python which
could facilitate this?
Basically, I want to do the following, but in Python (the following code is
Ruby, using the Mocha library):
def test_stubbing_an_instance_method_on_all_instances_of_a_class
Product.any_instance.stubs(:name).returns('stubbed_name')
assert_equal 'stubbed_name', SomeClassThatUsesProduct.get_new_product_name
end
The important thing to note from above is that I need to mock it out on the
class level, since I'm actually need to mock out methods on an instance
created by the thing I'm testing.
Use Case:
I have a class `QueryMaker` which calls a method on an instance of
`RemoteAPI`. I want to mock out the `RemoteAPI.get_data_from_remote_server`
method to return some constant. How do I do this inside a test without having
to put a special case within the `RemoteAPI` code to check for what
environment it's running in.
Example of what I wanted in action:
# a.py
class A(object):
def foo(self):
return "A's foo"
# b.py
from a import A
class B(object):
def bar(self):
x = A()
return x.foo()
# test.py
from a import A
from b import B
def new_foo(self):
return "New foo"
A.foo = new_foo
y = B()
if y.bar() == "New foo":
print "Success!"
Answer: Needing to mock out methods when testing is very common and there are lots of
tools to help you with it in Python. The danger with "monkey patching" classes
like this is that if you don't _undo_ it afterwards then the class has been
modified for all other uses throughout your tests.
My library mock, which is one of the most popular Python mocking libraries,
includes a helper called "patch" that helps you to safely patch methods or
attributes on objects and classes during your tests.
The mock module is available from:
<http://pypi.python.org/pypi/mock>
The patch decorator can be used as a context manager or as a test decorator.
You can either use it to patch out with functions yourself, or use it to
automatically patch with Mock objects that are very configurable.
from a import A
from b import B
from mock import patch
def new_foo(self):
return "New foo"
with patch.object(A, 'foo', new_foo):
y = B()
if y.bar() == "New foo":
print "Success!"
This handles the unpatching for you automatically. You could get away without
defining the mock function yourself:
from mock import patch
with patch.object(A, 'foo') as mock_foo:
mock_foo.return_value = "New Foo"
y = B()
if y.bar() == "New foo":
print "Success!"
|
python click event scope issue in pygame
Question: I've created a GameObject class, using the python pygame library, which draws
a rectangle on the screen. I would like to integrate an event handler which
would allow me to draw the rectangle around, however the click events for the
GameObject are not registering. Here are a couple snippets of code from the
class:
` def on_event(self, event):`
if event.type == pygame.MOUSEBUTTONDOWN:
print "I'm a mousedown event!"
self.down = True
self.prev_x=pygame.mouse.get_pos(0)
self.prev_y=pygame.mouse.get_pos(1)
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
self.down = False
`def on_draw(self, surface): `
#paints the rectangle the particular color of the square
pygame.draw.rect(surface, pygame.Color(self.red, self.green, self.blue), self.geom)`
Do I need to make the rect into an image for the mouse events to register, or
is there some other way I can drag this box around?
Answer: > > Do I need to make the rect into an image for the mouse events to register,
> or is there some other way I can drag this box around?
No image required. Solution:
Note:
1. You already use event to get MOUSEMOTION, so use event's data: .pos, and .button from the event.
2. use [Color](http://www.pygame.org/docs/ref/color.html) class to store as a single variable:
self.color_bg = Color("blue") self.color_fg = Color(20,20,20) print
self.color_bg.r, self.color_bg.g, self.color_bg.b
Note: I kept some code slightly more verbose to make it easier to read, ex:
you could do:
# it uses
x,y = event.pos
if b.rect.collidepoint( (x,y) ):
# you could do (the same thing)
if b.rect.collidepoint( event.pos* ):
Solution:
import pygame
from pygame.locals import *
from random import randint
class Box(object):
"""simple box, draws rect and Color"""
def __init__(self, rect, color):
self.rect = rect
self.color = color
def draw(self, surface):
pygame.draw.rect(surface, self.color, self.rect)
class Game(object):
def __init__(self):
# random loc and size boxes
# target = box to move
self.target = None
for i in range(5):
x,y = randint(0, self.width), randint(0, self.height)
size = randint(20, 200)
r = Rect(0,0,0,0)
# used 0 because: will be using propery, but have to create it first
r.size = (size, size)
r.center = (x, y)
self.boxes.append( Box(r, Color("red") ))
def draw(self):
for b in self.boxes: b.draw()
def on_event(self, event):
# see: http://www.pygame.org/docs/ref/event.html
if event.type == MOUSEBUTTONDOWN and event.button = 1:
# LMB down = target if collide
x,y = event.pos
for b in self.boxes:
if b.rect.collidepoint( (x,y) ): self.target = b
elif event.type == MOUSEBUTTONUP and event.button = 1:
# LMB up : untarget
self.target = None
elif event.type == MOUSEMOTION:
x,y = event.pos
# is a valid Box selected?
if self.target is not None:
self.target.rect.center = (x,y)
|
Calculating pi in Python using geometry
Question: I'm posting this code with the hope that this community will be willing to
assist me in ironing out some bugs I can't seem to be able to tackle. It's
quite short, is intended to guess pi, and is not intended to replace already
efficiently working approaches. This is not an assignment.
# this code is completely broken
from math import sqrt
def get_y(x, r):
return sqrt((r^2.0)-(x^2.0))
def get_distance(x1, y1, x2, y2):
return sqrt( (x2-x1)^2.0 + (y2-y1)^2.0 )
def c(r):
def range(b):
a = 0
while a < b:
yield a
a = a + 1
circumference = 0.0
for x1 in range(r):
x2 = x1 + 1.0
y1 = get_y(x1, r)
y2 = get_y(x2, r)
distance = get_distance(x1, y1, x2, x2)
circumference = circumference + distance
circumference = circumference * 4
return circumference
print get_y(0, 4)
radius = 400.0
print "%.64f" % (c(radius) / radius * 2)
Answer:
# Not broken anymore, prints 3.1415559...
from math import sqrt
def get_y(x, r):
return sqrt((r**2.0)-(x**2.0)) # First mistake: ** is exponentiation, not ^
def get_distance(x1, y1, x2, y2):
return sqrt( (x2-x1)**2.0 + (y2-y1)**2.0 )
def c(r):
# def range(b): # redundant
# a = 0
# while a < b:
# yield a
# a = a + 1
circumference = 0.0
for x1 in range(r):
x2 = x1 + 1.0
y1 = get_y(x1, r)
y2 = get_y(x2, r)
distance = get_distance(x1, y1, x2, y2) # second mistake, x2, x2 --> x2, y2
circumference = circumference + distance
circumference = circumference * 4
return circumference
print get_y(0, 4)
radius = 400.0
print "%.64f" % (c(radius) / (radius * 2)) # third mistake: / radius * 2 --> / (radius*2)
|
Python logging in interactive sessions
Question: I am trying to implement logging in my Python 2.7 applications and have found
it very useful. However, I have noticed that when running Python interactively
each logging message prints multiple times. The number of times the message is
printed is the same as the number of times I have previously run the script,
so it seems that the logger is not being cleaned up properly at the end of the
script (I would guess). Consider the following example:
import sys
import logging
def main(argv=None):
log = logging.getLogger('test')
log.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter("%(message)s"))
log.addHandler(console_handler)
log.info('Starting something...')
log.info('Doing something...')
log.info('Finished something.')
logging.shutdown()
if __name__=='__main__':
sys.exit(main(sys.argv[1:]))
Typing
>>> import file.py
>>> file.main()
yields the following:
Starting something...
Doing something...
Finished something.
Then typing `file.main()` a second time yields:
Starting something...
Starting something...
Doing something...
Doing something...
Finished something.
Finished something.
Repeating a third time would give three or each message and so on. Does anyone
know why this is happening - is this the expected behaviour of the logging
module and, if so, how can I change this? The above script only prints one of
each message if run as a script (`python file.py`), as expected.
Answer: Yes, you are creating and reusing a single instance of your logger. Each
handler added to that logger is also logging a message.
You probably want logging setup to be at the module level or in a separate
function so you only run it once.
Maybe something like this:
import atexit
import sys
import logging
log = logging.getLogger('test')
log.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter("%(message)s"))
log.addHandler(console_handler)
def shutdown_logging():
logging.shutdown()
atexit.register(shutdown_logging)
def main(argv=None):
log.info('Starting something...')
log.info('Doing something...')
log.info('Finished something.')
if __name__=='__main__':
sys.exit(main(sys.argv[1:]))
|
Is there an exact replacement for the old functional.curry?
Question: I am trying to run this snippet from
<http://www.ibm.com/developerworks/linux/library/l-prog3.html> on a python 2.6
runtime.
from functional import *
taxcalc = lambda income,rate,deduct: (income-(deduct))*rate
taxCurry = curry(taxcalc)
taxCurry = taxCurry(50000)
taxCurry = taxCurry(0.30)
taxCurry = taxCurry(10000)
print "Curried taxes due =",taxCurry
print "Curried expression taxes due =", \
curry(taxcalc)(50000)(0.30)(10000)
Ok, so I understand from <http://www.python.org/dev/peps/pep-0309/> that
functional is renamed to functools and curry to partial but just doing the
renames doesn't help. I get the error:
taxCurry = taxCurry(50000)
TypeError: <lambda>() takes exactly 3 arguments (1 given)
The following does work but do I really have to change it so much?
from functools import partial
taxcalc = lambda income,rate,deduct: (income-(deduct))*rate
taxCurry = partial(taxcalc)
taxCurry = partial(taxCurry, 50000)
taxCurry = partial(taxCurry, 0.30)
taxCurry = partial(taxCurry, 10000)
print "Curried taxes due =", taxCurry()
print "Curried expression taxes due =", \
taxcalc(50000, 0.30, 10000)
Is there a better way of preserving the mechanics of the original example?
Lastly was the original example truly currying or just partial application?
(as per <http://www.uncarved.com/blog/not_currying.mrk>)
Thanks for your time
Answer: I guess the reason why they changed it is because Python is dynamically typed.
This means that it would be really hard to debug the original `curry` code if
anything goes wrong - much harder than in a language like Haskell where you
would directly get a nice type error. So I think it was a reasonable decision
to replace it with the more explicit `partial` version (looks more pythonic to
me).
Your example is also a bit strange, since you just reassigning the partially
applied functions to the same name. Normally the partially applied function
would be given to another function. At least that is the only reasonable use
case in Python I can think of.
|
problem implementing get_filename() method for GtkFileChooser Button in glade and python?
Question: As a newbee I am trying to create a basic theme installer using Glade and
python. Everything is working fine but i am not able to find anywhere how to
use get_filename() method for gtkFileChooserButton. My Glade File Looks Like
this.
<?xml version="1.0"?>
<interface>
<requires lib="gtk+" version="2.16"/>
<!-- interface-naming-policy project-wide -->
<object class="GtkWindow" id="main">
<property name="title" translatable="yes">Maininin</property>
<property name="window_position">center</property>
<signal name="destroy" handler="on_main_destroy"/>
<child>
<object class="GtkVBox" id="vbox1">
<property name="visible">True</property>
<child>
<object class="GtkLabel" id="INFO">
<property name="visible">True</property>
<property name="label" translatable="yes">Theme</property>
</object>
<packing>
<property name="expand">False</property>
<property name="padding">28</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkHButtonBox" id="hbuttonbox1">
<property name="visible">True</property>
<property name="layout_style">spread</property>
<child>
<object class="GtkFileChooserButton" id="DD">
<property name="visible">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="pack_type">end</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<object class="GtkHButtonBox" id="hbuttonbox2">
<property name="visible">True</property>
<property name="layout_style">spread</property>
<child>
<object class="GtkButton" id="Add">
<property name="label">gtk-add</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_stock">True</property>
<signal name="clicked" handler="on_Add_clicked"/>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkButton" id="Quit">
<property name="label">gtk-quit</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_stock">True</property>
<signal name="clicked" handler="on_Quit_clicked"/>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="pack_type">end</property>
<property name="position">1</property>
</packing>
</child>
</object>
<packing>
<property name="position">2</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="WARN">
<property name="visible">True</property>
<property name="label" translatable="yes">Warning</property>
</object>
<packing>
<property name="expand">False</property>
<property name="padding">37</property>
<property name="position">3</property>
</packing>
</child>
</object>
</child>
`
And Python Code is:
import sys
try:
import pygtk
pygtk.require("2.0")
except:
pass
try:
import gtk
except:
print("GTK Not Availible")
sys.exit(1)
class workplz(object):
def __init__( self ):
builder = gtk.Builder()
builder.add_from_file("heme.glade")
builder.connect_signals({"on_main_destroy" : self.quit, "on_Add_clicked" : self.add, "on_Quit_clicked" : self.quit})
self._window = builder.get_object("main")
self._window.show()
def add(self, widget):
target=DD.get_filename()
print target
def quit(self, widget):
sys.exit(0)
if __name__ == "__main__":
wine = workplz()
gtk.main()
what is the right way of doing it???
Answer: I believe if you would get your GtkFileChooserButton object from the builder
and save a reference to it as a member of `workplz` class you could query it
in the `add` signal handler. See if script below would work for you:
class workplz(object):
def __init__( self ):
builder = gtk.Builder()
builder.add_from_file("heme.glade")
builder.connect_signals({"on_main_destroy" : self.quit, "on_Add_clicked" : self.add, "on_Quit_clicked" : self.quit})
# get GtkFileChooserButton object
self.DD = builder.get_object('DD')
self._window = builder.get_object("main")
self._window.show()
def add(self, widget):
target = self.DD.get_filename()
print target
def quit(self, widget):
sys.exit(0)
hope this helps, regards
|
Combining multiple csv files together and also adding a column during concatenation
Question: I have a set of files I am trying to import into mySql.
Each csv file looks like this:
Header1;Header2;Header3;Header4;Header5
Data1;Data2;Data3;Data4;Data5;
Data1;Data2;Data3;Data4;Data5;
Data1;Data2;Data3;Data4;Data5;
Data1;Data2;Data3;Data4;Data5;
Data may contain spaces, periods or a full colon. They absolutely will not
contain a semi-colon so that is a valid delimiter. They also will not contain
\n or any other newline characters.
Example Data
2010.08.30 18:34:59
0.7508
String Of Characters With Spaces In Them
Each file has a unique name to it. The names all follow the following pattern
Token1_Token2_Token3.csv
I am interested in combining a lot of these csv files (on the order of several
hundred) into one CSV file. Files can range from 10KB to 400MB. Ultimately, I
want to send it over to mysql. Don't worry about getting rid of the individual
header rows; I can do that in MySql easily.
I would like the final CSV file to look like this:
Header1,Header2,Header3,Header4,Header5,FileName
Data1,Data2,Data3,Data4,Data5,Token1
Data1,Data2,Data3,Data4,Data5,Token1
Data1,Data2,Data3,Data4,Data5,Token1
Data1,Data2,Data3,Data4,Data5,Token1
Data1,Data2,Data3,Data4,Data5,Token1
I dont care about any of the other tokens. I can also live if the solution
just dumps each csv filename into the Token1 field because, again, I can parse
that in mySql easily.
Please help me!! I've spent over 10 hours on what should be a relatively easy
problem.
Technologies available:
awk windows batch linux bash powershell perl python php mysql-import
This is a server box so I wont be able to compile anything but if you give me
a Java solution I will definitely try to run it on the box.
Answer: Using [`Text::CSV`](http://search.cpan.org/perldoc?Text%3a%3aCSV):
## Program
#!/usr/bin/env perl
use strict;
use warnings;
use File::Find;
use Text::CSV;
my $semi_colon_csv = Text::CSV->new( { 'sep_char' => ';', } );
my $comma_csv = Text::CSV->new( {
'sep_char' => ',',
'eol' => "\n",
} );
open my $fh_output, '>', 'output.csv' or die $!;
sub convert {
my $file_name = shift;
open my $fh_input, '<', $file_name or die $!;
# header
my $row = $semi_colon_csv->getline($fh_input);
$comma_csv->print( $fh_output, [ @$row, $file_name ] );
while ( $row = $semi_colon_csv->getline($fh_input) ) {
pop @$row unless $row->[-1]; # remove trailing semi-colon from input
my ($token) = ( $file_name =~ /^([^_]+)/ );
$comma_csv->print( $fh_output, [ @$row, $token ] );
}
}
sub wanted {
return unless -f;
convert($_);
}
my $path = 'csv'; # assuming that all your CSVs are in ./csv/
find( \&wanted, $path );
## Output (output.csv)
Header1,Header2,Header3,Header4,Header5,Token1_Token2_Token3.csv
Data1,Data2,Data3,Data4,Data5,Token1
Data1,Data2,Data3,Data4,Data5,Token1
Data1,Data2,Data3,Data4,Data5,Token1
Data1,Data2,Data3,Data4,Data5,Token1
|