text
stringlengths 226
34.5k
|
---|
How can I can I programatically post a note to Google Reader?
Question: I use my Google Reader notes as a place to store bookmarks and small snippets
of information. I would like to write a small script to let me post notes from
the command line (I prefer Python,but an answer using any language will be
accepted).
[This project](http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI) seemed
to be a be a good place to start & some more up-to-date information
[here](http://blog.martindoms.com/2009/08/15/using-the-google-reader-api-
part-1/). The process appears to be:
1. Get a SID (session ID) from [https://www.google.com/accounts/ClientLogin?service=reader&Email=](https://www.google.com/accounts/ClientLogin?service=reader&Email=){0}&Passwd={1}
2. Get a temporary token from <http://www.google.com/reader/api/0/token>
3. Make a POST to <http://www.google.com/reader/api/0/item/edit> with the correct field values
So... step 2 above always fails for me (get a 403 forbidden) and trying Martin
Doms C# code has the same issue. It looks like Google no longer use this
method for authentication.
Update... [This comment](http://blog.martindoms.com/2010/01/20/using-the-
google-reader-api-part-3/#comment-105) got me up and running. I can now log in
and get a token. Now I just need to figure out how to POST the note. My code
is below:
import urllib2
# Step 1: login to get session auth
email = 'myuser@gmail.com'
passwd = 'mypassword'
response = urllib2.urlopen('https://www.google.com/accounts/ClientLogin?service=reader&Email=%s&Passwd=%s' % (email,passwd))
data = response.read()
credentials = {}
for line in data.split('\n'):
fields = line.split('=')
if len(fields)==2:
credentials[fields[0]]=fields[1]
assert credentials.has_key('Auth'),'no Auth in response'
# step 2: get a token
req = urllib2.Request('http://www.google.com/reader/api/0/token')
req.add_header('Authorization', 'GoogleLogin auth=%s' % credentials['Auth'])
response = urllib2.urlopen(req)
# step 3: now POST the details of note
# TBD...
Answer: Using Firebug you can see what gets submitted if you add a Google Reader note
from a browser.
The url it posts to is : <http://www.google.co.uk/reader/api/0/item/edit>.
It seems that the only required parameters are 'T' (for the token retrieve at
step 2) and 'snippet' which is the note being posted.
Based on that I did the following which works for me (note import urllib as
well encode the post body):
# step 3: now POST the details of note
import urllib
token = response.read()
add_note_url = "http://www.google.co.uk/reader/api/0/item/edit"
data = {'snippet' : 'This is the note', 'T' : token}
encoded_data = urllib.urlencode(data)
req = urllib2.Request(add_note_url, encoded_data)
req.add_header('Authorization', 'GoogleLogin auth=%s' % credentials['Auth'])
response = urllib2.urlopen(req)
# this part is optional
if response.code == 200:
print 'Gadzooks!'
else:
print 'Curses and damnation'
There are a couple of other params that you can set e.g. ck, linkify, share
etc, but they are all documented on the site.
I leave reading the note from a command line argument to the script as an
exercise for the reader.
|
How can I see the details of an exception in Python's debugger?
Question: Sometimes while I'm debugging an exception will be raised.
For example, consider this code:
def some_function(): # Pretend this function is in a library...
# ...and deep within the library is an exception:
raise Exception('An exception message with valuable information.')
import pdb; pdb.set_trace()
try:
some_function() # Pretend I am debugging from this point using pdb.
except:
pass
While debugging from the `some_function()` call, if I issue a `next` command I
will see the following details about the exception that was raised [and
caught]:
Exception: Exceptio...ation.',)
Here's a straight copy / paste from the terminal I was working in:
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb) next
Exception: Exceptio...ation.',)
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb)
It would be useful to see the entire exception message. How can I do this in
pdb?
Answer: `pdb` stores the exception type and value in `__exception__`. You can print
the exception part of a traceback in `pdb` with:
import traceback; print "".join(traceback.format_exception_only(*__exception__))
For example:
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb) next
Exception: Exceptio...ation.',)
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb) import traceback; print "".join(traceback.format_exception_only(*__exception__))
Exception: An exception message with valuable information.
(Pdb)
Unfortunately this does not include the rest of the traceback, but all that
information is available through the `where` command of `pdb` anyway. If you
really want the full traceback, you can add the following to your `~/.pdbrc`
file or paste it into your terminal:
!global __currentframe, __stack; from inspect import currentframe as __currentframe, stack as __stack
!global __format_exception_only, __print_stack; from traceback import format_exception_only as __format_exception_only, print_stack as __print_stack
!global __Pdb; from pdb import Pdb as __Pdb
# find the last frame on the stack with an object named "pdb" or "self" that is a pdb.Pdb object
# works for pdb called the usual way, or pdb.pm(), or pdb.set_trace()
!global __pdb; __pdb = [__framerec[0].f_locals.get("pdb") or __framerec[0].f_locals.get("self") for __framerec in __stack() if (__framerec[0].f_locals.get("pdb") or __framerec[0].f_locals.get("self")).__class__ == __Pdb][-1]
alias traceback __print_stack(__pdb.stack[-1][0]); print "".join(__format_exception_only(*__exception__))
Then you can just use the new `traceback` alias to get what you want:
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb) next
Exception: Exceptio...ation.',)
> /tmp/test.py(7)<module>()
-> some_function() # Pretend I am debugging from this point using pdb.
(Pdb) traceback
File "test.py", line 7, in <module>
some_function() # Pretend I am debugging from this point using pdb.
File "test.py", line 3, in some_function
raise Exception('An exception message with valuable information.')
Exception: An exception message with valuable information.
(Pdb)
Warning: all of this relies on undocumented `pdb` and `bdb` internals and is
likely to break.
|
How to spread django unit tests over multiple files?
Question: * I have a python-django application
* I'm using the [unit testing framework](https://docs.djangoproject.com/en/1.3/topics/testing/)
* The tests are arranged in the file "tests.py" in the module directory
* I'm running the tests via `./manage.py test app`
Now..
* The `tests.py` file is getting rather large/complex/messy
* I'd like to break `tests.py` up into smaller collections of tests...
How?
Answer: You can create `tests` folder with `___init___.py` inside (so that it becomes
a package). Then you add your split test .py files there and import all of
them in `___init___.py`.
I.e: Substitute the `test.py` file with a module that looks and acts like the
file:
Create a `tests` Directory under the app in question
app
app\models.py
app\views.py
app\tests
app\tests\__init__.py
app\tests\bananas.py
app\tests\apples.py
Import the submodules into `app\tests\__init__.py`:
from bananas import *
from apples import *
Now you can use ./manage.py as if they were all in a single file:
./manage.py test app.some_test_in_bananas
Note that this approach is no longer valid from Django 1.6, see this
[post](http://stackoverflow.com/a/20932450/117194).
|
md5 a string multiple times get different result on different platform
Question: t.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
static char* unsigned_to_signed_char(const unsigned char* in , int len) {
char* res = (char*)malloc(len * 2 + 1);
int i = 0;
memset(res , 0 , len * 2 + 1);
while(i < len) {
sprintf(res + i * 2 , "%02x" , in[i]);
i ++;
};
return res;
}
static unsigned char * md5(const unsigned char * in) {
MD5_CTX ctx;
unsigned char * result1 = (unsigned char *)malloc(MD5_DIGEST_LENGTH);
MD5_Init(&ctx);
printf("len: %lu \n", strlen(in));
MD5_Update(&ctx, in, strlen(in));
MD5_Final(result1, &ctx);
return result1;
}
int main(int argc, char *argv[])
{
const char * i = "abcdef";
unsigned char * data = (unsigned char *)malloc(strlen(i) + 1);
strncpy(data, i, strlen(i));
unsigned char * result1 = md5(data);
free(data);
printf("%s\n", unsigned_to_signed_char(result1, MD5_DIGEST_LENGTH));
unsigned char * result2 = md5(result1);
free(result1);
printf("%s\n", unsigned_to_signed_char(result2, MD5_DIGEST_LENGTH));
unsigned char * result3 = md5(result2);
free(result2);
printf("%s\n", unsigned_to_signed_char(result3, MD5_DIGEST_LENGTH));
return 0;
}
makeflle
all:
cc t.c -Wall -L/usr/local/lib -lcrypto
and t.py
#!/usr/bin/env python
import hashlib
import binascii
src = 'abcdef'
a = hashlib.md5(src).digest()
b = hashlib.md5(a).digest()
c = hashlib.md5(b).hexdigest().upper()
print binascii.b2a_hex(a)
print binascii.b2a_hex(b)
print c
The results of python script on Debian6 x86 and MacOS 10.6 are the same:
e80b5017098950fc58aad83c8c14978e
b91282813df47352f7fe2c0c1fe9e5bd
85E4FBD1BD400329009162A8023E1E4B
the c version on MacOS is:
len: 6
e80b5017098950fc58aad83c8c14978e
len: 48
eac9eaa9a4e5673c5d3773d7a3108c18
len: 64
73f83fa79e53e9415446c66802a0383f
**Why it is different from Debian6 ?**
Debian environment:
gcc (Debian 4.4.5-8) 4.4.5
Python 2.6.6
Linux shuge-lab 2.6.26-2-686 #1 SMP Thu Nov 25 01:53:57 UTC 2010 i686 GNU/Linux
OpenSSL was installed from testing repository.
MacOS environment:
i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3)
Python 2.7.1
Darwin Lees-Box.local 10.7.0 Darwin Kernel Version 10.7.0: Sat Jan 29 15:17:16 PST 2011; root:xnu-1504.9.37~1/RELEASE_I386 i386
OpenSSL was installed from MacPort.
openssl @1.0.0d (devel, security)
OpenSSL SSL/TLS cryptography library
Answer: I think you are allocating bytes exactly for MD5 result, without ending `\0`.
Then you are calculating MD5 of block of memory that starts with result from
previous MD5 calculating but with some random bytes after it. You should
allocate one byte more for result and set it to `\0`.
My proposal:
...
unsigned char * result1 = (unsigned char *)malloc(MD5_DIGEST_LENGTH + 1);
result1[MD5_DIGEST_LENGTH] = 0;
...
|
Run custom admin command from view
Question: I have a custom admin command that emails out reports. It normally runs from a
cron job. What I would like to do is add a button to my web app that when
clicked will cause the the admin command to run there and then rather than
wait for the cron job to call it. How do I do this? Do I have to call out to a
command line such as
python manage.py myadmincmd
or can I invoke the code from within a view? It seems it would be cleaner if I
could do this from within a view without needing to break out to the command
line.
Answer: You can use `call_command`:
from django.core.management import call_command
call_command('myadmincmd')
|
python & suds "ImportError: cannot import name getLogger"
Question: I'm using Ubuntu 11.04 (natty). I have been using Suds to consume a SOAP web
service. Everything was working fine... until it wasn't. I can no longer
import Suds. I've uninstalled and re-installed Suds from the Ubuntu
repositories but still get the same import error (see IDLE traceback below).
I'm using Python 2.7.1 and Suds 0.4.1-2. Does anyone have any ideas on how to
solve this problem??
>>> import suds
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
import suds
File "/usr/lib/pymodules/python2.7/suds/__init__.py", line 154, in <module>
import client
File "/usr/lib/pymodules/python2.7/suds/client.py", line 23, in <module>
import suds.metrics as metrics
File "/usr/lib/pymodules/python2.7/suds/metrics.py", line 23, in <module>
from logging import getLogger
ImportError: cannot import name getLogger
>>>
Answer: `logging` is a standard module of Python. There are several possible reasons
why Python can't find it anymore:
1. The is another `logging` module in the path (print `sys.path` to get a list of paths Python will search)
2. Someone changed `PYTHONPATH` (the default Python search path)
3. Someone messed with the Python installation (deleted the `logging` module)
|
Python: thinking of a module and its variables as a singleton — Clean approach?
Question: I'd like to implement some sort of singleton pattern in my Python program. I
was thinking of doing it without using classes; that is, I'd like to put all
the singleton-related functions and variables within a module and consider it
an actual singleton.
For example, say this is to be in the file 'singleton_module.py':
# singleton_module.py
# Singleton-related variables
foo = 'blah'
bar = 'stuff'
# Functions that process the above variables
def work(some_parameter):
global foo, bar
if some_parameter:
bar = ...
else:
foo = ...
Then, the rest of the program (i.e., other modules) would use this singleton
like so:
# another_module.py
import singleton_module
# process the singleton variables,
# which changes them across the entire program
singleton_module.work(...)
# freely access the singleton variables
# (at least for reading)
print singleton_module.foo
This seemed to be a pretty good idea to me, because it _looks_ pretty clean in
the modules that use the singleton.
However, all these tedious 'global' statements in the singleton module are
ugly. They occur in every function that processes the singleton-related
variables. That's not much in this particular example, but when you have 10+
variables to manage across several functions, it's not pretty.
Also, this is pretty error-prone if you happen to forget the global
statements: variables local to the function will be created, and the module's
variables won't be changed, which is not what you want!
So, would this be considered to be clean? Is there an approach similar to mine
that manages to do away with the 'global' mess?
Or is this simply not the way to go?
Answer: A common alternative to using a module as a singleton is Alex Martelli's [Borg
pattern](http://code.activestate.com/recipes/66531-singleton-we-dont-need-no-
stinkin-singleton-the-bo/):
class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
# and whatever else you want in your class -- that's all!
There can be multiple instances of this class, but they all share the same
state.
|
Python WebKitWebView: how to get (generated) source code
Question: Is it possible to get the generated source code (so including JavaScript added
DOM nodes) with Python and WebKit, and if so, how?
import webkit
web_view = webkit.WebView()
web_view.open('http://google.com')
But then?
Answer: Bind a function to the `loadFinished(bool)` signal, in that function you can
use `mainFrame().toHtml()` to get the source code.
|
Will this eventually lead to a crash (wxpython)
Question: I have over 300 questions/prompts that I plan to include in the program. The
flow is pretty much like this:
**Create a window with the question. Store answer in variable. Create NEW
window with question. Store NEW answer.**
_this continues on for over 300 questions._
* * *
I have 2 concerns:
* * *
1) Will this eventually lead to a crash since I'm creating so many windows
2) Everything works with this code if you select 'Yes' to the second question
(A2) but it does not work if you select 'No'. Can you please see if you can
find what's wrong with it?
* * *
import wx
a1 = ['Apples', 'Bananas', 'Strawberries', 'Watermelon',
"Don't remember", 'None of the above']
a2 = ['No', 'Yes']
a4 = ['No', 'Yes']
class Fruit(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Fruit', size=(300,200))
#create panel and button
panel = wx.Panel(self)
# B1 - create multiple choice list
box = wx.MultiChoiceDialog(None, """
A1. What kind of fruit did you buy at the store?""", 'Fruit', a1)
if box.ShowModal() == wx.ID_OK:
a_1 = box.GetSelections()
print (a_1, '\n')
# A2 - create single choice list
box = wx.SingleChoiceDialog(None, """
A2. Do you like eating fruit?
""", 'Fruit', a2)
if box.ShowModal() == wx.ID_OK:
a_2 = box.GetStringSelection()
print (a_2, '\n')
if a_2 == 'Yes':
box = wx.TextEntryDialog(None, "A3. What kind of fruit is your favorite? ", "Fruit", "")
if box.ShowModal() == wx.ID_OK:
a_3 = box.GetValue()
print (a_3, '\n')
box = wx.SingleChoiceDialog(None, """
A4. Did you eat the fruit that you bought?
""", 'Fruit', a4)
if box.ShowModal() == wx.ID_OK:
a_4 = box.GetStringSelection()
print (a_4, '\n')
Thanks
Answer: Holy Cow. You're not really chaining the dialogs like that are you? To try to
answer your questions:
1. Will this eventually lead to a crash: This snippet of code should fail at the first `print` following someone clicking No. See bullet point #2. There's a lot missing here, I don't see any error handling, no `__main__`, missing an `App()` etc. Because you're repeatedly reassigning the value of `box` I don't think you're likely to encounter memory issues, but those are the least of your concerns at this stage.
2. Everything works if you click Yes, but fails if you click No: That's coming from this `box.ShowModal() == wx.ID_OK`. You're only creating the variables `a_#` if you get the OK value from your Dialog. You could do this instead:
`a_1 = box.getSelections() if box.ShowModal() == wx.ID_OK else None`
Here you'd substitute in some meaningful value for `None`.. Note that this
uses the Python Ternary Syntax, which was introduced in 2.5 or 2.6. It would
not work with 2.4.
All that said, what you probably want to create is a Wizard. They are
"typically used to decompose a complex dialog into several simple steps".
There's a tutorial available here at
[wxWidgets](http://wiki.wxpython.org/wxWizard "wxWizard Tutorial") that might
shed some light. Once you've looked at that a little bit you should
investigate sizers, as it appears you're using multiline strings to create
white spaces(?).
|
Turbomail Integration with Pyramid
Question: I am in need of a method to send an email from a Pyramid application. I know
of
[pyramid_mailer](http://docs.pylonsproject.org/projects/pyramid_mailer/en/latest/),
but it seems to have a fairly limited message class. I don't understand if
it's possible to write the messages from pyramid_mailer using templates to
generate the body of the email. Further, I haven't seen anything regarding
whether rich-text is supported, or if it's just simple plain-text.
Previously, I was using [Turbomail](http://pypi.python.org/pypi/TurboMail)
with the Pylons framework. Unfortunately there doesn't appear to be any
adapters available for TurboMail for Pyramid. I know that TurboMail can be
extended for additional frameworks, but have no idea where I would even start
such a task. Has anyone written an adapter for Pyramid or can point me in the
right direction of what would be required to do so?
Answer: I can't answer your Turbomail questions other than to say that I've heard it
works fine with Pyramid.
Regarding pyramid_mailer, it's entirely possible to render your emails using
the same subsystem that lets pyramid render all of your templates.
from pyramid.renderers import render
opts = {} # a dictionary of globals to send to your template
body = render('email.mako', opts, request)
Also, the pyramid_mailer Message object is based on the lamson MailResponse
object, which is stable and well-tested.
You can create a mail that consists of both a plain text body as well as html,
by specifying either the `body` or `html` constructor parameters to the
Message class.
plain_body = render('plain_email.mako', opts, request)
html_body = render('html_email.mako', opts, request)
msg = Message(body=plain_body, html=html_body)
|
Is it bad style to reassign long variables as a local abbreviation?
Question: I prefer to use long identifiers to keep my code semantically clear, but in
the case of repeated references to the same identifier, I'd like for it to
"get out of the way" in the current scope. Take this example in Python:
def define_many_mappings_1(self):
self.define_bidirectional_parameter_mapping("status", "current_status")
self.define_bidirectional_parameter_mapping("id", "unique_id")
self.define_bidirectional_parameter_mapping("location", "coordinates")
#etc...
Let's assume that I really want to stick with this long method name, and that
these arguments are always going to be hard-coded. Implementation 1 feels
wrong because most of each line is taken up with a repetition of characters.
The lines are also rather long in general, and will exceed 80 characters
easily when nested inside of a class definition and/or a try/except block,
resulting in ugly line wrapping. Let's try using a for loop:
def define_many_mappings_2(self):
mappings = [("status", "current_status"),
("id", "unique_id"),
("location", "coordinates")]
for mapping in mappings:
self.define_parameter_mapping(*mapping)
I'm going to lump together all similar iterative techniques under the umbrella
of Implementation 2, which has the improvement of separating the "unique"
arguments from the "repeated" method name. However, I dislike that this has
the effect of placing the arguments before the method they're being passed
into, which is confusing. I would prefer to retain the "verb followed by
direct object" syntax.
I've found myself using the following as a compromise:
def define_many_mappings_3(self):
d = self.define_bidirectional_parameter_mapping
d("status", "current_status")
d("id", "unique_id")
d("location", "coordinates")
In Implementation 3, the long method is aliased by an extremely short
"abbreviation" variable. I like this approach because it is immediately
recognizable as a set of repeated method calls on first glance while having
less redundant characters and much shorter lines. The drawback is the usage of
an extremely short and semantically unclear identifier "d".
What is the most readable solution? Is the usage of an "abbreviation variable"
acceptable if it is explicitly assigned from an unabbreviated version in the
local scope?
Answer: itertools to the rescue again! Try using starmap - here's a simple demo:
list(itertools.starmap(min,[(1,2),(2,2),(3,2)]))
prints
[1,2,2]
starmap is a generator, so to actually invoke the methods, you have to consume
the generator with a list.
import itertools
def define_many_mappings_4(self):
list(itertools.starmap(
self.define_parameter_mapping,
[
("status", "current_status"),
("id", "unique_id"),
("location", "coordinates"),
] ))
Normally I'm not a fan of using a dummy list construction to invoke a sequence
of functions, but this arrangement seems to address most of your concerns.
If `define_parameter_mapping` returns None, then you can replace `list` with
`any`, and then all of the function calls will get made, and you won't have to
construct that dummy list.
|
python bitarray to and from file
Question: I'm writing a large bitarray to a file using this code:
import bitarray
bits = bitarray.bitarray(bin='0000011111') #just an example
with open('somefile.bin', 'wb') as fh:
bits.tofile(fh)
However, when i attempt to read this data back using:
import bitarray
a = bitarray.bitarray()
with open('somefile.bin', 'rb') as fh:
bits = a.fromfile(fh)
print bits
it fails with 'bits' being a NoneType. What am i doing wrong?
Answer: I think "a" is what you want. a.fromfile(fh) is a method which fills a with
the contents of fh: it doesn't return a bitarray.
>>> import bitarray
>>> bits = bitarray.bitarray('0000011111')
>>>
>>> print bits
bitarray('0000011111')
>>>
>>> with open('somefile.bin', 'wb') as fh:
... bits.tofile(fh)
...
>>> a = bitarray.bitarray()
>>> with open('somefile.bin', 'rb') as fh:
... a.fromfile(fh)
...
>>> print a
bitarray('0000011111000000')
|
How do I use timesince
Question: I found this snippet:
def timesince(dt, default="just now"):
now = datetime.utcnow()
diff = now - dt
periods = (
(diff.days / 365, "year", "years"),
(diff.days / 30, "month", "months"),
(diff.days / 7, "week", "weeks"),
(diff.days, "day", "days"),
(diff.seconds / 3600, "hour", "hours"),
(diff.seconds / 60, "minute", "minutes"),
(diff.seconds, "second", "seconds"),
)
for period, singular, plural in periods:
if period:
return "%d %s ago" % (period, singular if period == 1 else plural)
return default
and want to use it in an output when doing a query to my database in Google
Appegine. My database looks like so:
class Service(db.Model):
name = db.StringProperty(multiline=False)
urla = db.StringProperty(multiline=False)
urlb = db.StringProperty(multiline=False)
urlc = db.StringProperty(multiline=False)
timestampcreated = db.DateTimeProperty(auto_now_add=True)
timestamplastupdate = db.DateTimeProperty(auto_now=True)
In the mainpage of the webapp requesthandler I want to do:
elif self.request.get('type') == 'list':
q = db.GqlQuery('SELECT * FROM Service')
count = q.count()
if count == 0:
self.response.out.write('Success: No services registered, your database is empty.')
else:
results = q.fetch(1000)
for result in results:
resultcreated = timesince(result.timestampcreated)
resultupdated = timesince(result.timestamplastupdate)
self.response.out.write(result.name + '\nCreated:' + resultcreated + '\nLast Updated:' + resultupdated + '\n\n')
What am I doing wrong? I'm having troubles with formatting my code using the
snippet.
Which one of these should I do?
this?
def timesince:
class Service
class Mainpage
def get(self):
or this?
class Service
class Mainpage
def timesince:
def get(self):
I'm not too familiar with Python and would appreciate any input on how to fix
this. Thanks!
Answer: I'm not totally clear what the problem you're having is, so bear with me. A
Traceback would be helpful. :)
timesince() doesn't require any member variables, so I don't think it should
be inside one of the classes. If I were in your situation, I would probably
put timesince in its own file and then import that module in the file where
Mainpage is defined.
If you're putting them all in the same file, make sure that your spacing is
consistent and you don't have any tabs.
|
Write unicode content and unicode file name in Windows
Question:
#source file is encoded in utf8
import urllib2
import re
req = urllib2.urlopen('http://people.w3.org/rishida/scripts/samples/hungarian.html')
c = req.read()#.decode('utf-8')
p = r'title="This is Latin script \(Hungarian language\)">(.+)'
text = re.search(p, c).group(1)
name = text[:10]+'.txt' #file name will have special chars in it
f = open(name, 'wb')
f.write(text) #content of file will have special chars in it
f.close()
x = raw_input('done')
As you can see the script does a couple things: \- Reads content that is known
to have unicode characters from a webpage into a variable
(The source file is saved in utf-8 but this should not make a difference
unless unicode strings are actually being defined in the source code... As you
can see the unicode string is being defined dynamially into a variable.. what
encoding the source is shouldn't matter in this scenario)
* Writes a file with a name containing unicode characters
* Write unicode content into this file as well
Here's the weird behavior I get (Windows 7, Python 2.7) : When I don't use the
decode function:
c = req.read()
The NAME of the file will come out gibberish, but the CONTENT of the file will
come out readable (that is you can see the correct unicode hungarian
characters)
Yet, when I USE the decode function:
c = req.read().decode('utf-8')
It will NOT ERROR on opening the file (really creating it with 'w' mode) and
the resulting file's NAME will be readable, yep now it shows the correct
unicode characters.
So far so good right? Well, then it WILL ERROR on trying to write the unicode
content to the file:
f.write(text) #content of file will have special chars in it
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 8: ordinal not in range(128)
You see, I can't seem to have the cake and eat it too... Either I can
correctly write the NAME of the file or I can correctly write the CONTENT of
the file..
**How can I do both?**
I've also tried writing the file with
f = codecs.open(name, encoding='utf-8', mode='wb')
But it also errors..
Answer: While winterTTR's answer does work.. I've realized that this approach is
convoluted. Rather, all you really need to do is encode the data you write to
the file. The name you don't need to encode and both the name and the content
will come out "readable".
content = '\xunicode chars'.decode('utf-8')
f = open(content[:5]+'.txt', 'wb')
f.write(content.encode('utf-8'))
f.close()
|
Optimization of SPARQL query. [ Estimated execution time exceeds the limit of 1500 (sec) ]
Question: I am trying to run this query on <http://dbpedia.org/sparql> but I get an
error that my query is too expensive. When I run the query trough
<http://dbpedia.org/snorql/> I get:
The estimated execution time 25012730 (sec) exceeds the limit of 1500 (sec) ...
When running the query through my python script using SPARQLWrapper I simply
get an HTTP 500.
I figure I need to do something to optimize my SPARQL query. I need the data
for iterating over educational institutions and importing it in to a local
database, maybe I am using SPARQL wrong and should do this in a fundamentally
different way.
Hope someone can help me!
# The query
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX : <http://dbpedia.org/resource/>
PREFIX dbpedia2: <http://dbpedia.org/property/>
PREFIX dbpedia: <http://dbpedia.org/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT DISTINCT ?uri
?name
?homepage
?student_count
?native_name
?city
?country
?type
?lat ?long
?image
WHERE {
?uri rdf:type dbpedia-owl:EducationalInstitution .
?uri foaf:name ?name .
OPTIONAL { ?uri foaf:homepage ?homepage } .
OPTIONAL { ?uri dbpedia-owl:numberOfStudents ?student_count } .
OPTIONAL { ?uri dbpprop:nativeName ?native_name } .
OPTIONAL { ?uri dbpprop:city ?city } .
OPTIONAL { ?uri dbpprop:country ?country } .
OPTIONAL { ?uri dbpprop:type ?type } .
OPTIONAL { ?uri geo:lat ?lat . ?uri geo:long ?long } .
OPTIONAL { ?uri foaf:depiction ?image } .
}
ORDER BY ?uri
LIMIT 20 OFFSET 10
Answer: Forget it. You won't be able to get that query back from dbpedia with just one
SPARQL. Those optionals are very expensive.
To work it around you need to first run something like:
SELECT DISTINCT ?uri WHERE {
?uri rdf:type dbpedia-owl:EducationalInstitution .
?uri foaf:name ?name .
} ORDER BY ?uri
LIMIT 20 OFFSET 10
Then iterate over the resultset of this query to form single queries for each
`dbpedia-owl:EducationalInstitution` such as ... (notice the filter at the end
of the query):
SELECT DISTINCT ?uri
?name
?homepage
?student_count
?native_name
?city
?country
?type
?lat ?long
?image
WHERE {
?uri rdf:type dbpedia-owl:EducationalInstitution .
?uri foaf:name ?name .
OPTIONAL { ?uri foaf:homepage ?homepage } .
OPTIONAL { ?uri dbpedia-owl:numberOfStudents ?student_count } .
OPTIONAL { ?uri dbpprop:nativeName ?native_name } .
OPTIONAL { ?uri dbpprop:city ?city } .
OPTIONAL { ?uri dbpprop:country ?country } .
OPTIONAL { ?uri dbpprop:type ?type } .
OPTIONAL { ?uri geo:lat ?lat . ?uri geo:long ?long } .
OPTIONAL { ?uri foaf:depiction ?image } .
FILTER (?uri = <http://dbpedia.org/resource/%C3%89cole_%C3%A9l%C3%A9mentaire_Marie-Curie>)
}
Where `<http://dbpedia.org/resource/%C3%89cole_%C3%A9l%C3%A9mentaire_Marie-
Curie>` has been obtained from the first query.
... and yes it will be slow and you might not be able to run this for an
online application. Advice: try to work out some sort of caching mechanism to
sit between your app and the dbpedia SPARQL endpoint.
|
Opening the Excel application from Python
Question: I am using 'xlwt' to write into Excel files as part of my project in Python. I
also need to actually open the Excel spreadsheet for display and also close
it. I found a function:
import webbrowser
webbrowser.open('C:/Users/300231823/Desktop/GUI/simplenew4.xls')
This seems to open the .xls file. How do I close the file?
I am completely new to programming, and I started using Python 3 weeks ago.
Answer:
from win32com.client import Dispatch
xl = Dispatch("Excel.Application")
xl.Visible = True # otherwise excel is hidden
# newest excel does not accept forward slash in path
wb = xl.Workbooks.Open(r'C:\Users\300231823\Desktop\GUI\simplenew4.xls')
wb.Close()
xl.Quit()
The win32com module is part of
[pywin32](http://sourceforge.net/projects/pywin32/).
|
best method and data structure for sorting a list of tuples into multiple lists?
Question: Let's say I have a list of tuples like this:
l = [('music','300','url'),('movie','400','url'),
('clothing','250','url'),('music','350','url'),
('music','400','url'),('movie','1000','url')]
and that I want to sort these tuples into multiple lists, each grouped by the
first element in the tuples. Further, once grouped into those lists, I want
the new lists reverse sorted by the second element (the int). So, the result
would be:
music = [('music','400','url'),('music','350','url'),('music','300','url')]
movie = [('movie','1000','url'),('movie','400','url')]
clothing = [('clothing','250','url')]
Perhaps I could forego the multiple lists and make a list of lists of tuples?
So, I would get:
sortedlist = [[('music','400','url'),('music','350','url'),('music','300','url')],
[('movie','1000','url'),('movie','400','url')],
[('clothing','250','url')]]
But even in this case, how would I get the internal lists reverse sorted by
the second element?
If I'm going about this the wrong way, please mention it. I'm still new at
Python. Thx!
Answer: You can do something like this:
import itertools
import operator
sorted_l = sorted(l, key=lambda x: (x[0], int(x[1])), reverse=True)
print [list(g[1]) for g in itertools.groupby(sorted_l, key=operator.itemgetter(0))]
Output :
[[('music', '400', 'url'), ('music', '350', 'url'), ('music', '300', 'url')],
[('movie', '1000', 'url'), ('movie', '400', 'url')],
[('clothing', '250', 'url')]]
|
problems with python-mailer and google?
Question: I've just tried the following:
server = smtplib.SMTP(smtpname, smtpport)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
server.sendmail(username, recipient, "TEST")
server.close()
smtpname is "smtp.gmail.com", smtpport is 587, username is a google acc +
"@gmail.com", recipient is a 2nd gmail.
could anyone tell me whats wrong? the scripts runs in python, no errors, but i
get nothing
Answer: Take a look at the [email example](http://docs.python.org/library/email-
examples.html)
Your use of "TEST" string should be a properly formatted MIME message.
In your case, it should be be: from email.mime.text import MIMEText
import smtplib
# Create a MIME text message and populate its values
msg = MIMEText("TEST")
msg['Subject'] = "TEST"
msg['From'] = username
msg['To'] = recipient
server = smtplib.SMTP(smtpname, smtpport)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
# Send a properly formatted MIME message, rather than a raw string
server.sendmail(username, recipient, msg.as_string())
server.close()
|
date2num , ValueError: ordinal must be >= 1
Question: I'm using the matplotlib candlestick module which requires the time to be
passed as a float day format . I`m using date2num to convert it, before :
This is my code :
import csv
import sys
import math
import numpy as np
import datetime
from optparse import OptionParser
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.mlab as mlab
import matplotlib.dates as mdates
from matplotlib.finance import candlestick
from matplotlib.dates import date2num
datafile = 'historical_data/AUD_Q10_1D_500.csv'
print 'loading', datafile
r = mlab.csv2rec(datafile, delimiter=';')
quotes = [date2num(r['date']),r['open'],r['close'],r['max'],r['min']]
candlestick(ax, quotes, width=0.6)
plt.show()
_( here is the csv file :<http://db.tt/MIOqFA0> )_
This is what the doc says :
> candlestick(ax, quotes, width=0.20000000000000001, colorup='k',
> colordown='r', alpha=1.0) quotes is a list of (time, open, close, high, low,
> ...) tuples. As long as the first 5 elements of the tuples are these values,
> the tuple can be as long as you want (eg it may store volume). time must be
> in float days format - see date2num
Here is the full error log :
Traceback (most recent call last):
File
"/usr/lib/python2.6/site-packages/matplotlib/backends/backend_qt4agg.py",
line 83, in paintEvent
FigureCanvasAgg.draw(self) File
"/usr/lib/python2.6/site-packages/matplotlib/backends/backend_agg.py",
line 394, in draw
self.figure.draw(self.renderer) File
"/usr/lib/python2.6/site-packages/matplotlib/artist.py",
line 55, in draw_wrapper draw(artist,
renderer, *args, **kwargs) File
"/usr/lib/python2.6/site-packages/matplotlib/figure.py",
line 798, in draw func(*args) File
"/usr/lib/python2.6/site-packages/matplotlib/artist.py",
line 55, in draw_wrapper draw(artist,
renderer, *args, **kwargs) File
"/usr/lib/python2.6/site-packages/matplotlib/axes.py", line 1946, in draw a.draw(renderer)
File
"/usr/lib/python2.6/site-packages/matplotlib/artist.py",
line 55, in draw_wrapper draw(artist,
renderer, *args, **kwargs) File
"/usr/lib/python2.6/site-packages/matplotlib/axis.py", line 971, in draw tick_tups = [ t for
t in self.iter_ticks()] File
"/usr/lib/python2.6/site-packages/matplotlib/axis.py", line 904, in iter_ticks majorLocs =
self.major.locator() File
"/usr/lib/python2.6/site-packages/matplotlib/dates.py",
line 743, in __call__ self.refresh()
File
"/usr/lib/python2.6/site-packages/matplotlib/dates.py",
line 752, in refresh dmin, dmax =
self.viewlim_to_dt() File
"/usr/lib/python2.6/site-packages/matplotlib/dates.py",
line 524, in viewlim_to_dt return
num2date(vmin, self.tz),
num2date(vmax, self.tz) File
"/usr/lib/python2.6/site-packages/matplotlib/dates.py",
line 289, in num2date if not
cbook.iterable(x): return
_from_ordinalf(x, tz) File "/usr/lib/python2.6/site-packages/matplotlib/dates.py",
line 203, in _from_ordinalf dt =
datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1
If I run a quick :
for x in r['date']:
print str(x) + "is :" + str(date2num(x))
it outputs something like :
2010-06-12is :733935.0
2010-07-12is :733965.0
2010-08-12is :733996.0
which sound ok to me :)
Answer: Read the docstring a bit more carefully :)
> quotes is a list of (time, open, close, high, low, ...) tuples.
What's happening is that it expects _each item_ of `quotes` to be a sequence
of (time, open, close, high, low).
You're passing in 5 long arrays, it expects a long sequence of 5 items.
You just need to `zip` your input.
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from matplotlib.finance import candlestick
from matplotlib.dates import date2num
datafile = 'Downloads/AUD_Q10_1D_500.csv'
r = mlab.csv2rec(datafile, delimiter=';')
quotes = zip(date2num(r['date']),r['open'],r['close'],r['max'],r['min'])
fig, ax = plt.subplots()
candlestick(ax, quotes, width=0.6)
plt.show()
![enter image description here](http://i.stack.imgur.com/1e5Ad.png)
|
Get specifics elements of a xml output in python
Question: I'm getting some problems to get this part of the code, that I get from
[yourself](http://stackoverflow.com/questions/1140672/parsing-
xml/1140753#1140753). Here is my code:
import cStringIO
import pycurl
from xml.etree import ElementTree
_API_KEY = 'my api key'
_ima = '/the/path/to/a/image'
sock = cStringIO.StringIO()
upl = pycurl.Curl()
values = [
("key", _API_KEY),
("image", (upl.FORM_FILE, _ima))]
upl.setopt(upl.URL, "http://api.imgur.com/2/upload.xml")
upl.setopt(upl.HTTPPOST, values)
upl.setopt(upl.WRITEFUNCTION, sock.write)
upl.perform()
upl.close()
xmldata = sock.getvalue()
#print xmldata
sock.close()
tree = ElementTree.fromstring(xmldata)
url = tree.findtext('original')
webpage = tree.findtext('imgur_page')
delpage = tree.findtext('delete_page')
print 'Url: ' + str(url)
print 'Pagina: ' + str(webpage)
print 'Link de borrado: ' + str(delpage)
If I uncomment the test print, I get a output similar to this:
<?xml version="1.0" encoding="utf-8"?>
<upload><image><name></name><title></title><caption></caption><hash>dxPGi</hash><deletehash>kj2XOt4DC13juUW</deletehash><datetime>2011-06-10 02:59:26</datetime><type>image/png</type><animated>false</animated><width>1024</width><height>768</height><size>172863</size><views>0</views><bandwidth>0</bandwidth></image><links><original>http://i.stack.imgur.com/dxPGi.png</original><imgur_page>http://imgur.com/dxPGi</imgur_page><delete_page>http://imgur.com/delete/kj2XOt4DC13juUW</delete_page><small_square>http://i.stack.imgur.com/dxPGis.jpg</small_square><large_thumbnail>http://i.stack.imgur.com/dxPGil.jpg</large_thumbnail></links></upload>
I want the receive some specific value, but it throw me this error:
Traceback (most recent call last):
File "<pyshell#28>", line 27, in <module>
url = tree.find('original').text
AttributeError: 'NoneType' object has no attribute 'text'
I searched in the python module help about ElementTree, and it don't have this
attribute, so how can I get only the text, not the object.
Update:
I found some info about getting a text string
[here](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findtext)
but still no results. Now I get:
Traceback (most recent call last): File "<pyshell#32>", line 34, in <module>
print 'Url: ' + url TypeError: cannot concatenate 'str' and 'NoneType' objects
Update 2:
I added the str() to the print and now I get a nice string. The bad part is,
that now I get None as response. So question still apply. How I get the url,
webpage and delete_page of this xml?
Answer: Your `find()` call is trying to find an immediate child of the top of the tree
with a tag named `original`, not a tag at any lower level than that. Use:
url = tree.find('.//original').text
if you want to find all elements in the tree with the tag named `original`.
The pattern matching rules for ElementTree's `find()` method are laid out in a
table on this page: <http://effbot.org/zone/element-xpath.htm>
For `//` matching it says:
> Selects all subelements, on all levels beneath the current element (search
> the entire subtree). For example, “.//egg” selects all “egg” elements in the
> entire tree.
Edit: here is some test code for you, it use the XML sample string you posted
I just ran it through XML Tidy in TextMate to make it legible:
from xml.etree import ElementTree
xmldata = '''<?xml version="1.0" encoding="utf-8"?>
<upload>
<image>
<name/>
<title/>
<caption/>
<hash>dxPGi</hash>
<deletehash>kj2XOt4DC13juUW</deletehash>
<datetime>2011-06-10 02:59:26</datetime>
<type>image/png</type>
<animated>false</animated>
<width>1024</width>
<height>768</height>
<size>172863</size>
<views>0</views>
<bandwidth>0</bandwidth>
</image>
<links>
<original>http://i.stack.imgur.com/dxPGi.png</original>
<imgur_page>http://imgur.com/dxPGi</imgur_page>
<delete_page>http://imgur.com/delete/kj2XOt4DC13juUW</delete_page>
<small_square>http://i.stack.imgur.com/dxPGis.jpg</small_square>
<large_thumbnail>http://i.stack.imgur.com/dxPGil.jpg</large_thumbnail>
</links>
</upload>'''
tree = ElementTree.fromstring(xmldata)
print tree.find('.//original').text
On my machine (OS X running python 2.6.1) that produces:
Ian-Cs-MacBook-Pro:tmp ian$ python test.py
http://i.stack.imgur.com/dxPGi.png
|
Save an array as bin in Matlab, pass it to Python and read the bin file in Python
Question: I am currently trying to save an array as bin file in Matlab, send it to
Python and read it in Python. However, Matlab is showing errors when I run it.
I am using the following codes:
Read the array in Matlab, convert to bin file and pass to Python:
array1 = rand(5,1); %% array1 is the desired array that needs to be sent to Python
fid = fopen('nazmul.bin','wb'); %% I want to save array1 in the nazmul.bin file
fwrite(fid,array1);
status=fclose(fid);
python('squared.py','nazmul.bin'); %% I want to send the parameters to squared.py program
squared.py file:
import sys
if __name__ == '__main__':
f = open("nazmul.bin", "rb") # Trying to open the bin file
try:
byte = f.read(1) # Reading the bin file and saving it in the byte array
while byte != "":
# Do stuff with byte.
byte = f.read(1)
finally:
f.close()
print byte # printing the byte array from Python
However, when I run this program, nothing gets printed. I guess that the bin
file is not getting passed properly to the squared.py file.
Thanks for your feedback.
Nazmul
Answer: There are several problems here.
1. You should use double underscore when checking for 'main'. I.e. `__main__ == "__main__"`.
2. You are _not_ collecting bytes but rather always storing the _last_ byte read. Therefore, the last byte is always `""`.
3. Finally, it seems like indentation is not correct. I assume this is just a stackoverflow formatting error.
4. One more potential issue - When you use fwrite(fid, A) in MATLAB, it assumes that you want to write bytes (8 bit numbers). However, your `rand()` command generates reals, so MATLAB first rounds the results to integers and your binary file will hold '0' or '1' only.
Final note: Reading a file one byte at a time is probably very inefficient. It
is probably better to read the file in large chunks, or - if it is a small
file - read the entire file in one `read()` operation.
The corrected Python code is as follows:
if __name__ == '__main__':
f = open("xxx.bin", "rb") # Trying to open the bin file
try:
a = [];
byte = f.read(1) # Reading the bin file and saving it in the byte array
while byte != "":
a.append(byte);
# Do stuff with byte.
byte = f.read(1)
finally:
f.close()
print a;
|
How to solve AttributeError when importing igraph?
Question: When I import the igraph package in my project, I get an AttributeError. This
only happens in the project directory:
[12:34][~]$ python2
Python 2.7.1 (r271:86832, Apr 15 2011, 12:09:10)
[GCC 4.5.2 20110127 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import igraph
>>>
[12:34][~]$ cd projectdir/
[12:34][projectdir]$ python2
Python 2.7.1 (r271:86832, Apr 15 2011, 12:09:10)
[GCC 4.5.2 20110127 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import igraph
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/igraph/__init__.py", line 42, in <module>
import gzip
File "/usr/lib/python2.7/gzip.py", line 36, in <module>
class GzipFile(io.BufferedIOBase):
AttributeError: 'module' object has no attribute 'BufferedIOBase'
>>>
There is no file igraph.py in the project directory:
[12:34][projectdir]$ ls -alR | grep igraph | wc -l
0
And there are no circular imports.
How can I solve this error?
Answer: Most likely, there is a module `io` in `~/projectdir` or one of the paths the
project configures. The gzip module imported by igraph starts with
import io
and expect the built-in io module, not your project's one. Look for an `io`
directory, or `io.py` or `io.pyc`. It can also help to scrutinize `sys.path`
for any other directories (maybe outside of `~/projectdir`) that might contain
modules named `io`.
|
Python: no module named unittest. How can I fix this?
Question: It seems strange that a module from the std Python lib to be missing. I'm
probably doing something wrong, but I cannot figure out what exactly.
shift@bt:~/experiments/$ python test/test_creation.py
'import site' failed; use -v for traceback
Traceback (most recent call last):
File "test/test_creation.py", line 1, in <module>
import unittest
ImportError: No module named unittest
Running with the -v switch shows this:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Traceback (most recent call last):
File "test/test_creation.py", line 1, in <module>
import unittest
ImportError: No module named unittest
# clear __builtin__._
# clear sys.path
# clear sys.argv
# clear sys.ps1
# clear sys.ps2
# clear sys.exitfunc
# clear sys.exc_type
# clear sys.exc_value
# clear sys.exc_traceback
# clear sys.last_type
# clear sys.last_value
# clear sys.last_traceback
# clear sys.path_hooks
# clear sys.path_importer_cache
# clear sys.meta_path
# clear sys.flags
# clear sys.float_info
# restore sys.stdin
# restore sys.stdout
# restore sys.stderr
# cleanup __main__
# cleanup[1] zipimport
# cleanup[1] signal
# cleanup[1] exceptions
# cleanup[1] _warnings
# cleanup sys
# cleanup __builtin__
# cleanup ints: 3 unfreed ints
# cleanup floats
Where should I look to figure out what's wrong?
Answer: You have your python environment installed into `/home/shift/experiments/lib`
? see docs.python.org on
[PYTHONHOME](http://docs.python.org/using/cmdline.html#envvar-PYTHONHOME)
|
urllib2 gives HTTP Error 400: Bad Request for certain urls, works for others
Question: I'm trying to do a simple HTTP get request with Python's urllib2 module. It
works sometimes, but other times I get `HTTP Error 400: Bad Request`. I know
it's not an issue with the URL, because if I use `urllib` and simply do
`urllib.urlopen(url)` it works fine - but when I add headers and do
`urllib2.urlopen()` I get Bad Request on certain sites.
Here is the code that's not working:
# -*- coding: utf-8 -*-
import re,sys,urllib,urllib2
url = "http://www.gamestop.com/"
headers = {'User-Agent:':'Mozilla/5.0'}
req = urllib2.Request(url,None,headers)
response = urllib2.urlopen(req,None)
html1 = response.read()
(gamestop.com is an example of a URL that does not work)
Some different sites work, some don't, so I'm not sure what I'm doing wrong
here. Am I missing some important headers? Making the request incorrectly?
Using the wrong User-Agent? (I also tried using the exact User-Agent of my
browser, and that didn't fix anything)
Thanks!
Answer: You've got an extra colon in your headers.
headers = { 'User-Agent:': 'Mozilla/5.0' }
Should be:
headers = { 'User-Agent': 'Mozilla/5.0' }
|
question about IDLE debugger in Python
Question: This is a simple question, is it possible to view an entire list in the locals
box of the IDLE debugger? Because right now, if a list becomes too long, the
debugger will put an ellipsis and not show the entire list. I also tried
typing in the name of the list in the actual python shell, but nothing
happened.
here is what i am seeing:`axyz
[[[-1,-1,-1,-1,-1,-1,...,1,-1,-1,-1,-1,-1,-1]]]` and if i type axyz into the
shell when the program is running, nothing happens.
Answer: If you need to dump out large quantities of debug information, import the
logging module and invoke it like so:
import logging
logging.debug(str(axyz))
Python's [logging module](http://docs.python.org/library/logging.html) is
tremendously versatile, and can be used for logging to any device in any
format you desire.
Other severity levels can be logged (`logging.info()`, `logging.error()`,
`logging.exception()`) and you can set the logging verbosity in configuration
later on.
|
Sibling package imports
Question: I've tried reading through questions about sibling imports and even the
[package documentation](http://docs.python.org/tutorial/modules.html#intra-
package-references), but I've yet to find an answer.
With the following structure:
├── LICENSE.md
├── README.md
├── api
│ ├── __init__.py
│ ├── api.py
│ └── api_key.py
├── examples
│ ├── __init__.py
│ ├── example_one.py
│ └── example_two.py
└── tests
│ ├── __init__.py
│ └── test_one.py
How can the scripts in the `examples` and `tests` directories import from the
`api` module and be run from the commandline?
Also, I'd like to avoid the ugly `sys.path.insert` hack for every file. Surely
this can be done in Python, right?
Answer: Here is another alternative that I insert at top of the Python files in
`tests` folder:
# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))
|
Python: Matplotlib - probability plot for several data set
Question: I have several data sets (distribution) as follows:
set1 = [1,2,3,4,5]
set2 = [3,4,5,6,7]
set3 = [1,3,4,5,8]
How do I plot a scatter plot with the data sets above with the y-axis being
the probability (i.e. the percentile of the distribution in set: 0%-100% ) and
the x-axis being the data set names? in JMP, it is called 'Quantile Plot'.
Something like image attached: ![enter image description
here](http://i.stack.imgur.com/XC786.png)
Please educate. Thanks.
**[EDIT]**
My data is in csv as such:
![enter image description here](http://i.stack.imgur.com/Xa39b.png)
Using JMP analysis tool, I'm able to plot the probability distribution plot
(QQ-plot/Normal Quantile Plot as figure far below):
![enter image description here](http://i.stack.imgur.com/IpTMc.png)
I believe Joe Kington almost has my problem solved but, I'm wondering how to
process the raw csv data into arrays of probalility or percentiles.
I doing this to automate some stats analysis in Python rather than depending
on JMP for plotting.
Answer: I'm not entirely clear on what you want, so I'm going to guess, here...
You want the "Probability/Percentile" values to be a cumulative histogram?
So for a single plot, you'd have something like this? (Plotting it with
markers as you've shown above, instead of the more traditional step plot...)
import scipy.stats
import numpy as np
import matplotlib.pyplot as plt
# 100 values from a normal distribution with a std of 3 and a mean of 0.5
data = 3.0 * np.random.randn(100) + 0.5
counts, start, dx, _ = scipy.stats.cumfreq(data, numbins=20)
x = np.arange(counts.size) * dx + start
plt.plot(x, counts, 'ro')
plt.xlabel('Value')
plt.ylabel('Cumulative Frequency')
plt.show()
![enter image description here](http://i.stack.imgur.com/39tkO.png)
If that's roughly what you want for a single plot, there are multiple ways of
making multiple plots on a figure. The easiest is just to use subplots.
Here, we'll generate some datasets and plot them on different subplots with
different symbols...
import itertools
import scipy.stats
import numpy as np
import matplotlib.pyplot as plt
# Generate some data... (Using a list to hold it so that the datasets don't
# have to be the same length...)
numdatasets = 4
stds = np.random.randint(1, 10, size=numdatasets)
means = np.random.randint(-5, 5, size=numdatasets)
values = [std * np.random.randn(100) + mean for std, mean in zip(stds, means)]
# Set up several subplots
fig, axes = plt.subplots(nrows=1, ncols=numdatasets, figsize=(12,6))
# Set up some colors and markers to cycle through...
colors = itertools.cycle(['b', 'g', 'r', 'c', 'm', 'y', 'k'])
markers = itertools.cycle(['o', '^', 's', r'$\Phi$', 'h'])
# Now let's actually plot our data...
for ax, data, color, marker in zip(axes, values, colors, markers):
counts, start, dx, _ = scipy.stats.cumfreq(data, numbins=20)
x = np.arange(counts.size) * dx + start
ax.plot(x, counts, color=color, marker=marker,
markersize=10, linestyle='none')
# Next we'll set the various labels...
axes[0].set_ylabel('Cumulative Frequency')
labels = ['This', 'That', 'The Other', 'And Another']
for ax, label in zip(axes, labels):
ax.set_xlabel(label)
plt.show()
![enter image description here](http://i.stack.imgur.com/7ZhT4.png)
If we want this to look like one continuous plot, we can just squeeze the
subplots together and turn off some of the boundaries. Just add the following
in before calling `plt.show()`
# Because we want this to look like a continuous plot, we need to hide the
# boundaries (a.k.a. "spines") and yticks on most of the subplots
for ax in axes[1:]:
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.yaxis.set_ticks([])
axes[0].spines['right'].set_color('none')
# To reduce clutter, let's leave off the first and last x-ticks.
for ax in axes:
xticks = ax.get_xticks()
ax.set_xticks(xticks[1:-1])
# Now, we'll "scrunch" all of the subplots together, so that they look like one
fig.subplots_adjust(wspace=0)
![enter image description here](http://i.stack.imgur.com/Xllnj.png)
Hopefully that helps a bit, at any rate!
Edit: If you want percentile values, instead a cumulative histogram (I really
shouldn't have used 100 as the sample size!), it's easy to do.
Just do something like this (using `numpy.percentile` instead of normalizing
things by hand):
# Replacing the for loop from before...
plot_percentiles = range(0, 110, 10)
for ax, data, color, marker in zip(axes, values, colors, markers):
x = np.percentile(data, plot_percentiles)
ax.plot(x, plot_percentiles, color=color, marker=marker,
markersize=10, linestyle='none')
![enter image description here](http://i.stack.imgur.com/hcPxv.png)
|
Python- Possible English one-word anagrams given input letters
Question: I know variations of this have been asked before, but I was unable to
understand any of the previous implementations because most of them involved
using sets and the issubset method.
Here is what I am trying to do: I have a set of words in a dictionary and a
list of possible letters. I want to find if the members of the set can be
formed through re-arranging the letters in the list. Here is my current
implementation:
def solve(dictionary, letters):
for word in dictionary: #for each word in the dictionary
if len(word) > len(letters): # first optimization, doesn't check words that are larger than letter set
continue
else:
scrambledword = "".join([b for b in sorted(list(word))]) #sorts the letters in each word
if set(scrambledword).issubset(letters):
print word
def main():
dictionary = set([x.strip() for x in open("C:\\Python27\\dictionary.txt")])
letters = sorted(['v','r','o','o','m','a','b','c','d'])
solve(dictionary, letters)
main()
The obvious problem with this implementation is that some words will be found
that use more than one letter in "letters." For example, the word 'cardboard'
appears as a valid word, despite there being only one copy of 'a' and 'r' in
the letters list. How do I use the "issubset" method on lists?
Answer: To know if you can make a word out of a set of letters [oops, I did it myself
-- I meant 'collection'!], you want every letter to occur at least the right
number of times, so I think we're going to have to work the counts in there
somehow. By definition, Python sets don't care about the number of elements in
a source list. Maybe something like
from collections import Counter
letters = ['v','r','o','o','m','a','b','c','d']
words = 'cardboard boom booom'.split()
letterscount = Counter(letters)
for word in words:
wordcount = Counter(word)
print word, all(letterscount[c] >= wordcount[c] for c in wordcount)
giving
cardboard False
boom True
booom False
Counter is a handy utility class:
>>> c = Counter(letters)
>>> c
Counter({'o': 2, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'm': 1, 'r': 1, 'v': 1})
>>> c['o']
2
>>> c['z']
0
[DSM: the return! I removed a community edit which doesn't work because
Counter instances aren't hashable.]
If searching speed is a concern, then you can trade off memory and
precomputation time:
from collections import defaultdict, Counter
from itertools import combinations
# precomputations
allwords = open('/usr/share/dict/words').read().split()
allwords = list(w for w in allwords if len(w) >= 3) # hack, /words contains lots of silliness
allwords_by_count = defaultdict(list)
for i, word in enumerate(allwords):
allwords_by_count[frozenset(word)].append((word, Counter(word)))
if i % 1000 == 0:
print i, word
def wordsfrom(letters, words_by_count):
lettercount = Counter(letters)
for subsetsize in range(1, len(lettercount)+1):
for subset in combinations(lettercount, subsetsize):
for possword, posswordcount in words_by_count[frozenset(subset)]:
if all(posswordcount[c] <= lettercount[c] for c in posswordcount):
yield possword
>>> wordsfrom('thistles', allwords_by_count)
<generator object wordsfrom at 0x1032956e0>
>>> list(wordsfrom('thistles', allwords_by_count))
['ess', 'sis', 'tit', 'tst', 'hei', 'hie', 'lei', 'lie', 'sie', 'sise', 'tie', 'tite', 'she', 'het', 'teth', 'the', 'els', 'less', 'elt', 'let', 'telt', 'set', 'sett', 'stet', 'test', 'his', 'hiss', 'shi', 'sish', 'hit', 'lis', 'liss', 'sil', 'lit', 'til', 'tilt', 'ist', 'its', 'sist', 'sit', 'shies', 'tithe', 'isle', 'sile', 'sisel', 'lite', 'teil', 'teli', 'tile', 'title', 'seit', 'sesti', 'site', 'stite', 'testis', 'hest', 'seth', 'lest', 'selt', 'lish', 'slish', 'hilt', 'lith', 'tilth', 'hist', 'sith', 'stith', 'this', 'list', 'silt', 'slit', 'stilt', 'liesh', 'shiel', 'lithe', 'shiest', 'sithe', 'theist', 'thesis', 'islet', 'istle', 'sistle', 'slite', 'stile', 'stilet', 'hitless', 'tehsil', 'thistle']
[Heh. I just noticed that 'thistles' itself isn't in the list, but that's
because it's not in the words file..]
And yes, the apparent "nonwords" there are really in the words file:
>>> assert all(w in allwords for w in (wordsfrom('thistles', allwords_by_count)))
>>>
|
how to get the math operators strings from module `operator` in python
Question: Take `operator.add` for example:
>>>import operator as op
>>>op.add(1,2) #means 1 + 2
3
>>>op.add.__name__
'add'
I want sort of:
>>>op.add.math_str
"+"
Can I get all those math string `"+", "-", ">"...` module `operator` supported
runtime?
EDIT:
>>> [eval(x) for x in [".".join(("op",x,"__doc__")) for x in dir(op)]]
['abs(a) -- Same as abs(a).',
'add(a, b) -- Same as a + b.',
'and_(a, b) -- Same as a & b.',
'concat(a, b) -- Same as a + b, for a and b sequences.',
'contains(a, b) -- Same as b in a (note reversed operands).',
'delitem(a, b) -- Same as del a[b].',
'delslice(a, b, c) -- Same as del a[b:c].',
'div(a, b) -- Same as a / b when __future__.division is not in effect.',
'str(object) -> string\n\nReturn a nice string representation of the object.\nIf the argument is a string, the return value is the same object.',
above code can list most operators strings, is that means I can list strings
with re module?
Thanks!
Answer: You can use the [following table from
tutorial](http://docs.python.org/library/operator.html?highlight=operator#mapping-
operators-to-functions) to build your own mappings dictionary only once and
then simply use it whenever you will need it.
|
How to compare two lists of dicts in Python?
Question: How do I compare two lists of `dict`? The result should be the odd ones out
from the list of dict B.
Example:
ldA = [{'user':"nameA", 'a':7.6, 'b':100.0, 'c':45.5, 'd':48.9},
{'user':"nameB", 'a':46.7, 'b':67.3, 'c':0.0, 'd':5.5}]
ldB =[{'user':"nameA", 'a':7.6, 'b':99.9, 'c':45.5, 'd':43.7},
{'user':"nameB", 'a':67.7, 'b':67.3, 'c':1.1, 'd':5.5},
{'user':"nameC", 'a':89.9, 'b':77.3, 'c':2.2, 'd':6.5}]
Here I want to compare ldA with ldB. It should print the below output.
ldB -> {user:"nameA", b:99.9, d:43.7}
ldB -> {user:"nameB", a:67.7, c:1.1 }
ldb -> {user:"nameC", a:89.9, b:77.3, c:2.2, d:6.5}
I have gone through the below link, but there it return onlys the name, but I
want name and value like above.
_[List of Dicts comparision to match between lists and detect value changes in
Python](http://stackoverflow.com/questions/2412562/list-of-dicts-comparision-
to-match-between-lists-and-detect-value-change-in-pytho)_
Answer: For a general solution, consider the following. It will properly diff, even if
the users are out of order in the lists.
def dict_diff ( merge, lhs, rhs ):
"""Generic dictionary difference."""
diff = {}
for key in lhs.keys():
# auto-merge for missing key on right-hand-side.
if (not rhs.has_key(key)):
diff[key] = lhs[key]
# on collision, invoke custom merge function.
elif (lhs[key] != rhs[key]):
diff[key] = merge(lhs[key], rhs[key])
for key in rhs.keys():
# auto-merge for missing key on left-hand-side.
if (not lhs.has_key(key)):
diff[key] = rhs[key]
return diff
def user_diff ( lhs, rhs ):
"""Merge dictionaries using value from right-hand-side on conflict."""
merge = lambda l,r: r
return dict_diff(merge, lhs, rhs)
import copy
def push ( x, k, v ):
"""Returns copy of dict `x` with key `k` set to `v`."""
x = copy.copy(x); x[k] = v; return x
def pop ( x, k ):
"""Returns copy of dict `x` without key `k`."""
x = copy.copy(x); del x[k]; return x
def special_diff ( lhs, rhs, k ):
# transform list of dicts into 2 levels of dicts, 1st level index by k.
lhs = dict([(D[k],pop(D,k)) for D in lhs])
rhs = dict([(D[k],pop(D,k)) for D in rhs])
# diff at the 1st level.
c = dict_diff(user_diff, lhs, rhs)
# transform to back to initial format.
return [push(D,k,K) for (K,D) in c.items()]
Then, you can check the solution:
ldA = [{'user':"nameA", 'a':7.6, 'b':100.0, 'c':45.5, 'd':48.9},
{'user':"nameB", 'a':46.7, 'b':67.3, 'c':0.0, 'd':5.5}]
ldB =[{'user':"nameA", 'a':7.6, 'b':99.9, 'c':45.5, 'd':43.7},
{'user':"nameB", 'a':67.7, 'b':67.3, 'c':1.1, 'd':5.5},
{'user':"nameC", 'a':89.9, 'b':77.3, 'c':2.2, 'd':6.5}]
import pprint
if __name__ == '__main__':
pprint.pprint(special_diff(ldA, ldB, 'user'))
|
small language in python
Question: I'm writing what might not even be called a language in python. I currently
have several operators: `+`, `-`, `*`, `^`, `fac`, `@`, `!!`. `fac` computes a
factorial, `@` returns the value of a variable, `!!` sets a variable. The code
is below. How would I go about writing a way to define functions in this
simple language?
EDIT: i updated the code!
import sys, shlex, readline, os, string
List, assign, call, add, sub, div, Pow, mul, mod, fac, duf, read,\
kill, clr, STO, RET, fib, curs = {}, "set", "get", "+", "-", "/", "^", "*",\
"%", "fact", "func", "read", "kill", "clear", ">", "@", "fib", "vars"
def fact(num):
if num == 1: return 1
else: return num*fact(num-1)
def Simp(op, num2, num1):
global List
try: num1, num2 = float(num1), float(num2)
except:
try: num1 = float(num1)
except:
try: num2 = float(num2)
except: pass
if op == mul: return num1*num2
elif op == div: return num1/num2
elif op == sub: return num1-num2
elif op == add: return num1+num2
elif op == Pow: return num1**num2
elif op == assign: List[num1] = num2; return "ok"
elif op == call: return List[num1]
elif op == fac: return fact(num1)
elif op == duf: return "%s %s %s"%(duf, num1, num2)
elif op == mod: return num1%num2
elif op == kill: del List[num1]; return "ok"
elif op == clr: os.system("clear")
elif op == STO: List[num2] = num1; return "ok"
elif op == RET: return List[num1]
elif op == curs: return List
elif op == read: List[num1] = Eval(raw_input("%s "%num1)); return "ok"
def Eval(expr):
ops = "%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s"%(mul, add, sub, div, Pow, assign, call, fac, duf, mod, read, kill, clr, STO, RET, curs)
stack, expr, ops = [], shlex.split(string.lower(expr)), ops.split()
for i in expr:
if i[0] != ';':
if i not in ops: stack.append(i)
elif i in ops: stack.append(Simp(i, stack.pop(), stack.pop()))
else: stack.append("ok")
return stack[0]
def shell():
try:
x = ""
while x != "quit":
x = raw_input("star> ")
try: l = Eval(x)
except KeyError: l = "does not exist"
except: l = "parse error!"
if l != None: print " =>",l,"\n"
except (EOFError, KeyboardInterrupt): print
if len(sys.argv) > 1:
x = open(sys.argv[1], 'r'); l = x.readlines(); x.close()
for i in l:
if i[0] != ";":
i = ' '.join(i.split())
x = Eval(i)
if x != None: print i,"\n =>",x,"\n"
else: pass
shell()
else: shell()
Answer: Your program is very confused, and it needs to be fixed before it can be
modified to support defining functions. I will do this in several steps and as
I complete them, I will add them into the answer. This answer will get to be
quite long.
Also, you obviously haven't decided what your language definition should be.
You've decided to make your language definition sort of follow your
implementation technique, and this is kind of broken, and results in a lot of
pain.
First, the definition for your `Simp` function is really broken. It demands
that everything take exactly two values off the stack, and put exactly one
value back on. This is broken. The factorial function doesn't work this way,
nor does the Fibonacci function, so you are forced to have a 'dummy' argument
that's never used. Also, things like assigning to an element of your global
list or dictionary have no reason to push values onto the stack, so you're
left pushing 'ok'. This is broken and needs fixing.
Here is the version with this problem fixed. Notice that I've renamed `Simp`
to `builtin_op` to more accurately reflect its purpose:
import sys, shlex, readline, os, string
List, assign, call, add, sub, div, Pow, mul, mod, fac, duf, read,\
kill, clr, STO, RET, fib, curs = {}, "set", "get", "+", "-", "/", "^", "*",\
"%", "fact", "func", "read", "kill", "clear", ">", "@", "fib", "vars"
def fact(num):
if num == 1: return 1
else: return num*fact(num-1)
def builtin_op(op, stack):
global List
if op == mul: stack.append(float(stack.pop())*float(stack.pop()))
elif op == div: stack.append(float(stack.pop())/float(stack.pop()))
elif op == sub: stack.append(float(stack.pop())-float(stack.pop()))
elif op == add: stack.append(float(stack.pop())+float(stack.pop()))
elif op == Pow: stack.append(float(stack.pop())**float(stack.pop()))
elif op == assign: val = List[stack.pop()] = stack.pop(); stack.append(val)
elif op == call: stack.append(List[stack.pop()])
elif op == fac: stack.append(fact(stack.pop()))
elif op == duf: stack.append("%s %s %s" % (duf, stack.pop(), stack.pop()))
elif op == mod: stack.append(float(stack.pop())%float(stack.pop()))
elif op == kill: del List[stack.pop()]
elif op == clr: os.system("clear")
elif op == STO: val = List[stack.pop()] = stack.pop(); stack.append(val)
elif op == RET: stack.append(List[stack.pop()])
elif op == curs: stack.append(List)
elif op == read: prompt = stack.pop(); List[prompt] = Eval(raw_input("%s "%prompt)); stack.append(List[prompt])
def Eval(expr):
ops = "%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s"%(mul, add, sub, div, Pow, assign, call, fac, duf, mod, read, kill, clr, STO, RET, curs)
stack, expr, ops = [], shlex.split(string.lower(expr)), ops.split()
for i in expr:
if i[0] != ';':
if i not in ops: stack.append(i)
elif i in ops: builtin_op(i, stack)
else: stack.append("ok")
return stack[0]
def shell():
try:
x = ""
while x != "quit":
x = raw_input("star> ")
try: l = Eval(x)
except KeyError: l = "does not exist"
except: l = "parse error!"
if l != None: print " =>",l,"\n"
except (EOFError, KeyboardInterrupt): print
if len(sys.argv) > 1:
x = open(sys.argv[1], 'r'); l = x.readlines(); x.close()
for i in l:
if i[0] != ";":
i = ' '.join(i.split())
x = Eval(i)
if x != None: print i,"\n =>",x,"\n"
else: pass
shell()
else: shell()
There are still a number of problems here that aren't fixed, and I won't fix
in any future version. For example, it's possible a value on the stack cannot
be interpreted as a floating point number. This will cause an exception, and
this exception may be thrown before the other value is read off the stack.
This means that if the wrong 'types' are on the stack the stack could be in an
ambiguous state after a 'parse error'. Generally you want to avoid situations
like this in a language.
Defining functions is an interesting problem. In your language, evaluation is
immediate. You don't have a mechanism for delaying evaluation until later.
But, you're using the `shlex` module for parsing. And it has a way of saying
that a whole group of characters (including spaces and such) are part of one
entity. This gives us a quick and easy way to implement functions. You can do
something like this:
star> "3 +" add3 func
to create your function, and:
star> 2 add3 get
to call it. I used `get` because that's what you've assigned to `call` in your
program.
The only problem is that the function is going to need access to the current
state of the stack in order to work. You can easily feed the string for the
function back into `Eval`, but `Eval` always creates a brand new stack each
time it is called. In order to implement functions, this needs to be fixed. So
I've added a defaulted `stack` argument to the `Eval` function. If this
argument is left at its default value, `Eval` will still create a new stack,
just like before. But if an existing stack is passed in, `Eval` will use it
instead.
Here is the modified code:
import sys, shlex, readline, os, string
List, assign, call, add, sub, div, Pow, mul, mod, fac, duf, read,\
kill, clr, STO, RET, fib, curs = {}, "set", "get", "+", "-", "/", "^", "*",\
"%", "fact", "func", "read", "kill", "clear", ">", "@", "fib", "vars"
funcdict = {}
def fact(num):
if num == 1: return 1
else: return num*fact(num-1)
def builtin_op(op, stack):
global List
global funcdict
if op == mul: stack.append(float(stack.pop())*float(stack.pop()))
elif op == div: stack.append(float(stack.pop())/float(stack.pop()))
elif op == sub: stack.append(float(stack.pop())-float(stack.pop()))
elif op == add: stack.append(float(stack.pop())+float(stack.pop()))
elif op == Pow: stack.append(float(stack.pop())**float(stack.pop()))
elif op == assign: val = List[stack.pop()] = stack.pop(); stack.append(val)
elif op == call: Eval(funcdict[stack.pop()], stack)
elif op == fac: stack.append(fact(stack.pop()))
elif op == duf: name = stack.pop(); funcdict[name] = stack.pop(); stack.append(name)
elif op == mod: stack.append(float(stack.pop())%float(stack.pop()))
elif op == kill: del List[stack.pop()]
elif op == clr: os.system("clear")
elif op == STO: val = List[stack.pop()] = stack.pop(); stack.append(val)
elif op == RET: stack.append(List[stack.pop()])
elif op == curs: stack.append(List)
elif op == read: prompt = stack.pop(); List[prompt] = Eval(raw_input("%s "%prompt)); stack.append(List[prompt])
def Eval(expr, stack=None):
ops = "%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s"%(mul, add, sub, div, Pow, assign, call, fac, duf, mod, read, kill, clr, STO, RET, curs)
if stack is None:
stack = []
expr, ops = shlex.split(string.lower(expr)), ops.split()
for i in expr:
if i[0] != ';':
if i not in ops: stack.append(i)
elif i in ops: builtin_op(i, stack)
else: stack.append("ok")
return stack[0]
def shell():
try:
x = ""
while x != "quit":
x = raw_input("star> ")
try: l = Eval(x)
except KeyError: l = "does not exist"
except: l = "parse error!"
if l != None: print " =>",l,"\n"
except (EOFError, KeyboardInterrupt): print
if len(sys.argv) > 1:
x = open(sys.argv[1], 'r'); l = x.readlines(); x.close()
for i in l:
if i[0] != ";":
i = ' '.join(i.split())
x = Eval(i)
if x != None: print i,"\n =>",x,"\n"
else: pass
shell()
else: shell()
In stack based languages, two very useful built in operators are `dup` and
`swap`. `dup` takes the top stack element and duplicates it. `swap` swaps the
top two stack elements.
If you have `dup` you can implement a `square` function like so:
star> "dup *" square func
Here is your program with `dup` and `swap` implemented:
import sys, shlex, readline, os, string
List, assign, call, add, sub, div, Pow, mul, mod, fac, duf, read,\
kill, clr, STO, RET, fib, curs, dup, swap = {}, "set", "get", "+", "-", "/", "^", "*",\
"%", "fact", "func", "read", "kill", "clear", ">", "@", "fib", "vars", "dup", "swap"
funcdict = {}
def fact(num):
if num == 1: return 1
else: return num*fact(num-1)
def builtin_op(op, stack):
global List
global funcdict
if op == mul: stack.append(float(stack.pop())*float(stack.pop()))
elif op == div: stack.append(float(stack.pop())/float(stack.pop()))
elif op == sub: stack.append(float(stack.pop())-float(stack.pop()))
elif op == add: stack.append(float(stack.pop())+float(stack.pop()))
elif op == Pow: stack.append(float(stack.pop())**float(stack.pop()))
elif op == assign: val = List[stack.pop()] = stack.pop(); stack.append(val)
elif op == call: Eval(funcdict[stack.pop()], stack)
elif op == fac: stack.append(fact(stack.pop()))
elif op == duf: name = stack.pop(); funcdict[name] = stack.pop(); stack.append(name)
elif op == mod: stack.append(float(stack.pop())%float(stack.pop()))
elif op == kill: del List[stack.pop()]
elif op == clr: os.system("clear")
elif op == STO: val = List[stack.pop()] = stack.pop(); stack.append(val)
elif op == RET: stack.append(List[stack.pop()])
elif op == curs: stack.append(List)
elif op == dup: val = stack.pop(); stack.append(val); stack.append(val)
elif op == swap: val1 = stack.pop(); val2 = stack.pop(); stack.append(val1); stack.append(val2)
elif op == read: prompt = stack.pop(); List[prompt] = Eval(raw_input("%s "%prompt)); stack.append(List[prompt])
def Eval(expr, stack=None):
ops = "%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s"%(mul, add, sub, div, Pow, assign, call, fac, duf, mod, read, kill, clr, STO, RET, curs, dup, swap)
if stack is None:
stack = []
expr, ops = shlex.split(string.lower(expr)), ops.split()
for i in expr:
if i[0] != ';':
if i not in ops: stack.append(i)
elif i in ops: builtin_op(i, stack)
else: stack.append("ok")
return stack[0]
def shell():
try:
x = ""
while x != "quit":
x = raw_input("star> ")
try: l = Eval(x)
except KeyError: l = "does not exist"
except: l = "parse error!"
if l != None: print " =>",l,"\n"
except (EOFError, KeyboardInterrupt): print
if len(sys.argv) > 1:
x = open(sys.argv[1], 'r'); l = x.readlines(); x.close()
for i in l:
if i[0] != ";":
i = ' '.join(i.split())
x = Eval(i)
if x != None: print i,"\n =>",x,"\n"
else: pass
shell()
else: shell()
Lastly, here is my version in Python that's much clearer (in my opinion
anyway) than the Python you've written:
import shlex, functools, sys, StringIO
def bin_numeric_op(func):
@functools.wraps(func)
def execute(self):
n2, n1 = self._stack.pop(), self._stack.pop()
n1 = float(n1)
n2 = float(n2)
self._stack.append(func(n1, n2))
return execute
def relational_op(func):
@functools.wraps(func)
def execute(self):
n2, n1 = self._stack.pop(), self._stack.pop()
self._stack.append(bool(func(n1, n2)))
return execute
def bin_bool_op(func):
@functools.wraps(func)
def execute(self):
n2, n1 = self._stack.pop(), self._stack.pop()
n1 = bool(n1)
n2 = bool(n2)
self._stack.append(bool(func(n1, n2)))
return execute
class Interpreter(object):
def __init__(self):
self._stack = []
self._vars = {}
self._squarestack = []
def processToken(self, token):
if token == '[':
self._squarestack.append(len(self._stack))
# Currently inside square brackets, don't execute
elif len(self._squarestack) > 0:
if token == ']':
startlist = self._squarestack.pop()
lst = self._stack[startlist:]
self._stack[startlist:] = [tuple(lst)]
else:
self._stack.append(token)
# Not current inside list and close square token, something's wrong.
elif token == ']':
raise ValueError("Unmatched ']'")
elif token in self.builtin_ops:
self.builtin_ops[token](self)
else:
self._stack.append(token)
def get_stack(self):
return self._stack
def get_vars(self):
return self._vars
@bin_numeric_op
def add(n1, n2):
return n1 + n2
@bin_numeric_op
def mul(n1, n2):
return n1 * n2
@bin_numeric_op
def div(n1, n2):
return n1 / n2
@bin_numeric_op
def sub(n1, n2):
return n1 - n2
@bin_numeric_op
def mod(n1, n2):
return n1 % n2
@bin_numeric_op
def Pow(n1, n2):
return n1**n2
@relational_op
def less(v1, v2):
return v1 < v2
@relational_op
def lesseq(v1, v2):
return v1 <= v2
@relational_op
def greater(v1, v2):
return v1 > v2
@relational_op
def greatereq(v1, v2):
return v1 > v2
@relational_op
def isequal(v1, v2):
return v1 == v2
@relational_op
def isnotequal(v1, v2):
return v1 != v2
@bin_bool_op
def bool_and(v1, v2):
return v1 and v2
@bin_bool_op
def bool_or(v1, v2):
return v1 or v2
def bool_not(self):
stack = self._stack
v1 = stack.pop()
stack.append(not v1)
def if_func(self):
stack = self._stack
pred = stack.pop()
code = stack.pop()
if pred:
self.run(code)
def ifelse_func(self):
stack = self._stack
pred = stack.pop()
nocode = stack.pop()
yescode = stack.pop()
code = yescode if pred else nocode
self.run(code)
def store(self):
stack = self._stack
value = stack.pop()
varname = stack.pop()
self._vars[varname] = value
def fetch(self):
stack = self._stack
varname = stack.pop()
stack.append(self._vars[varname])
def remove(self):
varname = self._stack.pop()
del self._vars[varname]
# The default argument is because this is used internally as well.
def run(self, code=None):
if code is None:
code = self._stack.pop()
for tok in code:
self.processToken(tok)
def dup(self):
self._stack.append(self._stack[-1])
def swap(self):
self._stack[-2:] = self._stack[-1:-3:-1]
def pop(self):
self._stack.pop()
def showstack(self):
print"%r" % (self._stack,)
def showvars(self):
print "%r" % (self._vars,)
builtin_ops = {
'+': add,
'*': mul,
'/': div,
'-': sub,
'%': mod,
'^': Pow,
'<': less,
'<=': lesseq,
'>': greater,
'>=': greatereq,
'==': isequal,
'!=': isnotequal,
'&&': bool_and,
'||': bool_or,
'not': bool_not,
'if': if_func,
'ifelse': ifelse_func,
'!': store,
'@': fetch,
'del': remove,
'call': run,
'dup': dup,
'swap': swap,
'pop': pop,
'stack': showstack,
'vars': showvars
}
def shell(interp):
try:
while True:
x = raw_input("star> ")
msg = None
try:
interp.run(shlex.split(x))
except KeyError:
msg = "does not exist"
except:
sys.excepthook(*sys.exc_info())
msg = "parse error!"
if msg != None:
print " =>",msg,"\n"
else:
print " => %r\n" % (interp.get_stack(),)
except (EOFError, KeyboardInterrupt):
print
interp = Interpreter()
if len(sys.argv) > 1:
lex = shlex.shlex(open(sys.argv[1], 'r'), sys.argv[1])
tok = shlex.get_token()
while tok is not None:
interp.processToken(tok)
tok = lex.get_token()
shell(interp)
This new version supports an `if` and `ifelse` statement. With this and
function calls, it's possible to implement the `fib` and `fact` functions in
the language. I will add in how you would define these later.
Here is how you would define the `fib` function:
star> fib [ dup [ pop 1 0 + ] swap [ dup 1 - fib @ call swap 2 - fib @ call + ] swap 0 + 2 0 + < ifelse ] !
=> []
star> 15 fib @ call
=> [987.0]
The `0 + 2 0 +` sequence before the `<` is to force the comparison to be a
numeric comparison.
Also notice how the `[` and `]` single characters are quoting operators. They
cause everything between them to be not executed and instead stored on the
stack as a single list of items. This is the key to defining functions.
Functions are a sequence of tokens that you can execute with the `call`
operator. They can also be used for 'anonymous blocks' that are sort of a
cross between `lambda` expressions and a standard Python block. These are used
in the `fib` function for the two possible paths of the `ifelse` statement.
The parser for this is ridiculously simple. And `shlex` is plenty powerful
enough as a lexer for this simple language. Other projects would be fetching
individual items out of a list. Creating a new list that consists of only a
portion of a previous list. 'Listifying' a single token on the stack.
Implementation of a `while` primitive. Numeric operators that operate on
integers (in actual Forth, the numeric operations by default operate on
integers and you need to specify something like `+.` to get a floating point
version). And some operations on symbol tokens that allow string manipulation.
Perhaps a 'split' and 'join' operation that turns a token into a list of
individual tokens for the characters or joins a list together into a single
token would be sufficient.
|
pyparsing issue
Question: Right now I have just started to use `pyparsing` to parse simple postfix
expressions. At the moment, I got this far:
from pyparsing import *
integer = Word(nums)
op = Word("+-*/^", max=1)
space = Word(" ")
expr = Word(nums)+space+Word(nums)+space+op
parsed = expr.parseString("3 4 *")
print parsed
But when I run it, it prints:
Traceback (most recent call last):
File "star_parse.py", line 6, in <module>
parsed = expr.parseString("3 4 *")
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pyparsing-1.5.5-py2.6.egg/pyparsing.py", line 1100, in parseString
raise exc
pyparsing.ParseException: Expected W:( ) (at char 2), (line:1, col:3)
What am I doing wrong?
Answer: White space is handled by default. There is also the handy `oneOf`:
from pyparsing import *
integer = Word(nums)
op = oneOf('* + - / ^')
expr = integer + integer + op
parsed = expr.parseString("3 4 *")
print parsed
|
Importing a long list of constants to a Python file
Question: In Python, is there an analogue of the `C` preprocessor statement such as?:
`#define MY_CONSTANT 50`
Also, I have a large list of constants I'd like to import to several classes.
Is there an analogue of declaring the constants as a long sequence of
statements like the above in a `.py` file and importing it to another `.py`
file?
Edit.
The file `Constants.py` reads:
#!/usr/bin/env python
# encoding: utf-8
"""
Constants.py
"""
MY_CONSTANT_ONE = 50
MY_CONSTANT_TWO = 51
And `myExample.py` reads:
#!/usr/bin/env python
# encoding: utf-8
"""
myExample.py
"""
import sys
import os
import Constants
class myExample:
def __init__(self):
self.someValueOne = Constants.MY_CONSTANT_ONE + 1
self.someValueTwo = Constants.MY_CONSTANT_TWO + 1
if __name__ == '__main__':
x = MyClass()
Edit.
From the compiler,
> NameError: "global name 'MY_CONSTANT_ONE' is not defined"
>
> function **init** in myExample at line 13 self.someValueOne =
> Constants.MY_CONSTANT_ONE + 1 copy output Program exited with code #1 after
> 0.06 seconds.
Answer: Python isn't preprocessed. You can just create a file `myconstants.py`:
MY_CONSTANT = 50
And importing them will just work:
import myconstants
print myconstants.MY_CONSTANT * 2
|
sharing variables between powershell and C#
Question: I am trying to build a document assembly application in .Net that will allow
rules and conditions to be embedded within the document fragments, presumably
using some kind of scripting language (and I don't really want to invent my
own scripting language)
I need the ability for the c# code to invoke the scripting language and vice
versa, but importantly I also want them to be able to share arbitrary data
structures by reference (not just passing a couple of strings back and forward
by value)
Can I do this with powershell or do I need to use a DLR language such as
IronPython? Come to that, are there other advantages of using a DLR language
which mean I should use DLR anyway?
Andy
Answer: I think [this
article](http://www.codeproject.com/KB/cs/HowToRunPowerShell.aspx) is exactly
what you're looking for (for Powershell, anyway).
Using a DLR language might bring the bits of code you'll be executing a little
bit closer to home. Invoking Powershell from a .NET app executes on a new
thread according to the above article.
In any case, I would personally be leery of executing random bits of any
scripting language without defining a subset of allowed commands and
validating the input against that.
|
What's the best way to initialise and use contants across Python classes?
Question: Here's how I am declaring constants and using them across different Python
classes:
# project/constants.py
GOOD = 1
BAD = 2
AWFUL = 3
# project/question.py
from constants import AWFUL, BAD, GOOD
class Question:
def __init__(self):
...
Is the above a good way to store and use contant values? I realise that after
a while, the constants file can get pretty big and I could explicitly be
importing 10+ of those constants in any given file.
Answer: why not just use
import constants
def use_my_constants():
print constants.GOOD, constants.BAD, constants.AWFUL
From the python zen:
> Namespaces are good. Lets do more of those!
**EDIT:** Except, when you do quote, you should include a reference and check
it, because as others have pointed out, it should read:
> Namespaces are one honking great idea -- let's do more of those!
This time, I actually copied it from the source: [PEP 20 -- The Zen of
Python](http://www.python.org/dev/peps/pep-0020/)
|
Keeping a pipe to a process open
Question: I have an `app` that reads in stuff from `stdin` and returns, after a newline,
results to `stdout`
A simple (stupid) example:
$ app
Expand[(x+1)^2]<CR>
x^2 + 2*x + 1
100 - 4<CR>
96
Opening and closing the `app` requires a lot of initialization and clean-up
(its an interface to a Computer Algebra System), so I want to keep this to a
minimum.
I want to open a pipe in Python to this process, write strings to its `stdin`
and read out the results from `stdout`. `Popen.communicate()` doesn't work for
this, as it closes the file handle, requiring to reopen the pipe.
I've tried something along the lines of this related question: [Communicate
multiple times with a process without breaking the
pipe?](http://stackoverflow.com/questions/3065060/communicate-multiple-times-
with-a-process-without-breaking-the-pipe) but I'm not sure how to wait for the
output. It is also difficult to know a priori how long it will take the `app`
to finish to process for the input at hand, so I don't want to make any
assumptions. I guess most of my confusion comes from this question: [Non-
blocking read on a subprocess.PIPE in
python.](http://stackoverflow.com/questions/375427/non-blocking-read-on-a-
subprocess-pipe-in-python) where it is stated that mixing high and low level
functions is not a good idea.
**EDIT** : Sorry that I didn't give any code before, got interrupted. This is
what I've tried so far and it seems to work, I'm just worried that something
goes wrong unnoticed:
from subprocess import Popen, PIPE
pipe = Popen(["MathPipe"], stdin=PIPE, stdout=PIPE)
expressions = ["Expand[(x+1)^2]", "Integrate[Sin[x], {x,0,2*Pi}]"] # ...
for expr in expressions:
pipe.stdin.write(expr)
while True:
line = pipe.stdout.readline()
if line != '':
print line
# output of MathPipe is always terminated by ';'
if ";" in line:
break
Potential problems with this?
Answer: Using subprocess, you can't do this reliably. You might want to look at using
the [pexpect](http://www.noah.org/wiki/Pexpect) library. That won't work on
Windows - if you're on Windows, try
[winpexpect](http://pypi.python.org/pypi/winpexpect/1.4).
Also, if you're trying to do mathematical stuff in Python, check out
[SAGE](http://sagemath.org/). They do a lot of work on interfacing with other
open-source maths software, so there's a chance they've already done what
you're trying to.
|
using pipe with python
Question:
import re
import subprocess
sub = subprocess.Popen(['/home/karthik/Downloads/stanford-parser-2011-06- 08/lexparser.csh'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr = subprocess.PIPE)
sub.stdin.write("i am a fan of ac milan which is the best club in the world")
relns = []
while(True):
rel = sub.stdout.readline()
m = re.search("Sentence skipped", rel)
if m != None:
print 'stop'
sys.exit(0)
if rel == '\n':
break
relns.append(rel)
print relns
sub.terminate()
So i want to the stanford parser and using the lexparser.csh to parse this
line of text . But when i run this piece of code i am a getting the output of
the default of text. The actual text given in is not being parsed. So am i
using pipes the right way ?And i've seen in a lot of examples - a '-' is used
along with the command . Why is that being used ? Cos when i use that the
script just stalls at sub.stdout.readline()
Answer: You may need to call `flush()` on `sub.stdin` after writing.
|
How do I run some python code in another process?
Question: I want to start, from Python, some other Python code, preferably a function,
but in **another process**.
It is mandatory to run this in another process, because I want to run some
concurrency tests, like opening a file that was opened exclusively by the
parent process (this has to fail).
Requirements:
* multiplatform: linux, osx, windows
* compatible with Python 2.6-3.x
Answer: I would seriously take a look at the documentation for
[multiprocessing](http://docs.python.org/library/multiprocessing.html) library
of Python. From the first sentence of the package's description:
> multiprocessing is a package that supports spawning processes using an API
> similar to the threading module.
It then goes on to say that it side-steps the GIL, which is what it sounds
like you're trying to avoid. See their example of a trivial set up:
from multiprocessing import Process
def f(name):
print 'hello', name
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
That's a function call being done in another process separate from the process
you're inside. Again, all this from the documentation.
|
Forward-compatible print statement in python 2.5
Question: OK, maybe I'm just having an off day. This seems like something a lot of
people must be asking, but Google is failing me horribly. The closest thing I
found was [this](http://stackoverflow.com/questions/388069/python-graceful-
future-feature-future-import) which doesn't exactly address this issue.
At work I run Arch on my desktop (which is python 3 by default), and Debian
Lenny on my company's servers (which is python 2.5). I want to write a single
python script that will work in both python 2 and 3. It's a very simple
script, not much to it (mostly it just calls off to git using `subprocess`).
Everything already works in both versions of python EXCEPT for the damned
`print` statements.
Everyone out there seems to suggest the `from __future__ import
print_function` trick. However this was introduced in python 2.6, and I'm
stuck with 2.5.
So what are my options? How can I call `print` in both 2.5 and 3 using the
same script? I was thinking maybe some kind of wrapper function, but this
might not be the most "pythonic" way of doing things. Your thoughts? And no,
upgrading the server to 2.6 isn't an option.
Thanks!
Answer: `print("hi")` works on both py 2 and 3 without `from __future__` in py 2.5
alternatively, although not recommended:
import sys
sys.stdout.write("hi")
|
counting (large number of) strings within (very large) text
Question: I've seen a couple variations of the "efficiently search for strings within
file(s)" question on Stackoverflow but not quite like my situation.
* I've got one text file which contains a relatively large number (>300K) of strings. The vast majority of these strings are multiple words (for ex., "Plessy v. Ferguson", "John Smith", etc.).
* From there, I need to search through a very large set of text files (a set of legal docs totaling >10GB) and tally the instances of those strings.
Because of the number of search strings, the strings having multiple words,
and the size of the search target, a lot of the "standard" solutions seem fall
to the wayside.
Some things simplify the problem a little -
* I don't need sophisticated tokenizing / stemming / etc. (e.g. the only instances I care about are "Plessy v. Ferguson", don't need to worry about "Plessy", "Plessy et. al." etc.)
* there will be some duplicates (for ex., multiple people named "John Smith"), however, this isn't a very statistically significant issue for this dataset so... if multiple John Smith's get conflated into a single tally, that's ok for now.
* I only need to count these specific instances; I don't need to return search results
* 10 instances in 1 file count the same as 1 instance in each of 10 files
Any suggestions for quick / dirty ways to solve this problem?
I've investigated NLTK, Lucene & others but they appear to be overkill for the
problem I'm trying to solve. Should I suck it up and import everything into a
DB? bruteforce grep it 300k times? ;)
My preferred dev tool is Python.
* * *
The docs to be searched are primarily legal docs like this -
<http://www.lawnix.com/cases/plessy-ferguson.html>
The intended results are tallys for how often the case is referenced across
those docs - "Plessey v. Ferguson: 15"
Answer: An easy way to solve this is to build a trie with your queries (simply a
prefix tree, list of nodes with a single character inside), and when you
search through your 10gb file you go through your tree recursively as the text
matches.
This way you prune _a lot_ of options really early on in your search for each
character position in the big file, while still searching your whole solution
space.
Time performance will be very good (as good as a lot of other, more
complicated solutions) and you'll only need enough space to store the tree (a
lot less than the whole array of strings) and a small buffer into the large
file. Definitely a lot better than grepping a db 300k times...
|
python version of C unsigned char
Question: I need help with a python version for this C code:
#define HostBusy_high 0x02
#define control_register 0x37a
Out32 (control_register,(unsigned char)(Inp32(control_register) | HostBusy_high));
the Out32 and Inp32 are functions located in the inpout32.dll used to
interface parallel ports. These functions take hex values as their parameters.
I tried to code in python to get the desired value but that is not what I am
getting. See python version below:
from ctypes import windll
#parallel port instance
p_port = windll.inpout32
HostBusy_high = 0x02
control_register = 0x37a
write_data = write(p_port(Inp32(control_register) | HostBusy_high))
Out32 (control_register,write_data))
With the code above i do not seem to get the value I want. I suspect it is the
unsigned value.
Thanks
Answer: Depends on why you need an unsigned char. For most purposes you'll just use a
Python integer. If you need to actually have a one-byte datum, you can use
Python's struct.pack to make a one-byte byte string out of an integer.
You can't, in general, get good results by doing line by line literal
translation of code between languages, without a good understanding of both
the source and target languages, as well as the body of code you're
translating.
|
Help verifying RSA signed text with Python
Question: Using Java I have created RSA keypairs. Using Java I can use these keys to
sign and verify some text. I can also "export" these keys in PEM format and
load them into a Python test script. Once in the Python script, I can use
these keys to sign and verify some text using M2Crypto.
I have not yet been able to verify in Python the signature I created in Java.
Right now I am just trying to get cross-platform signing and verifying to
work.
Here is Java snippet:
Signature sig = Signature.getInstance("MD5WithRSA");
sig.initSign(key.getPrivate());
sig.update("This is a message.".getBytes("UTF8"));
byte[] signatureBytes = sig.sign();
return Base64.encodeBytes(signatureBytes, Base64.DO_BREAK_LINES);
Which generates:
PIp4eLhA941xmpdqu7j60731R9oWSNWcHvwoVADKxABGoUE02eDS0qZ4yQD2vYBdRDXXxHV4UjtW
YQwv9nsOzCBWeDQ0vv6W0dLVfTBuk79On7AALuwnTFr8s0y5ZN5RINvPPR60mwONav26ZbPj4ub3
NZqUS/zkqyO8Z8D2zUjk0pqAhWDGbFBaWPQJBPOY9iRt8GlsAUkGfYGeIx9DNU8aiJmQ3NnUHbs4
5NEr3xydbNJjwK96kkNJ9vyKZRfnNd4eW2UllPiwJSRQgefCQfh79ZuiYeQEuk3HMh7Si4iYl7uU
rWCgYFl4fGV1X/k+BSHR4ZZFWGQ3IPfafYHyNw==
And here is the public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg+N7xQHVHU3VHMZ9VGFdUf6ud3rAL8YS
sfWv2zFMnKAjh6XacwDGX6jJR/0/pyDriRGw/uodBDSFvgn9XEM/srMYtbJ1KQ9R9ChDifixF3Hx
yzbzPRvFoEfZnS/63+d1r0wnafz7xx0eDEYE3TgRKTMikwOsuIOFWa7GhA4BvP7ad79bI5ORJdLu
9Je+k+4dbt0xk2t7YopxYmyU+4zhZMxuthJTr69rXgqhgsCRdK6kFIGm3YuJ1WQcci8OVwH+3o7F
XzJHpSTxH57m6PX5lXaywIDCbUauTpBV3w+0vTeGI/2o+U40qhLBkpZT9GSVKxgXl5a0XxrkwTGn
61XZqQIDAQAB
-----END PUBLIC KEY-----
Then in Python the key is loaded and the signature is attempted to be
verified:
from M2Crypto import RSA, EVP
pub_key = RSA.load_pub_key('public_key.pem')
verify_evp = EVP.PKey()
verify_evp.assign_rsa(pub_key)
verify_evp.verify_init()
verify_evp.verify_update("This is a message.")
if verify_evp.verify_final(sig_string.decode('base64')) == 1:
print "Good"
else:
print "Bad"
And this does not verify. I suspect it is some leading or trailing characters
or encoding weirdness that I don't understand.
I have no particular attachement to M2Crypto and have played a bit with the
gdata.tlslite modules as well.
Please note that the keys are working, and that the text and signature above
verify in Java, and the keys (public and private) can be used within Python to
sign and verify text. The problem is somewhere in how Java-generated signature
and/or the message text is getting into the Python code.
What am I doing wrong?
Answer: `M2Crypto.EVP` defaults to 'sha1' (SHA1) and you're using `MD5WithRSA`. I
think you should switch `SHA1WithRSA` (MD5 is a **very** weak algorithm).
|
Wrapping C++ classes that contain wxString with Cython
Question: I'm working on a Python extension to tie in with a C++ application written
using wxWidgets for the GUI. I'm using Cython, and have the basic system
(build tools, plus a starter extension with appropriate version details etc)
happily working.
I'm only interested in making backend (non-GUI) functionality available, such
as file parsing and processing. However, all classes - not just the GUI ones -
use `wxString` for string data, such as in the following minimal example:
#include <wx/string.h>
class MyClass{
wxString name;
wxString get_name(){
return this->name;
}
};
My question is what is the best way to go about wrapping such a class? Is
there a simple way to interface between a Python string and a `wxString`
instance? Or will I need to wrap the `wxString` class as well? Am I able to
tie in somehow with the wxPython port to avoid re-inventing the wheel?
Answer: I got it to work by using the static `wxString::FromUTF8()` function to
convert from Python to wxString, and the `wxString.ToUTF8()` to go in the
other direction. The following is the code I came up with:
# Import the parts of wxString we want to use.
cdef extern from "wx/string.h":
cdef cppclass wxString:
char* ToUTF8()
# Import useful static functions from the class.
cdef extern from "wx/string.h" namespace "wxString":
wxString FromUTF8(char*)
# Function to convert from Python string to wxString. This can be given either
# a unicode string, or a UTF-8 encoded byte string. Results with other encodings
# are undefined and will probably lead to errors.
cdef inline wxString from_python(python_string):
# If it is a Python unicode string, encode it to a UTF-8 byte string as this
# is how we will pass it to wxString.
if isinstance(python_string, unicode):
byte_string = python_string.encode('UTF-8')
# It is already a byte string, and we have no choice but to assume its valid
# UTF-8 as theres no (sane/efficient) way to detect the encoding.
else:
byte_string = python_string
# Turn the byte string (which is still a Python object) into a C-level char*
# string.
cdef char* c_string = byte_string
# Use the static wxString::FromUTF8() function to get us a wxString.
return FromUTF8(c_string)
# Function to convert a wxString to a UTF-8 encoded Python byte string.
cdef inline object to_python_utf8(wxString wx_string):
return wx_string.ToUTF8()
# Function to convert a wxString to a Python unicode string.
cdef inline object to_python_unicode(wxString wx_string):
# Since the wxString.ToUTF8() method returns a const char*, we'd have to try
# and cast it if we wanted to do it all in here. I've tried this and can't
# seem to get it to work. But calling the to_python_utf8() function
# means Cython handles the conversions and it all just works. Plus, since
# they are defined as inline functions this may well be simplified down when
# compiled.
byte_string = to_python_utf8(wx_string)
# Decode it to a unicode string and we're done.
return byte_string.decode('UTF-8')
Simply put this in a .pxd file (personally, I put it in a subdirectory as
`wx/string.pxd` \- make sure you also create an `wx/__init__.pdx` if you
choose to do the same). Then `cimport` it and call the functions as
appropriate:
cimport wx.string
wx_string = wx.string.from_python(python_string)
python_string = wx.string.to_python_unicode(wx_string)
|
Unknown screen output of manually installed Python 2.7
Question: I installed Python 2.7 today using:
./configure --prefix=/home/zhanwu/local --enable-shared --enable-profiling --with-pydebug
make install
Then I keep getting something like "[37745 refs]" on screen after each
function call:
[zhanwu@cluster ~]$ ~/local/bin/python
Python 2.7.1 (r271:86832, Jun 16 2011, 17:45:05)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
[37745 refs]
>>> print 'test'
test
[37745 refs]
>>> sys.exit()
[18048 refs]
[zhanwu@cluster ~]$
What does those numbers mean? Anything wrong here and can I get rid of them?
uname -a result:
[zhanwu@cluster ~]$ uname -a
Linux cluster.xxx.xxx.xxx 2.6.18-128.1.14.el5 #1 SMP Wed Jun 17 06:38:05 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux
Answer: You get these because you configured the build with `--with-pydebug`. They
denote the number of references Python is currently keeping track of. To get
rid of them, configure without `--with-pydebug`.
|
How to insert DTD DOCTYPE content when using SAX to generate XML output in Python
Question: I am trying to generate a large XML file using python(actually jython)
xml.sax.saxutils.XMLGenerator. I would like to include DTD information but I
could not figure out how to pass the DTD string to SAX. Here is the sample SAX
writer class:
from xml.sax.saxutils import XMLGenerator
class xml_writer:
def __init__(self, output, encoding):
"""
an XML writer object that generate xml output to a file
"""
xmlwriter = XMLGenerator(output, encoding)
xmlwriter.startDocument()
self._writer = xmlwriter
self._output = output
self._encoding = encoding
self.attr_vals = {}
self.attr_qnames = {}
return
def start_elem(self, name):
name = unicode(name)
attrs = AttributesNSImpl(self.attr_vals, self.attr_qnames)
self._writer.startElementNS((None, name), name, attrs)
self._writer._out.write('\n')
self.attr_qnames = {}
self.attr_vals = {}
def end_elem(self, name):
name = unicode(name)
self._writer.endElementNS((None, name), name)
self._writer._out.write('\n')
def setAttribute(self, aname, value):
aname = unicode(aname)
value = unicode(value)
self.attr_vals[(None, aname)] = value
self.attr_qnames[(None, aname)] = aname
def close(self):
"""
Clean up
"""
self._writer.endDocument()
return
Appreciate your help.
Answer: You could subclass `XMLGenerator` and add a `write()` method. Here is an
example:
import sys
from xml.sax.saxutils import XMLGenerator
class MyXMLGenerator(XMLGenerator):
def __init__(self, out=sys.stdout, encoding="UTF-8"):
XMLGenerator.__init__(self, out, encoding)
self.out = out
def write (self,s):
self.out.write(s)
def writexml(out):
xmlwriter = MyXMLGenerator(out)
xmlwriter.startDocument()
xmlwriter.write("<!DOCTYPE test SYSTEM 'test.dtd'>\n")
xmlwriter.startElement('test', {"a": "1"})
xmlwriter.characters('abc123')
xmlwriter.endElement('test')
xmlwriter.endDocument()
if __name__ == '__main__':
writexml(out=open("out.xml", "w"))
Resulting output in **out.xml** :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE test SYSTEM 'test.dtd'>
<test a="1">abc123</test>
|
Xml parsing with Python using recursion. Problem with return value
Question: I am somewhat new to Python and programming in general so I apologize. By the
way, thanks in advance.
I am parsing an xml document (kml specifically which is used in Google Earth)
using Python 2.5, cElementTree and expat. I am trying to pull out all the text
from the 'name', 'description' and 'coordinates' nodes inside each 'placemark'
node for each geometry type (i.e. polylines, polygon, point), but I want to
keep the geometry types separate. For example, I want only the
'name','description', and 'coordinates' text for every placemark that is part
of a 'polygon' (i.e. it has a 'polygon' node). I will need to do this for
'polylines' and 'points' also. I have figured out a way to do this, but the
code is long a verbose and specific to each geometry type, which leads me to
my question.
Ideally, I would like to use the same code for each geometry type, but the
problem is that each geometry type has a different node structure (i.e.
different node names and number of nested nodes). So for proof of concept I
thought this would be a good opportunity to use/learn recursion to drill down
the node tree of 'placemark' node and get the information I was looking for. I
have looked at the many posts on Python recursion and am still having problems
with implementing the solutions provided.
The sample xml for a 'placemark' node is:
<Placemark>
<name>testPolygon</name>
<description>polygon text</description>
<styleUrl>#msn_ylw-pushpin</styleUrl>
<Polygon>
<tessellate>1</tessellate>
<outerBoundaryIs>
<LinearRing>
<coordinates>
-81.4065,31.5072,0 -81.41269,31.45992,0 -81.34490,31.459696,0
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
The recursion function I am using is:
def getCoords( child, searchNode ):
# Get children of node
children = child.getchildren()
# If node has one or more child
if len( children ) >= 1 :
# Loop through all the children
for child in children:
# call to recursion function
getCoords( child, searchNode )
# If does not have children and is the 'searchNode'
elif len( children ) == 0 and child.tag == searchNode:
# Return the text inside the node. This is where it is not working
# Other posts recommended returning the function like
# return getCoords(child, searchNode), but I am getting an unending loop
return child.text
# Do nothing if node doesn't have children and does not match 'searchNode'
else:
print 'node does not have children and is not what we are looking for'
I am calling the recursion function like:
searchNode = 'coordinates'
# loop through all 'Placemark nodes' in document
for mark in placemark:
# Get children of 'Placemark' node
children = mark.getchildren()
# Loop through children nodes
for child in children:
# if a 'Polygon' node is found
if child.tag == 'Polygon':
# call recursion function
getCoords( child, searchNode)
I realize, at least, part of my problem is the return value. Other posts
recommended returning the function, which I interpreted to be 'return
getCoords(child, searchNode), but I am getting an unending loop. Also, I
realize this could be posted on the GIS site, but I think this is more of a
general programming question. Any ideas?
Answer: With recursion you want to pay attention to your base cases, and your
recursive cases. Whatever your base cases happen to be, if you expect to be
able to collect information from your recursion, they have to return data that
your recursive cases can (and more importantly do) use. Similarly you need to
make sure the data your recursive cases return can be used by each other.
First identify your base and recursive cases. The base cases are the "leaf"
nodes, with no children. In a base case you want to just return some data, and
not call the recursive function again. This is what allows you to get "back up
the stack" as they say, and prevent infinite recursion. The recursive cases
will require you to save the data collected from a series of recursive calls,
which is almost what you're doing in your `for` loop.
I noticed that you have
# Recursive case: node has one or more child
if len( children ) >= 1 :
# Loop through all the children
for child in children:
# call to recursion function
getCoords( child, searchNode )
but what are you doing with the results of your getCoords calls?
You either want to save the results in some sort of a data structure which you
can return at the end of your for loop, or if you're not interested in saving
the results themselves, just print your base case 1 ( successful search ) when
you reach it instead of returning it. Because now your base case 1 is just
returning up the stack to an instance that isn't doing anything with the
result! So try:
# If node has one or more child
if len( children ) >= 1 :
# Data structure for your results
coords = []
# Loop through all the children
for child in children:
# call to recursion function
result = getCoords( child, searchNode )
# Add your new results together
coords.extend(result)
# Give the next instance up the stack your results!
return coords
Now since your results are in a list and you're using the `extend()` method
you've got to make your base cases return lists as well!
# Base case 1: does not have children and is the 'searchNode'
elif len( children ) == 0 and child.tag == searchNode:
# Return the text from the node, inside a list
return [child.text]
# Base case 2: doesn't have children and does not match 'searchNode'
else:
# Return empty list so your extend() function knows what to do with the result
return []
This should just give you a single list in the end, which you'll probably want
to store in a variable. I've just printed the results here:
searchNode = 'coordinates'
# loop through all 'Placemark nodes' in document
for mark in placemark:
# Get children of 'Placemark' node
children = mark.getchildren()
# I imagine that getchildren() might return None, so check it
# otherwise you'll get an error when trying to iterate on it
if children:
# Loop through children nodes
for child in children:
# if a 'Polygon' node is found
if child.tag == 'Polygon':
# call recursion function and print (or save) result
print getCoords( child, searchNode)
|
Adding context menu option through Python
Question: I'm trying to make a small Python script that is executed by clicking an
option in a file's context menu. It would execute something like
"path_to_script %L", where %L is (I think) the location of the file the user
has right-clicked. I know I have to add something to the registry for that
option to appear, but _winreg is getting confusing. What do I have to do to
add a registry entry (through Python) so my script can be called like that?
Answer: I dont know how you can remove from registry (probably manually or _winreg)
but you can follow a way like that per your custom python script to
registration to windows.
**registerOne.reg**
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\*\shell\One]
[HKEY_CLASSES_ROOT\*\shell\One\command]
@="python.exe one.py \"%1\""
**one.py**
def registerScriptToContextMenu ():
# http://support.microsoft.com/kb/310516
cmdLine = 'regedit.exe registerOne.reg'
import os
os.system(cmdLine)
def one_main (*args):
pass
|
Iron Python - No module named "os"
Question: I have been trying to debug this sample code, but I am having trouble.
**Here is the code:**
import System
import get_events_devices
from System.Windows.Forms import *
from System.ComponentModel import *
from System.Drawing import *
from clr import *
clr.AddReference("IronPython")
class Check: # namespace
class Form1(System.Windows.Forms.Form):
"""type(_label1) == System.Windows.Forms.Label, type(_button1) == System.Windows.Forms.Button"""
__slots__ = ['_label1', '_button1']
def __init__(self):
self.InitializeComponent()
@accepts(Self(), bool)
@returns(None)
def Dispose(self, disposing):
super(type(self), self).Dispose(disposing)
@returns(None)
def InitializeComponent(self):
self._button1 = System.Windows.Forms.Button()
self._label1 = System.Windows.Forms.Label()
self.SuspendLayout()
#
# button1
#
self._button1.Location = System.Drawing.Point(58, 61)
self._button1.Name = 'button1'
self._button1.Size = System.Drawing.Size(75, 23)
self._button1.TabIndex = 0
self._button1.Text = 'Click'
self._button1.UseVisualStyleBackColor = True
self._button1.Click += self._button1_Click
#
# label1
#
self._label1.AutoSize = True
self._label1.Location = System.Drawing.Point(190, 70)
self._label1.Name = 'label1'
self._label1.Size = System.Drawing.Size(0, 13)
self._label1.TabIndex = 1
#
# Form1
#
self.ClientSize = System.Drawing.Size(292, 273)
self.Controls.Add(self._label1)
self.Controls.Add(self._button1)
self.Name = 'Form1'
self.Text = 'Form1'
self.ResumeLayout(False)
self.PerformLayout()
@accepts(Self(), System.Object, System.EventArgs)
@returns(None)
def _button1_Click(self, sender, e):
# Snippet Statement
pass
# End Snippet Statement
self._label1.Text = 'mohsin'
get_events_devices.units()
I have just added optparse.py, get_events_devices.py, and iron python.dll.
From where I get ironpython_module.dll as I have install Iron Python I am not
getting this .dll?
Any ideas?
Answer: If you are running and debugging the Python code using Visual Studio via the
IronPython tools, it might be that your `sys.path` does not contain a
reference to all of the IronPython modules such as `os`.
In your code, try adding the following to indicate the install directory of
IronPython:
import sys
sys.path.append(r"C:\Program Files\IronPython 2.7\Lib")
The above is a workaround for [this reported
bug](http://ironpython.codeplex.com/workitem/30348).
|
Python mysqldb: Library not loaded: libmysqlclient.18.dylib
Question: I just compiled and installed mysqldb for python 2.7 on my mac os 10.6. I
created a simple test file that imports
import MySQLdb as mysql
Firstly, this command is red underlined and the info tells me "Unresolved
import". Then I tried to run the following simple python code
import MySQLdb as mysql
def main():
conn = mysql.connect( charset="utf8", use_unicode=True, host="localhost",user="root", passwd="",db="" )
if __name__ == '__main__'():
main()
When executing it I get the following error message
Traceback (most recent call last):
File "/path/to/project/Python/src/cvdv/TestMySQLdb.py", line 4, in <module>
import MySQLdb as mysql
File "build/bdist.macosx-10.6-intel/egg/MySQLdb/__init__.py", line 19, in <module>
\namespace cvdv
File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/toom/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
Referenced from: /Users/toom/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so
Reason: image not found
What might be the solution to my problem?
EDIT: Actually I found out that the library lies in /usr/local/mysql/lib. So I
need to tell my pydev eclipse version where to find it. Where do I set this?
Answer: I solved the problem by creating a symbolic link to the library. I.e.
The actual library resides in
/usr/local/mysql/lib
And then I created a symbolic link in
/usr/lib
Using the command:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
so that I have the following mapping:
ls -l libmysqlclient.18.dylib
lrwxr-xr-x 1 root wheel 44 16 Jul 14:01 libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib
That was it. After that everything worked fine.
EDIT:
Notice, to do this in El Capitan mac os release, you need disable SIP. Here is
hint how do it in final release:
<http://apple.stackexchange.com/a/208481/90910> .
|
Problem with creating an object in neo4j
Question: I am using the django integration for neo4j and I'm getting the following
traceback when I'm trying to create a node.
I do have JPype installed and it can be imported.
p = Person.objects.create(first_name='omer', last_name='katz')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 138, in create
return self.get_query_set().create(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/model/django_model/__init__.py", line 362, in create
obj.save(force_insert=True)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 460, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_util.py", line 47, in __get__
method, graphdb = self.descr_get(obj, cls)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_util.py", line 41, in descr_get
graphdb = self.accessor.__get__(obj, cls)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/model/django_model/__init__.py", line 58, in __get__
return DjangoNeo.neo
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/model/django_model/__init__.py", line 124, in neo
return self.__setup_neo()
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/model/django_model/__init__.py", line 136, in __setup_neo
self.__neo = NeoService(resource_uri, **options)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/__init__.py", line 522, in __new__
neo = core.load_neo(resource_uri, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_core.py", line 180, in load_neo
backend.initialize(**parameters)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 61, in initialize
raise ImportError("No applicable backend found.")
ImportError: No applicable backend found.
EDIT:
As requested here are my neo4j settings:
NEO4J_RESOURCE_URI = '/var/neo4j/neo4django'
# NEO4J_RESOURCE_URI should be the path to where
# you want to store the Neo4j database.
NEO4J_OPTIONS = {
# this is optional and can be used to specify
# extra startup parameters for Neo4j, such as
# the classpath to load Neo4j from.
}
EDIT:
After following thobe's suggestion I get the following when I try to import my
own models:
ERROR:root:Importing native backends failed.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 51, in initialize
embedded, remote = implementation.initialize(classpath, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/reflection.py", line 44, in initialize
jvm = jpype.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_core.py", line 96, in getDefaultJVMPath
return _linux.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 36, in getDefaultJVMPath
jvm = _getJVMFromJavaHome()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 55, in _getJVMFromJavaHome
if os.path.exists(java_home+"/bin/javac") :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
ERROR:root:Importing native backends failed.
Traceback (most recent call last):
FERROR:root:Importing native backends failed.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 51, in initialize
embedded, remote = implementation.initialize(classpath, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/reflection.py", line 44, in initialize
jvm = jpype.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_core.py", line 96, in getDefaultJVMPath
return _linux.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 36, in getDefaultJVMPath
jvm = _getJVMFromJavaHome()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 55, in _getJVMFromJavaHome
if os.path.exists(java_home+"/bin/javac") :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
ERROR:root:Importing native backends failed.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 51, in initialize
embedded, remote = implementation.initialize(classpath, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/reflection.py", line 44, in initialize
jvm = jpype.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_core.py", line 96, in getDefaultJVMPath
return _linux.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 36, in getDefaultJVMPath
jvm = _getJVMFromJavaHome()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 55, in _getJVMFromJavaHome
if os.path.exists(java_home+"/bin/javac") :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
ERROR:root:Importing native backends failed.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 51, in initialize
embedded, remote = implementation.initialize(classpath, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/reflection.py", line 44, in initialize
jvm = jpype.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_core.py", line 96, in getDefaultJVMPath
return _linux.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 36, in getDefaultJVMPath
jvm = _getJVMFromJavaHome()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 55, in _getJVMFromJavaHome
if os.path.exists(java_home+"/bin/javac") :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
ERROR:root:Importing native backends failed.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 51, in initialize
embedded, remote = implementation.initialize(classpath, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/reflection.py", line 44, in initialize
jvm = jpype.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_core.py", line 96, in getDefaultJVMPath
return _linux.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 36, in getDefaultJVMPath
jvm = _getJVMFromJavaHome()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 55, in _getJVMFromJavaHome
if os.path.exists(java_home+"/bin/javac") :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
ERROR:root:Importing native backends failed.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 51, in initialize
embedded, remote = implementation.initialize(classpath, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/reflection.py", line 44, in initialize
jvm = jpype.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_core.py", line 96, in getDefaultJVMPath
return _linux.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 36, in getDefaultJVMPath
jvm = _getJVMFromJavaHome()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 55, in _getJVMFromJavaHome
if os.path.exists(java_home+"/bin/javac") :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
ile "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 51, in initialize
embedded, remote = implementation.initialize(classpath, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/reflection.py", line 44, in initialize
jvm = jpype.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_core.py", line 96, in getDefaultJVMPath
return _linux.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 36, in getDefaultJVMPath
jvm = _getJVMFromJavaHome()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 55, in _getJVMFromJavaHome
if os.path.exists(java_home+"/bin/javac") :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
ERROR:root:Importing native backends failed.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 51, in initialize
embedded, remote = implementation.initialize(classpath, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/reflection.py", line 44, in initialize
jvm = jpype.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_core.py", line 96, in getDefaultJVMPath
return _linux.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 36, in getDefaultJVMPath
jvm = _getJVMFromJavaHome()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 55, in _getJVMFromJavaHome
if os.path.exists(java_home+"/bin/javac") :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
ERROR:root:Importing native backends failed.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 51, in initialize
embedded, remote = implementation.initialize(classpath, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/reflection.py", line 44, in initialize
jvm = jpype.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_core.py", line 96, in getDefaultJVMPath
return _linux.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 36, in getDefaultJVMPath
jvm = _getJVMFromJavaHome()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 55, in _getJVMFromJavaHome
if os.path.exists(java_home+"/bin/javac") :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
ERROR:root:Importing native backends failed.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/__init__.py", line 51, in initialize
embedded, remote = implementation.initialize(classpath, params)
File "/usr/local/lib/python2.7/dist-packages/Neo4j.py-0.1_SNAPSHOT-py2.7.egg/neo4j/_backend/reflection.py", line 44, in initialize
jvm = jpype.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_core.py", line 96, in getDefaultJVMPath
return _linux.getDefaultJVMPath()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 36, in getDefaultJVMPath
jvm = _getJVMFromJavaHome()
File "/usr/local/lib/python2.7/dist-packages/jpype/_linux.py", line 55, in _getJVMFromJavaHome
if os.path.exists(java_home+"/bin/javac") :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Answer: You can get more verbose information about why the backend couldn't be found
by adding this to NEO4J_OPTIONS:
NEO4J_OPTIONS = {
log: True,
}
The output from that logging will make it easier to diagnose the actual issue
and suggest a fix.
|
Quick and easy: trayicon with python?
Question: I'd just need a quick example on how to easily put an icon with python on my
systray. This means: I run the program, no window shows up, just a tray icon
(I've got a png file) shows up in the systray and when I right-click on it a
menu appears with some options (and when I click on an option, a function is
run). Is that possible? I don't need any window at all...
Examples / code snippets are REALLY appreciated! :D
Answer: ## For Windows & Gnome
Here ya go! wxPython is the bomb. Adapted from the source of my [Feed
Notifier](http://www.feednotifier.com/) application.
import wx
TRAY_TOOLTIP = 'System Tray Demo'
TRAY_ICON = 'icon.png'
def create_menu_item(menu, label, func):
item = wx.MenuItem(menu, -1, label)
menu.Bind(wx.EVT_MENU, func, id=item.GetId())
menu.AppendItem(item)
return item
class TaskBarIcon(wx.TaskBarIcon):
def __init__(self):
super(TaskBarIcon, self).__init__()
self.set_icon(TRAY_ICON)
self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)
def CreatePopupMenu(self):
menu = wx.Menu()
create_menu_item(menu, 'Say Hello', self.on_hello)
menu.AppendSeparator()
create_menu_item(menu, 'Exit', self.on_exit)
return menu
def set_icon(self, path):
icon = wx.IconFromBitmap(wx.Bitmap(path))
self.SetIcon(icon, TRAY_TOOLTIP)
def on_left_down(self, event):
print 'Tray icon was left-clicked.'
def on_hello(self, event):
print 'Hello, world!'
def on_exit(self, event):
wx.CallAfter(self.Destroy)
def main():
app = wx.PySimpleApp()
TaskBarIcon()
app.MainLoop()
if __name__ == '__main__':
main()
|
Pydev: Where do I have to add the path for an external lib (usr/local/mysql/lib/libmysqlclient)?
Question: I use mysqldb and pydev eclipse. I successfully compiled mysqldb 1.23 and now
I would like to import it. mysqldb 1.23 needs the library
libmysqlclient.18.dylib which lies in my case in /usr/local/mysql/lib. So when
I start my test program in eclipse it crashes since it does not find the
correct library. Therefore I need to tell eclipse where to find the libs.
How do I do this my case?
What and where in eclipse/pydev do I have to tell it that
libmysqlclient.18.dylib resides in the above directoy?
The error message I get
ImportError: dlopen(/path/to/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
Referenced from: /path/to/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so
Reason: image not found
Answer: In your project's properties, (accessible from `Project > Properties...`),
click the `PyDev - PYTHONPATH` item. A view of your PYTHONPATH should be
visible. Click the `External Libraries` tab and add your library. The next
time you run, it should import correctly.
|
Split PDF files in python - ValueError: invalid literal for int() with base 10: '' "
Question: I am trying to split a huge pdf file into several small pdfs usinf pyPdf. I
was trying with this oversimplified code:
from pyPdf import PdfFileWriter, PdfFileReader
inputpdf = PdfFileReader(file("document.pdf", "rb"))
for i in xrange(inputpdf.numPages):
output = PdfFileWriter()
output.addPage(inputpdf.getPage(i))
outputStream = file("document-page%s.pdf" % i, "wb")
output.write(outputStream)
outputStream.close()
but I got the follow error message:
Traceback (most recent call last):
File "./hltShortSummary.py", line 24, in <module>
for i in xrange(inputpdf.numPages):
File "/usr/lib/pymodules/python2.7/pyPdf/pdf.py", line 342, in <lambda>
numPages = property(lambda self: self.getNumPages(), None, None)
File "/usr/lib/pymodules/python2.7/pyPdf/pdf.py", line 334, in getNumPages
self._flatten()
File "/usr/lib/pymodules/python2.7/pyPdf/pdf.py", line 500, in _flatten
pages = catalog["/Pages"].getObject()
File "/usr/lib/pymodules/python2.7/pyPdf/generic.py", line 466, in __getitem__
return dict.__getitem__(self, key).getObject()
File "/usr/lib/pymodules/python2.7/pyPdf/generic.py", line 165, in getObject
return self.pdf.getObject(self).getObject()
File "/usr/lib/pymodules/python2.7/pyPdf/pdf.py", line 549, in getObject
retval = readObject(self.stream, self)
File "/usr/lib/pymodules/python2.7/pyPdf/generic.py", line 67, in readObject
return DictionaryObject.readFromStream(stream, pdf)
File "/usr/lib/pymodules/python2.7/pyPdf/generic.py", line 517, in readFromStream
value = readObject(stream, pdf)
File "/usr/lib/pymodules/python2.7/pyPdf/generic.py", line 58, in readObject
return ArrayObject.readFromStream(stream, pdf)
File "/usr/lib/pymodules/python2.7/pyPdf/generic.py", line 153, in readFromStream
arr.append(readObject(stream, pdf))
File "/usr/lib/pymodules/python2.7/pyPdf/generic.py", line 87, in readObject
return NumberObject.readFromStream(stream)
File "/usr/lib/pymodules/python2.7/pyPdf/generic.py", line 232, in readFromStream
return NumberObject(name)
ValueError: invalid literal for int() with base 10: ''
any ideas???
Answer: I think this is a bug in pypdf. Check out the source
[here](https://bitbucket.org/micktwomey/pypdf/src/26ab3506f24b/pyPdf/generic.py).
`NumberObject.readFromStream` expects an integer-like string, and isn't
getting one. Probably the pdf in question is malformed in some unexpected way.
|
Very basic Python question (strings, formats and escapes)
Question: I am starting to learn Python with an online guide, and I just did an exercise
that required me to write this script:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close()
I got it to run fine, but then the guide said: "There's too much repetition in
this file. Use strings, formats, and escapes to print out line1, line2, and
line3 with just one target.write() command instead of 6."
I'm not sure how to do this. Can anyone help? Thanks!
Answer: The guide is suggesting creating a single string and writing it out rather
than calling`write()` six time which seems like good advice.
You've got three options.
You could concatentate the strings together like this:
line1 + "\n" + line2 + "\n" + line3 + "\n"
or like this:
"\n".join(line1,line2,line3) + "\n"
You could use old [string
formatting](http://docs.python.org/library/stdtypes.html#string-formatting) to
do it:
"%s\n%s\n%s\n" % (line1,line2,line3)
Finally, you could use the [newer string
formatting](http://docs.python.org/library/string.html#formatstrings) used in
Python 3 and also available from Python 2.6:
"{0}\n{1}\n{2}\n".format(line1,line2,line3)
I'd recommend using the last method because it's the most powerful when you
get the hang of it, which will give you:
target.write("{0}\n{1}\n{2}\n".format(line1,line2,line3))
|
Python SocketServer.TCPServer request
Question: I've been playing around with Python's SocketServer:
#!/usr/bin/python
import SocketServer
class EchoHandler(SocketServer.BaseRequestHandler):
def handle(self):
data=self.request.recv(1024)
self.request.send(data)
HOST, PORT = "localhost", 9999
server = SocketServer.TCPServer((HOST, PORT), TCPEchoServer)
server.serve_forever()
From reading the source, I know that `RequestHandler.__init__()` receives
`request` as a parameter and keeps a reference to it in `self.request`.
Where can I find the specifications for the `request` object?
Answer: In the [documentation of
`RequestHandler.handle`](http://docs.python.org/library/socketserver.html#SocketServer.RequestHandler.handle).
|
Something wrong with wtforms FieldList && validation
Question: Something wrong with wtforms FieldList && validation... It should say that
field must have Int value, not This field is required Why f.data has [None, 2,
None] value, not ['def', 2, 'abc'] ?
from webob.multidict import MultiDict
from wtforms import Form
from wtforms import FieldList, IntegerField
from wtforms import validators
class SearchForm(Form):
locality_id = FieldList(IntegerField(u'Locality', [validators.Required()]))
d = MultiDict([('locality_id-0', 'def'), ('locality_id-1', 2), ('locality_id-2', 'abc')])
f = SearchForm(d)
print f.validate()
print f.errors
print f.data
print f.locality_id.data
% python form_test.py
False
{'locality_id': [[u'This field is required.'], [u'This field is required.']]}
{'locality_id': [None, 2, None]}
[None, 2, None]
Answer: It looks like there is a `try... except` block in the `IntegerField` ancestry
which will place all non ints into the `process_errors` property and that the
class is specifically prevented from allowing you to have data populated with
anything but valid data. I believe you can still get the values you seek in
the `raw_data` property, however.
|
Google app engine(python) ImportError: No module named oauth2 in google app engine
Question: I have used python twitter script from <http://code.google.com/p/python-
twitter/> and oauth2 from <https://github.com/simplegeo/python-oauth2>
Answer: To import third-party modules in App Engine, they need to be included (or
symlinked) in the project directory. Your regular PYTHONPATH isn't checked, as
modules installed on your local machine most likely won't be available on the
production servers.
|
Django.db import error
Question:
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 14, in <module>
if not settings.DATABASES:
File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
How can I set the environment variable?
Answer: ["Standalone Django
scripts"](http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/)
|
Python exception ordering
Question: Just curious, why does the following code
import sys
class F(Exception):
sys.stderr.write('Inside exception\n')
sys.stderr.flush()
pass
sys.stderr.write('Before Exception\n')
sys.stderr.flush()
try:
raise F
except F:
pass
output:
Inside exception
Before Exception
and not:
Before exception
Inside Exception
Answer: You're printing in the class, not its initialization block . Try running this
import sys
class F(Exception):
sys.stderr.write('Inside exception\n')
sys.stderr.flush()
pass
alone. i.e., it's not running when you call `raise F`. Try this instead
import sys
class F(Exception):
def __init__():
sys.stderr.write('Inside exception\n')
sys.stderr.flush()
raise new F()
|
Python query: iterating through log file
Question: Please can someone help me solve the following query? I have a log file with
thousands of lines like the following:-
jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 recv: 1 timestamp: 00:00:02,217
jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 ack: 13 timestamp: 00:00:04,537
jarid: 462c6d11-9151-11e0-a72c-00238bbdc9e7 recv: 1 timestamp: 00:00:08,018
jarid: 462c6d11-9151-11e0-a72c-00238bbdc9e7 nack: 14 timestamp: 00:00:10,338
I would like to write a python script to iterate through this file and based
on the jarid (the second field in the log file) to get the timestamp from each
line where the jarid is found and print them on the same line. So for example,
for the following two lines:-
jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 recv: 1 timestamp: 00:00:02,217
jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 ack: 13 timestamp: 00:00:04,537
I would get the following output:-
jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 recv: 00:00:02,217 ack: 00:00:04,537
I think the best way to accomplish this is with a dictionary (or maybe not!,
please comment). I have written the following script, which is somewhat
working, but it is not giving me the desired output:-
#!/opt/SP/bin/python
log = file(/opt/SP/logs/generic.log, "r")
filecontent = log.xreadlines()
storage = {}
for line in filecontent:
line = line.strip()
jarid, JARID, status, STATUS, timestamp, TIME = line.split(" ")
if JARID not in storage:
storage[JARID] = {}
if STATUS not in storage[JARID]:
storage[JARID][STATUS] = {}
if TIME not in storage[JARID][STATUS]:
storage[JARID][STATUS][TIME] = {}
jarids = storage.keys()
jarids.sort()
for JARID in jarids:
stats = storage[JARID].keys()
stats.sort()
for STATUS in stats:
times = storage[JARID][STATUS].keys()
times.sort()
for TIME in times:
all = storage[JARID][STATUS][TIME].keys()
all.sort()
for JARID in jarids:
if "1" in storage[JARID].keys() and "13" in storage[JARID].keys():
print "MSG: %s, RECV: %s, ACK: %s" % (JARID, storage[JARID]["1"], storage[JARID]["13"])
else:
if "1" in storage[JARID].keys() and "14" in storage[JARID].keys():
print "MSG: %s, RECV: %s, NACK: %s" % (JARID, storage[JARID]["1"], storage[JARID]["14"])
When I run this script, I am getting the following output:-
MSG: 7e5ae720-9151-11e0-eff2-00238bce4216, RECV: {'00:00:02,217': {}}, ACK: {'00:00:04,537': {}}
Please note that I am still learning python and that my scripting skills are
not all that!
Please, can you help me figure out how to get the desired output as I wrote
above?
Answer: Based on JBernardo's answer, but using defaultdict instead of setdefault. You
can print it exactly the same way, so I won't copy that code here
from collections import defaultdict
log = ['jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 recv: 1 timestamp: 00:00:02,217',
'jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 ack: 13 timestamp: 00:00:04,537',
'jarid: 462c6d11-9151-11e0-a72c-00238bbdc9e7 recv: 1 timestamp: 00:00:08,018',
'jarid: 462c6d11-9151-11e0-a72c-00238bbdc9e7 nack: 14 timestamp: 00:00:10,338']
d = defaultdict(dict)
for i in (line.split() for line in log):
d[i[1]][i[2]] = i[-1]
You can also unpack into meaningful names. for example
for label1, jarid, jartype, x, label2, timestamp in (line.split() for line in log):
d[jarid][jartype] = timestamp
|
Any way of getting PyDoc into Jira Confluence
Question: I'm using PyDoc to generate documentation from my Python code and I'm using
Jira's Confluence plugin to manage documentation. Is there any way to
generating PyDoc documentation and putting it into Confluence?
Googling didn't yield too many results.
Thanks everyone
Answer: You can try something like this:
from pydoc import *
import io
d = HTMLDoc()
content = d.docmodule(sys.modules["mymodule"])
f = io.open('./out.html', 'w')
f.write(unicode(content))
f.close()
You now have an HTML file containing the pydoc info. The next trick is to get
it into Confluence so that it looks nice. I have so far tried importing it
into Microsoft Word as an .rtf, then cut-and-paste into Confluence.
|
Error while trying to setup a Jython interpreter
Question: I wanted to boot up a Jython interpreter inside the plugin, then execute files
inside the interpreter.
package com.jakob.jython;
import org.bukkit.plugin.java.JavaPlugin;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
public class EmbeddedJython extends JavaPlugin {
private static final Logger log = Logger.getLogger("Minecraft");
private PythonInterpreter interpreter;
private PyObject plugin;
public void onEnable() {
log.info("JythonTest enabled");
this.interpreter = new PythonInterpreter();
log.info("Jython interpreter fired up and cooking on gas");
log.info("Loading Python Plugin");
InputStream pythonScript = EmbeddedJython.class.getResourceAsStream("MyPlugin.py");
this.interpreter.execfile(pythonScript, "MyPlugin.py");
log.info("Getting plg method.");
this.plugin = this.interpreter.get("plg");
log.info("Plugin loaded");
log.info(plugin.invoke("onEnable").toString());
}
public void onDisable() {
log.info(plugin.invoke("onDisable").toString());
log.info("Jython disabled");
}
}
In other tests I can get the Jython interpreter up and running strings I hand
it but when I use the above snippet I end up with an exception that looks
something like this:
11:03:38 [SEVERE] Error occurred while enabling JythonTest v0.12 (Is it up to da
te?): null
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at org.python.core.ParserFacade.adjustForBOM(ParserFacade.java:371)
at org.python.core.ParserFacade.prepBufReader(ParserFacade.java:298)
at org.python.core.ParserFacade.prepBufReader(ParserFacade.java:288)
at org.python.core.ParserFacade.parse(ParserFacade.java:183)
at org.python.core.Py.compile_flags(Py.java:1717)
at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:235
)
at com.jakob.jython.EmbeddedJython.onEnable(EmbeddedJython.java:26)
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:125)
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader
.java:750)
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManage
r.java:253)
at org.bukkit.craftbukkit.CraftServer.loadPlugin(CraftServer.java:132)
at org.bukkit.craftbukkit.CraftServer.loadPlugins(CraftServer.java:110)
at net.minecraft.server.MinecraftServer.e(MinecraftServer.java:218)
at net.minecraft.server.MinecraftServer.a(MinecraftServer.java:205)
at net.minecraft.server.MinecraftServer.init(MinecraftServer.java:145)
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:265)
at net.minecraft.server.ThreadServerApplication.run(SourceFile:394)
java.io.IOException: java.io.IOException: Stream closed
at org.python.core.PyException.fillInStackTrace(PyException.java:70)
at java.lang.Throwable.<init>(Throwable.java:181)
at java.lang.Exception.<init>(Unknown Source)
at java.lang.RuntimeException.<init>(Unknown Source)
at org.python.core.PyException.<init>(PyException.java:46)
at org.python.core.PyException.<init>(PyException.java:43)
at org.python.core.Py.JavaError(Py.java:481)
at org.python.core.ParserFacade.fixParseError(ParserFacade.java:104)
at org.python.core.ParserFacade.parse(ParserFacade.java:186)
at org.python.core.Py.compile_flags(Py.java:1717)
at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:235
)
at com.jakob.jython.EmbeddedJython.onEnable(EmbeddedJython.java:26)
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:125)
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader
.java:750)
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManage
r.java:253)
at org.bukkit.craftbukkit.CraftServer.loadPlugin(CraftServer.java:132)
at org.bukkit.craftbukkit.CraftServer.loadPlugins(CraftServer.java:110)
at net.minecraft.server.MinecraftServer.e(MinecraftServer.java:218)
at net.minecraft.server.MinecraftServer.a(MinecraftServer.java:205)
at net.minecraft.server.MinecraftServer.init(MinecraftServer.java:145)
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:265)
at net.minecraft.server.ThreadServerApplication.run(SourceFile:394)
Caused by: java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at org.python.core.ParserFacade.adjustForBOM(ParserFacade.java:371)
at org.python.core.ParserFacade.prepBufReader(ParserFacade.java:298)
at org.python.core.ParserFacade.prepBufReader(ParserFacade.java:288)
at org.python.core.ParserFacade.parse(ParserFacade.java:183)
... 13 more
Could it be I'm using `execfile` wrong? Or is it an error or something I'm
missing in how `InputStream` works?
Answer: Are you sure that `EmbeddedJython.class.getResourceAsStream("MyPlugin.py");`
is finding the resource?
If it can't find the resource, `getResourceAsStream` will return a `null`, and
it is possible that the Jython interpreter will treat that as an empty
(closed) stream.
Your application should probably check this, rather than assuming that
`getResourceAsStream` has succeeded.
* * *
> If I `private File pythonFile = new File('MyScirpt.py');` and then hand
> `getResourceAsStream(pythonFile.getAbsolutePath());`
That won't work. The `getResourceAsStream` method looks for resources on the
classloader's classpath, and expects a path that can be resolved relative to
some entry on the classpath.
You probably want to do this:
private File pythonFile = new File('MyScirpt.py');
InputStream is = new FileInputStream(pythonFile);
and pass the `is` to the interpreter. You also need to arrange that the stream
is **always** closed when the interpreter has finished ... by whatever
mechanism that happens.
|
Python HTTPConnection file send with httplib, retrieving progress
Question: In a django app I'm using a third-party Python
[script](http://wiki.blip.tv/index.php/REST_Upload_Python_Script) to allow
users to upload files to blip.tv through httplib.HTTPConnection.send on an EC2
instance. Since these files are generally large I will use a message queue to
process the upload asynchronously (RabbitMQ/Celery), and give feedback on the
progress to the user in the frontend.
The httpconnection and send are done in this part of the script:
host, selector = urlparts = urlparse.urlsplit(url)[1:3]
h = httplib.HTTPConnection(host)
h.putrequest("POST", selector)
h.putheader("content-type", content_type)
h.putheader("content-length", len(data))
h.endheaders()
h.send(data)
response = h.getresponse()
return response.status, response.reason, response.read()
The getresponse() is returned after the file transfer is completed, how do I
write out the progress (assuming something with stdout.write) so I can write
this value to the cache framework for display (djangosnippets 678/679)?
Alternatively if there is a better practice for this, I'm all ears!
**EDIT:**
Since I've gone with urllib2 and used a tip from [this
question](http://stackoverflow.com/questions/5925028/urllib2-post-progress-
monitoring) to override the read() of the file to get the upload progress.
Furthermore I'm using poster to generate the multipart urlencode. Here's the
latest code:
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
def Upload(video_id, username, password, title, description, filename):
class Progress(object):
def __init__(self):
self._seen = 0.0
def update(self, total, size, name):
self._seen += size
pct = (self._seen / total) * 100.0
print '%s progress: %.2f' % (name, pct)
class file_with_callback(file):
def __init__(self, path, mode, callback, *args):
file.__init__(self, path, mode)
self.seek(0, os.SEEK_END)
self._total = self.tell()
self.seek(0)
self._callback = callback
self._args = args
def __len__(self):
return self._total
def read(self, size):
data = file.read(self, size)
self._callback(self._total, len(data), *self._args)
return data
progress = Progress()
stream = file_with_callback(filename, 'rb', progress.update, filename)
datagen, headers = multipart_encode({
"post": "1",
"skin": "xmlhttprequest",
"userlogin": "%s" % username,
"password": "%s" % password,
"item_type": "file",
"title": "%s" % title.encode("utf-8"),
"description": "%s" % description.encode("utf-8"),
"file": stream
})
opener = register_openers()
req = urllib2.Request(UPLOAD_URL, datagen, headers)
response = urllib2.urlopen(req)
return response.read()
This works though only for file path inputs, rather than an
InMemoryUploadedFile that comes from a form input (request.FILES), since it is
trying to read the file already saved in memory I suppose, and I get a
TypeError on line: "stream = file_with_callback(filename, 'rb',
progress.update, filename)":
coercing to Unicode: need string or buffer, InMemoryUploadedFile found
How can I achieve the same progress reporting with the user-uploaded file?
Also, will this consume alot of memory reading out the progress like this,
perhaps an upload solution to this [download progress for
urllib2](http://stackoverflow.com/questions/2028517/python-urllib2-progress-
hook) will work better, but how to implement... Help is sooo welcome
Answer: It turns out that the
[poster](http://atlee.ca/software/poster/poster.encode.html) library has a
callback hook in multipart_encode, which can be used to get the progress out
(upload or download). Good stuff...
Although i suppose I technically answered this question, I'm sure there are
other ways to skin this cat, so i'll post more if I find other methods or
details for this.
Here's the code:
def prog_callback(param, current, total):
pct = 100 - ((total - current ) *100 )/ (total)
print "Progress: %s " % pct
datagen, headers = multipart_encode({
"post": "1",
"skin": "xmlhttprequest",
"userlogin": "%s" % username,
"password": "%s" % password,
"item_type": "file",
"title": "%s" % title.encode("utf-8"),
"description": "%s" % description.encode("utf-8"),
"file": filename
}, cb=prog_callback)
opener = register_openers()
req = urllib2.Request(UPLOAD_URL, datagen, headers)
response = urllib2.urlopen(req)
return response.read()
|
events created with python vobject are not recognised by ms exchange
Question: I create an meeting invite using the python vobject and django's
`EmailMultiAlternatives` as follows:
cal = vobject.iCalendar()
cal.add('method').value = 'REQUEST' #IE/Outlook needs this
vevent = cal.add('vevent')
start = datetime.datetime(start.year, start.month, start.day, start.hour, start.minute, 0, 0, gettz(timezone))
end = datetime.datetime(end.year, end.month, end.day, end.hour, end.minute, 0, 0, gettz(timezone))
vevent.add('dtstamp').value = datetime.datetime.utcnow()
vevent.add('organizer').value = "mailto:" + organizer.email
vevent.add('uid').value = uid
vevent.add('sequence').value = str(sequence_number)
for participant in participants:
vevent.add('attendee;cutype=individual;role=req-participant;partstat=needs-action;rsvp=true').value = "mailto:" + participant.email
vevent.add('dtstart').value = start
vevent.add('dtend').value = end
vevent.add('summary').value = title
vevent.add('description').value = desc
vevent.add('last-modified').value = datetime.datetime.utcnow()
vevent.add('status').value = 'CONFIRMED'
vevent.add('location').value = ''
vevent.add('priority').value = '5'
vevent.add('class').value = ''
vevent.add('transp').value = 'OPAQUE'
vevent.add('created').value = created
vevent.add('x-microsoft-cdo-busystatus').value = 'BUSY'
vevent.add('x-microsoft-cdo-alldayevent').value = 'FALSE'
vevent.add('x-microsoft-cdo-insttype').value = '0'
vevent.add('x-microsoft-cdo-intendedstatus').value = 'FALSE'
vevent.add('x-microsoft-cdo-importance').value = '1'
vevent.add('x-microsoft-cdo-appt-sequence').value = str(sequence_number)
The email sent is as follows:
Content-Type: multipart/mixed; boundary="===============0735652256227437116=="
MIME-Version: 1.0
Subject: Test Meeting
From: "..." <...@example.com>
To: ...@example.com
Date: Tue, 21 Jun 2011 13:31:43 -0000
Message-ID: <20110621133143.17903.84489@...>
Reply-To: "..." <...@example.com>
X-OriginalArrivalTime: 21 Jun 2011 13:29:25.0546 (UTC) FILETIME=[3D2A38A0:01CC3017]
--===============0735652256227437116==
Content-Type: multipart/alternative;
boundary="===============1854598015118304554=="
MIME-Version: 1.0
--===============1854598015118304554==
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: Test Meeting
Time: 8 p.m. - 9 p.m. GMT+0530 Asia/Kolkata
Moderator: ... (...@example.com)
Message: A test meeting.
--===============1854598015118304554==
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
<table width=3D"100%">
<tr bgcolor=3D"#d8d8d8">
<td align=3D"center">
<table width=3D"530px" bgcolor=3D"#FFFFFF" style=3D"ma=
rgin-top:20px;padding:10px;margin-bottom:20px;text-align:left;">
<tr>
<td style=3D"padding-top:10px;">
<font face=3D"Arial, Helvetica, sans-serif=
">
<font color=3D"#336699" size=3D"14px" =
style=3D"font-size:14px;line-height:18px;"><b>Meeting Title:</b></font>
<font size=3D"14px" style=3D"font-size=
:14px;">Test Meeting</font>
</font>
</td>
</tr>
<tr>
<td style=3D"padding-top:10px;">
<font face=3D"Arial, Helvetica, sans-serif=
">
<font color=3D"#336699" size=3D"14px" =
style=3D"font-size:14px;line-height:18px;"><b>Meeting Time:</b></font>
<font size=3D"14px" style=3D"font-size=
:14px;">June 21, 2011</font>
<font size=3D"14px" style=3D"font-size=
:14px;">8 p.m. - 9 p.m.</font>
<font size=3D"11px" style=3D"font-size=
:11px;">GMT+0530 Asia/Kolkata</font>
</font>
</td>
</tr>
<tr>
<td style=3D"padding-top:10px;">
<font face=3D"Arial, Helvetica, sans-serif=
">
<font size=3D"14px" color=3D"#336699" =
style=3D"font-size:14px;line-height:18px;"><b>Moderator:</b></font>
<font size=3D"14px" style=3D"font-size=
:14px;">...</font>
<font size=3D"14px" style=3D"font-size=
:14px;">(<a href=3D"mailto:...@example.com">...@example.com</a>)</font>
</font>
</td>
</tr>
<tr>
<td style=3D"padding-top:10px;">
<font face=3D"Arial, Helvetica, sans-serif=
">
<font size=3D"14px" color=3D"#336699" =
style=3D"font-size:14px;line-height:18px;"><b>Message/Description:</b></fon=
t><br>
<font size=3D"14px" style=3D"font-size=
:14px;">A test meeting.<br /></font>
</font>
</td>
</tr>
</table>
</td>
</tr>
</table>
--===============1854598015118304554==
MIME-Version: 1.0
Content-Type: text/calendar; method="REQUEST"; name="invite.ics";
charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Content-class: urn:content-classes:calendarmessage
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REQUEST
PRODID:-//PYVOBJECT//NONSGML Version 1//EN
BEGIN:VTIMEZONE
TZID:IST
BEGIN:STANDARD
DTSTART:20000101T000000
RRULE:FREQ=3DYEARLY;BYMONTH=3D1
TZNAME:IST
TZOFFSETFROM:+0530
TZOFFSETTO:+0530
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
UID:IoCJJ_840167408_31@example.com
DTSTART;TZID=3DIST:20110621T200000
DTEND;TZID=3DIST:20110621T210000
ATTENDEE;CUTYPE=3DINDIVIDUAL;ROLE=3DREQ-PARTICIPANT;PARTSTAT=3DNEEDS-ACTIO=
N;RSVP
=3DTRUE:mailto:...@example.com
CLASS:
CREATED:20110621T052344Z
DESCRIPTION:A test meeting.\n
DTSTAMP:20110621T133143Z
LAST-MODIFIED:20110621T133143Z
LOCATION:
ORGANIZER:mailto:...@example.com
PRIORITY:5
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Test Meeting
TRANSP:OPAQUE
X-MICROSOFT-CDO-ALLDAYEVENT:FALSE
X-MICROSOFT-CDO-APPT-SEQUENCE:1
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
X-MICROSOFT-CDO-IMPORTANCE:1
X-MICROSOFT-CDO-INSTTYPE:0
X-MICROSOFT-CDO-INTENDEDSTATUS:FALSE
END:VEVENT
END:VCALENDAR
--===============1854598015118304554==--
--===============0735652256227437116==
Content-Type: application/ics; name="invite.ics"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="invite.ics"
QkVHSU46VkNBTEVOREFSDQpWRVJTSU9OOjIuMA0KTUVUSE9EOlJFUVVFU1QNClBST0RJRDotLy9QWVZPQkpFQ1QvL05PTlNHTUwgVmVyc2lvbiAxLy9FTg0KQkVHSU46VlRJTUVaT05FDQpUWklEOklTVA0KQkVHSU46U1RBTkRBUkQNCkRUU1RBUlQ6MjAwMDAxMDFUMDAwMDAwDQpSUlVMRTpGUkVRPVlFQVJMWTtCWU1PTlRIPTENClRaTkFNRTpJU1QNClRaT0ZGU0VURlJPTTorMDUzMA0KVFpPRkZTRVRUTzorMDUzMA0KRU5EOlNUQU5EQVJEDQpFTkQ6VlRJTUVaT05FDQpCRUdJTjpWRVZFTlQNClVJRDpJb0NKSl84NDAxNjc0MDhfMzFAZXhhbXBsZS5jb20NCkRUU1RBUlQ7VFpJRD1JU1Q6MjAxMTA2MjFUMjAwMDAwDQpEVEVORDtUWklEPUlTVDoyMDExMDYyMVQyMTAwMDANCkFUVEVOREVFO0NVVFlQRT1JTkRJVklEVUFMO1JPTEU9UkVRLVBBUlRJQ0lQQU5UO1BBUlRTVEFUPU5FRURTLUFDVElPTjtSU1ZQDQogPVRSVUU6bWFpbHRvOi4uLkBleGFtcGxlLmNvbQ0KQ0xBU1M6DQpDUkVBVEVEOjIwMTEwNjIxVDA1MjM0NFoNCkRFU0NSSVBUSU9OOkEgdGVzdCBtZWV0aW5nLlxuDQpEVFNUQU1QOjIwMTEwNjIxVDEzMzE0M1oNCkxBU1QtTU9ESUZJRUQ6MjAxMTA2MjFUMTMzMTQzWg0KTE9DQVRJT046DQpPUkdBTklaRVI6bWFpbHRvOi4uLkBleGFtcGxlLmNvbQ0KUFJJT1JJVFk6NQ0KU0VRVUVOQ0U6MQ0KU1RBVFVTOkNPTkZJUk1FRA0KU1VNTUFSWTpUZXN0IE1lZXRpbmcNClRSQU5TUDpPUEFRVUUNClgtTUlDUk9TT0ZULUNETy1BTExEQVlFVkVOVDpGQUxTRQ0KWC1NSUNST1NPRlQtQ0RPLUFQUFQtU0VRVUVOQ0U6MQ0KWC1NSUNST1NPRlQtQ0RPLUJVU1lTVEFUVVM6QlVTWQ0KWC1NSUNST1NPRlQtQ0RPLUlNUE9SVEFOQ0U6MQ0KWC1NSUNST1NPRlQtQ0RPLUlOU1RUWVBFOjANClgtTUlDUk9TT0ZULUNETy1JTlRFTkRFRFNUQVRVUzpGQUxTRQ0KRU5EOlZFVkVOVA0KRU5EOlZDQUxFTkRBUg==
--===============0735652256227437116==--
Which when decoded looks like:
Content-Type: multipart/mixed; boundary="===============0735652256227437116=="
MIME-Version: 1.0
Subject: Test Meeting
From: "..." <...@example.com>
To: ...@example.com
Date: Tue, 21 Jun 2011 13:31:43 -0000
Message-ID: <20110621133143.17903.84489@...>
Reply-To: "..." <...@example.com>
X-OriginalArrivalTime: 21 Jun 2011 13:29:25.0546 (UTC) FILETIME=[3D2A38A0:01CC3017]
--===============0735652256227437116==
Content-Type: multipart/alternative;
boundary="===============1854598015118304554=="
MIME-Version: 1.0
--===============1854598015118304554==
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: Test Meeting
Time: 8 p.m. - 9 p.m. GMT+0530 Asia/Kolkata
Moderator: ... (...@example.com)
Message: A test meeting.
--===============1854598015118304554==
Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
<table width="100%">
<tr bgcolor="#d8d8d8">
<td align="center">
<table width="530px" bgcolor="#FFFFFF" style="margin-top:20px;padding:10px;margin-bottom:20px;text-align:left;">
<tr>
<td style="padding-top:10px;">
<font face="Arial, Helvetica, sans-serif">
<font color="#336699" size="14px" style="font-size:14px;line-height:18px;"><b>Meeting Title:</b></font>
<font size="14px" style="font-size:14px;">Test Meeting</font>
</font>
</td>
</tr>
<tr>
<td style="padding-top:10px;">
<font face="Arial, Helvetica, sans-serif">
<font color="#336699" size="14px" style="font-size:14px;line-height:18px;"><b>Meeting Time:</b></font>
<font size="14px" style="font-size:14px;">June 21, 2011</font>
<font size="14px" style="font-size:14px;">8 p.m. - 9 p.m.</font>
<font size="11px" style="font-size:11px;">GMT+0530 Asia/Kolkata</font>
</font>
</td>
</tr>
<tr>
<td style="padding-top:10px;">
<font face="Arial, Helvetica, sans-serif">
<font size="14px" color="#336699" style="font-size:14px;line-height:18px;"><b>Moderator:</b></font>
<font size="14px" style="font-size:14px;">...</font>
<font size="14px" style="font-size:14px;">(<a href="mailto:...@example.com">...@example.com</a>)</font>
</font>
</td>
</tr>
<tr>
<td style="padding-top:10px;">
<font face="Arial, Helvetica, sans-serif">
<font size="14px" color="#336699" style="font-size:14px;line-height:18px;"><b>Message/Description:</b></font><br>
<font size="14px" style="font-size:14px;">A test meeting.<br /></font>
</font>
</td>
</tr>
</table>
</td>
</tr>
</table>
--===============1854598015118304554==
MIME-Version: 1.0
Content-Type: text/calendar; method="REQUEST"; name="invite.ics";
charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Content-class: urn:content-classes:calendarmessage
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REQUEST
PRODID:-//PYVOBJECT//NONSGML Version 1//EN
BEGIN:VTIMEZONE
TZID:IST
BEGIN:STANDARD
DTSTART:20000101T000000
RRULE:FREQ=YEARLY;BYMONTH=1
TZNAME:IST
TZOFFSETFROM:+0530
TZOFFSETTO:+0530
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
UID:IoCJJ_840167408_31@example.com
DTSTART;TZID=IST:20110621T200000
DTEND;TZID=IST:20110621T210000
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP
=TRUE:mailto:...@example.com
CLASS:
CREATED:20110621T052344Z
DESCRIPTION:A test meeting.\n
DTSTAMP:20110621T133143Z
LAST-MODIFIED:20110621T133143Z
LOCATION:
ORGANIZER:mailto:...@example.com
PRIORITY:5
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Test Meeting
TRANSP:OPAQUE
X-MICROSOFT-CDO-ALLDAYEVENT:FALSE
X-MICROSOFT-CDO-APPT-SEQUENCE:1
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
X-MICROSOFT-CDO-IMPORTANCE:1
X-MICROSOFT-CDO-INSTTYPE:0
X-MICROSOFT-CDO-INTENDEDSTATUS:FALSE
END:VEVENT
END:VCALENDAR
--===============1854598015118304554==--
--===============0735652256227437116==
Content-Type: application/ics; name="invite.ics"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="invite.ics"
BEGIN:VCALENDAR
VERSION:2.0
METHOD:REQUEST
PRODID:-//PYVOBJECT//NONSGML Version 1//EN
BEGIN:VTIMEZONE
TZID:IST
BEGIN:STANDARD
DTSTART:20000101T000000
RRULE:FREQ=YEARLY;BYMONTH=1
TZNAME:IST
TZOFFSETFROM:+0530
TZOFFSETTO:+0530
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
UID:IoCJJ_840167408_31@example.com
DTSTART;TZID=IST:20110621T200000
DTEND;TZID=IST:20110621T210000
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP
=TRUE:mailto:...@example.com
CLASS:
CREATED:20110621T052344Z
DESCRIPTION:A test meeting.\n
DTSTAMP:20110621T133143Z
LAST-MODIFIED:20110621T133143Z
LOCATION:
ORGANIZER:mailto:...@example.com
PRIORITY:5
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Test Meeting
TRANSP:OPAQUE
X-MICROSOFT-CDO-ALLDAYEVENT:FALSE
X-MICROSOFT-CDO-APPT-SEQUENCE:1
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
X-MICROSOFT-CDO-IMPORTANCE:1
X-MICROSOFT-CDO-INSTTYPE:0
X-MICROSOFT-CDO-INTENDEDSTATUS:FALSE
END:VEVENT
END:VCALENDAR
--===============0735652256227437116==--
This email works in every environment like Thunderbird/Lightening, Outlook
(without Exchange backend), GMail Calender, etc. except when the calendering
is handled by Exchange.
Can anyone tell me what is wrong and how to solve it.
Answer: Exchange strips out the content of the email when an application/ics
attachment is included. If that alternate view is removed, then the problem
should clear itself up.
|
How to include autocomplete in a python web form with MongoDB
Question: I wrote a web page in Python as follows:
#!/usr/bin/env python
import os, re, sys
from datetime import datetime
from pymongo import Connection
import cgi
class Handler:
def do(self, environ, start_response):
html = "<html><head><title>C Informatics</title></head><body>"
html += "<h1><center>National Management & Information System</h1>"
html += '<center><h3>CONTROL PROGRAMME<br>'
html += '</center>'
html += '<form method="post" action="newreg.py">'
html += 'Person Name :<input type="text" name="pname">'
html += 'Age :<input type="text" name="age">'
html += 'Gender : <input type="radio" name="sex" value="male">M'
html += '<input type="radio" name="sex" value="female">F<br><br>'
html += 'Complete Address :<br>'
html += 'H.No. and Street :<input type="text" name="hn1">'
html += 'Locality : <input type="text" name="locality">'
html += 'PIN Code : <input type="text" name="pin"><br>'
html += '<input type="submit" Value="Save">'
html += '</form>'
html += '</center>'
html += "</body></html>"
connection = Connection('localhost', 27017)
db = connection.health
tc = db.testColl
item = tc.find_one()["name"]
html += str(item)
html += name
output = html
mimeType = "text/html"
In the above form, I want to autocomplete the form field 'Location' (which
also pulls out the respective PIN code of that location and displays in the
field PIN).
The Data, Locations Name and their respective PIN code, are saved in a
collection in MongoDB.
So that when 'Save' is clicked the information is saved in new collections in
MongoDB.
With code, can some one please show me how it can be done ?
Thanks
NC
Answer: This question has neither to do with Python nor with MongoDB. What you are
trying is some auto-complete functionality through Javascript.
<http://docs.jquery.com/Plugins/autocomplete>
is a good start.
|
jdbc: Get the SQL Type Name from java.sql.Type code
Question: I have an array with Field Names and jdbc Type codes. (Those int codes that
you can find in
<http://download.oracle.com/javase/1.4.2/docs/api/constant-
values.html#java.sql.Types.BIT>
I use a level 4 Driver.
I can't figure out how to ask the driver for the corresponding SQL (DDL) Type
names. It would be useful in jdbc and in native dialects.
I have
(CustomerId, 1) (CustomerName, -8)
and I want
(customerId, INT) (customerId, VARCHAR(200))
Where can I find functions that help me with that? I am using jdbc in jython
via zxJDBC, so I can use all java and python DB API 2.0 functionality.
Answer: To specifically answer "Get the SQL Type Name from java.sql.Type code", if you
are using a version of java that can do reflection, here is a small utility
method that pretty much does the same thing:
public Map<Integer, String> getAllJdbcTypeNames() {
Map<Integer, String> result = new HashMap<Integer, String>();
for (Field field : Types.class.getFields()) {
result.put((Integer)field.get(null), field.getName());
}
return result;
}
Add `import java.lang.reflect.Field;` to your import declarations. Once you
have that in place, simply use it as follows:
...
Map<Integer, String> jdbcMappings = getAllJdbcTypeNames();
String typeName = jdbcMappings.get(-5); // now that will return BIGINT
...
|
mod_wsgi python2.5 ubuntu 11.04 problem
Question: I have such cfg on my amd64 platform with ubuntu 11.04:
1. build python2.5 from source to /usr/local/python2.5
2. virtualenv at /home/se7en/.virtualenvs/e-py25
alsp i recompile mod_wsgi.so to custom python:
se7en@se7en-System-Product-Name:~$ ldd /usr/lib/apache2/modules/mod_wsgi.so
linux-vdso.so.1 => (0x00007fff5af6c000)
libpython2.5.so.1.0 => /usr/lib/libpython2.5.so.1.0 (0x00007f7bed14b000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f7becf2d000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f7becd28000)
libutil.so.1 => /lib/x86_64-linux-gnu/libutil.so.1 (0x00007f7becb25000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f7bec8a0000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f7bec50b000)
/lib64/ld-linux-x86-64.so.2 (0x00007f7bed717000)
django.wsgi
#/usr/local/python2.5/bin/python
# -*- coding: utf-8 -*-
import os, sys
sys.stdout = sys.stderr
dn = os.path.dirname
PROJECT_ROOT = os.path.abspath( (dn(__file__)) )
#DJANGO_PROJECT_ROOT = os.path.join(PROJECT_ROOT, 'apps')
DJANGO_PROJECT_ROOT = PROJECT_ROOT
sys.path.insert(0, '/usr/local/python2.5/lib/python2.5/site-packages' )
sys.path.insert(0,'/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages')
sys.path.insert(0, DJANGO_PROJECT_ROOT )
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
print sys.version #return 2.5.5 (r255:77872, Apr 15 2011, 22:12:51
print sys.path
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
apache site config:
<VirtualHost 192.168.1.3>
ServerAdmin admin@wsgi.debianworld.ru
ServerName wsgi.debianworld.ru
ErrorLog /home/se7en/workspace/lxchg/logs/error_log
CustomLog /home/se7en/workspace/lxchg/logs/access_log common
WSGIScriptAlias / /home/se7en/workspace/lxchg/django.wsgi
Alias "/media/" "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/contrib/admin/media/"
<Location "/media/">
SetHandler None
</Location>
Alias "/main_media/" "/home/se7en/workspace/lxchg/main_media/"
<Location "/main_media/">
SetHandler None
</Location>
</VirtualHost>
WSGIPythonHome /home/se7en/.virtualenvs/e-py25
#WSGIPythonExecutable /usr/local/python2.5/bin/python
I got an error in my error log:
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] mod_wsgi (pid=2955): Exception occurred processing WSGI script '/home/se7en/workspace/lxchg/django.wsgi'.
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] Traceback (most recent call last):
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 248, in __call__
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] response = self.get_response(request)
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/core/handlers/base.py", line 141, in get_response
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] return self.handle_uncaught_exception(request, resolver, sys.exc_info())
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/core/handlers/base.py", line 176, in handle_uncaught_exception
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] if resolver.urlconf_module is None:
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/core/urlresolvers.py", line 239, in _get_urlconf_module
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] self._urlconf_module = import_module(self.urlconf_name)
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] __import__(name)
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "C:\\workspace\\sdl\\lxchg\\urls.py", line 3, in <module>
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/views/generic/create_update.py", line 1, in <module>
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] from django.forms.models import ModelFormMetaclass, ModelForm
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/forms/__init__.py", line 17, in <module>
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] from models import *
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/forms/models.py", line 6, in <module>
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] from django.db import connections
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/db/__init__.py", line 77, in <module>
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] connection = connections[DEFAULT_DB_ALIAS]
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/db/utils.py", line 92, in __getitem__
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] backend = load_backend(db['ENGINE'])
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] File "/home/se7en/.virtualenvs/e-py25/lib/python2.5/site-packages/django/db/utils.py", line 50, in load_backend
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] raise ImproperlyConfigured(error_msg)
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] ImproperlyConfigured: 'django.db.backends.mysql' isn't an available database backend.
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] Try using django.db.backends.XXX, where XXX is one of:
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] 'dummy', 'mysql', 'oracle', 'postgresql', 'postgresql_psycopg2', 'sqlite3'
[Wed Jun 22 13:45:54 2011] [error] [client 192.168.1.3] Error was: /home/se7en/.virtualenvs/e-py25/lib/python2.5/lib-dynload/array.so: undefined symbol: PyUnicodeUCS2_FromUnicode
Then i start project via manage.py runserver it works, but via mod_wsgi do
not. please help)
Answer: The operating system supplied Python versions on Linux boxes are compiled for
UCS4 Unicode character width. If you build from source code, if you don't
explicitly say otherwise it will default to UCS2. The result is that your
system Python 2.5 and local version under /usr/local are expecting different
widths for Unicode characters and since Unicode functions have the UCS type as
part of the name, when you are using objects compiled for one Python with the
other, you get undefined errors for the Unicode functions.
Why this is occuring as hinted at by other answer is that mod_wsgi.so is
actually picking up the system wide UCS4 libpython2.5.so file instead of that
for UCS2 Python under /usr/local/lib. Although you could set LD_LIBRARY_PATH
to make a process to look in /usr/local/lib first, that is a pain to do under
Apache. Instead what you should do is rebuild mod_wsgi from source code again
and do:
make distclean
./configure --with-python=/usr/local/bin/python2.5
LD_RUN_PATH=/usr/local/lib make
sudo make install
By setting LD_RUN_PATH as environment variable on the command when invoking
'make', the linker will embed /usr/local/lib into library search path direct
into mod_wsgi.so. That way it will find correct libpython2.5.so at run time
without needing to set LD_LIBRARY_PATH. You can confirm it worked by running
'ldd' on the resultant mod_wsgi.so and it should then pick up correct library
from /usr/local/lib.
|
Help with solving the DistributionNotFound error in Virtualenv
Question: I've installed `virtualenv` on my system which the argument to not copy over
any site packages. Then I did an `easy_install` to install Django and that
went fine too.
In the virtual environ when i try and try `django-admin.py`, I get an error
that I'm not being able to resolve. Could someone help me out please? Thanks a
ton.
(virt1) C:\virt_env\virt1>Scripts\django-admin.py
Traceback (most recent call last):
File "C:\virt_env\virt1\Scripts\django-admin.py", line 4, in <module>
import pkg_resources
File "C:\Program_Files\Python27\lib\site-packages\pkg_resources.py", line 2607, in <module>
parse_requirements(__requires__), Environment()
File "C:\Program_Files\Python27\lib\site-packages\pkg_resources.py", line 565, in resolve
raise DistributionNotFound(req) # XXX put more info here
pkg_resources.DistributionNotFound: django==1.3
Answer: I don't think `easy_install` knows about `virtualenv`. Use `pip` instead.
|
pygame freezes when I try to exit it after running it from IDLE!
Question: I'm running it through the livewires wrapper which is just training wheels for
pygame and other python modules in general; but everytime I run it, it'll
execute and when I try to exit, it will not respond and then crash.
Any input on how I could go about fixing this would be great. There isn't any
input in my textbook and all google seems to yield are results to this problem
using pygame itself.
Apparently pygame and Tkinter seem to conflict?
Thanks in advance!
Addendum - This is the code I was trying to run:
from livewires import games
screen_w = 640
screen_h = 480
my_screen = games.Screen (wid, heit)
my_screen.mainloop()
Answer: Similar question: [Pygame screen freezes when I close
it](http://stackoverflow.com/questions/5615860/pygame-screen-freezes-when-i-
close-it)
> There isn't any input in my textbook and all google seems to yield are
> results to this problem using pygame itself.
Those results probably address the same problem you're having. This is the
relevant part of the games.py file from livewires, and nowhere does it call
`pygame.quit()`:
def handle_events (self):
"""
If you override this method in a subclass of the Screen
class, you can specify how to handle different kinds of
events. However you must handle the quit condition!
"""
events = pygame.event.get ()
for event in events:
if event.type == QUIT:
self.quit ()
elif event.type == KEYDOWN:
self.keypress (event.key)
elif event.type == MOUSEBUTTONUP:
self.mouse_up (event.pos, event.button-1)
elif event.type == MOUSEBUTTONDOWN:
self.mouse_down (event.pos, event.button-1)
def quit (self):
"""
Calling this method will stop the main loop from running and
make the graphics window disappear.
"""
self._exit = 1
def mainloop (self, fps = 50):
"""
Run the pygame main loop. This will animate the objects on the
screen and call their tick methods every tick.
fps -- target frame rate
"""
self._exit = 0
while not self._exit:
self._wait_frame (fps)
for object in self._objects:
if not object._static:
object._erase ()
object._dirty = 1
# Take a copy of the _objects list as it may get changed in place.
for object in self._objects [:]:
if object._tickable: object._tick ()
self.tick ()
if Screen.got_statics:
for object in self._objects:
if not object._static:
for o in object.overlapping_objects ():
if o._static and not o._dirty:
o._erase ()
o._dirty = 1
for object in self._objects:
if object._dirty:
object._draw ()
object._dirty = 0
self._update_display()
self.handle_events()
# Throw away any pending events.
pygame.event.get()
The QUIT event just sets a flag which drops you out of the while loop in the
`mainloop` function. I'm guessing that if you find this file in your Python
directory and stick a `pygame.quit()` after the last line in `mainloop`, it
will solve your problem.
|
No module named os found -- Django, mod_wsgi, Apache 2.2
Question: I'm trying to set up apache, mod_wsgi, and django. I'm getting an internal
server error with this in my apache error log:
[Wed Jun 22 21:31:55 2011] [error] [client ::1] mod_wsgi (pid=2893): Target WSGI script '/django/internal/django-development.wsgi' cannot be loaded as Python module.
[Wed Jun 22 21:31:55 2011] [error] [client ::1] mod_wsgi (pid=2893): Exception occurred processing WSGI script '/django/internal/django-development.wsgi'.
[Wed Jun 22 21:31:55 2011] [error] Traceback (most recent call last):
[Wed Jun 22 21:31:55 2011] [error] File "/django/internal/django-development.wsgi", line 3, in <module>
[Wed Jun 22 21:31:55 2011] [error] import sys, os
[Wed Jun 22 21:31:55 2011] [error] ImportError: No module named os
[Wed Jun 22 21:31:55 2011] [error] [client ::1] mod_wsgi (pid=2893): Target WSGI script '/django/internal/django-development.wsgi' cannot be loaded as Python module.
[Wed Jun 22 21:31:55 2011] [error] [client ::1] mod_wsgi (pid=2893): Exception occurred processing WSGI script '/django/internal/django-development.wsgi'.
[Wed Jun 22 21:31:55 2011] [error] Traceback (most recent call last):
[Wed Jun 22 21:31:55 2011] [error] File "/django/internal/django-development.wsgi", line 3, in <module>
[Wed Jun 22 21:31:55 2011] [error] import sys, os
[Wed Jun 22 21:31:55 2011] [error] ImportError: No module named os
django-development.wsgi
#! /usr/bin/env python
import sys, os
path = '/django/internal'
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'internal.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Please let me know if there's anything (configuration files, for example) I
can post to help you help me diagnose this problem.
_edit:_
this is odd, considering I thought I set my default python version to 2.5..,
and ran ./configure with the python2.5 as a parameter
$otool -L mod_wsgi.somod_wsgi.so:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.10)
/System/Library/Frameworks/Python.framework/Versions/2.6/Python (compatibility version 2.6.0, current version 2.6.1)
and
LoadModule wsgi_module libexec/apache2/mod_wsgi.so
WSGIScriptAlias / /django/internal/django-development.wsgi
_edit:_
Ah, it looks like a bad configuration file was being imported. I've gotten it
to now give me the following output. Progress:
[Wed Jun 22 23:04:28 2011] [error] Exception ImportError: 'No module named atexit' in 'garbage collection' ignored
Fatal Python error: unexpected exception during garbage collection
[Wed Jun 22 23:04:28 2011] [error] Exception ImportError: 'No module named atexit' in 'garbage collection' ignored
Fatal Python error: unexpected exception during garbage collection
[Wed Jun 22 23:04:29 2011] [notice] caught SIGTERM, shutting down
[Wed Jun 22 23:04:29 2011] [warn] Init: Session Cache is not configured [hint: SSLSessionCache]
[Wed Jun 22 23:04:29 2011] [warn] mod_wsgi: Compiled for Python/2.5.4.
[Wed Jun 22 23:04:29 2011] [warn] mod_wsgi: Runtime using Python/2.6.1.
[Wed Jun 22 23:04:29 2011] [notice] Digest: generating secret for digest authentication ...
[Wed Jun 22 23:04:29 2011] [notice] Digest: done
[Wed Jun 22 23:04:29 2011] [notice] Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8l DAV/2 mod_wsgi/3.3 Python/2.6.1 configured -- resuming normal operations
[Wed Jun 22 23:06:04 2011] [error] [client ::1] client denied by server configuration: /django/internal/django-development.wsgi
_edit_
So, I'd still like to figure out how to make mod_wsgi run python 2.5 instead
of 2.6 -- this is what's causing me my big issues right now. Beyond that, it
should just be tweaking the apache configuration.
Answer: mod_wsgi for some reason cannot see your Py2.5 library. I would suggest
checking the value of
[WSGIPythonPath](http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPythonPath)
and make sure it points to something like /usr/lib/python2.5
|
soaplib with mod_wsgi without django, cherypy or other framework
Question: I checked soaplib for python on net and i get the example
import soaplib
from soaplib.core.service import rpc, DefinitionBase
from soaplib.core.model.primitive import String, Integer
from soaplib.core.server import wsgi
from soaplib.core.model.clazz import Array
class HelloWorldService(DefinitionBase):
@soap(String,Integer,_returns=Array(String))
def say_hello(self,name,times):
results = []
for i in range(0,times):
results.append('Hello, %s'%name)
return results
if __name__=='__main__':
try:
from wsgiref.simple_server import make_server
soap_application = soaplib.core.Application([HelloWorldService], 'tns')
wsgi_application = wsgi.Application(soap_application)
server = make_server('localhost', 7789, wsgi_application)
server.serve_forever()
except ImportError:
print "Error: example server code requires Python >= 2.5"
this example is working fine. But i want to run this with the mod_wsgi in
apache. I checked net and all come with django, cherrypy or pylone. Is it
possible to run this example without any python web framwork? what are the
steps to follow to run this example under mod_wsgi in apache. I want to run
this in unix.
Answer: Like every other "Integration With" document in the
[wiki](http://code.google.com/p/modwsgi/w/list), except with `application =
wsgi.Application(soap_application)`.
|
Where does python look for a dll opened by ctypes.cdll.<name> on windows?
Question: I'm afriad I couldn't find a simple answer for this on the internet, so maybe
there will be one in the future because of this question!
I'm using pywiiuse, a python wrapper for the C wiiuse library on windows. I've
gotten several plain C examples working simply by including the dll, header,
and library in the directory of the source.
However, I'm wondering where to put the dll so that pywiiuse will find it. A
look at the source shows that it is loaded as follows:
dll = ctypes.cdll.wiiuse
Running examples yields a module not found exception when I have the dll in
the same directory as my test example.
Where does python look for the dll?
Answer: The [Windows DLL search order](http://msdn.microsoft.com/en-
us/library/ms682586.aspx) is documented on MSDN. It's not Python-specific, and
there is no way to change the search order from a command-line option. (But
see the linked article for other ways to influence the search order.)
The source to
[`ctypes/__init__.py`](http://wpython11.wpython2.googlecode.com/hg/Lib/ctypes/__init__.py)
does:
from _ctypes import LoadLibrary as _dlopen
I wasn't able to find the definition of `LoadLibrary` in
[`_ctypes.c`](http://wpython11.wpython2.googlecode.com/hg/Modules/_ctypes/_ctypes.c),
but presumably it is a wrapper for the Windows
[`LoadLibraryEx`](http://msdn.microsoft.com/en-us/library/ms684179.aspx)
function that behaves similarly to the POSIX
[`dlopen`](http://linux.die.net/man/3/dlopen) function, because that is how it
is used.
If you can modify the Python source to use the `ctypes.CDLL` constructor
instead, it should work:
folder = os.path.dirname(os.path.abspath(__file__))
dll_path = os.path.join(folder, "wiiuse.dll")
dll = ctypes.CDLL(dll_path)
If that isn't viable, you may be able to monkey-patch ctypes to handle this
specific case, but that seems a bit dangerous. Perhaps just copying the DLL to
be in the same folder with the Python DLL would be the easiest alternative.
|
trying to rotate a triangle with complex numbers in tkinter python
Question: the first method is mine, the other two are from here
<http://effbot.org/zone/tkinter-complex-canvas.htm>
so i call the rotate method that calls the second one that calls the first
one. the first one gets the xy coordinates from the angle that is passed, and
then work with them to translate the triangle.
self.x and self.y are the coordinates on the canvas of the triangle, the
middle of the lower line of the triangle
i guess there's another way to do this, much simpler.
and i have found this btw, but it doesn't really help
[How do I rotate a polygon in python on a Tkinter
Canvas?](http://stackoverflow.com/questions/3408779/how-do-i-rotate-a-polygon-
in-python-on-a-tkinter-canvas)
Answer: Your post implied difficulty with understanding how to rotate triangles using
complex numbers. After reading your comment in reply to my answer I have
edited my code sample to demonstrate a way to get the angle from keyboard
input. I have no experience with Tkinter so perhaps someone can help with a
more state of the art approach. Gleaned from [Tkinter: Events and
Bindings](http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm) and
[The Tkinter Entry
Widget](http://effbot.org/tkinterbook/entry.htm#entry.Entry.config-method)
When you enter the keypress event handler, the Entry widget's text, retrieved
with text.get(), doesn't include the latest keypress character.
The angle entered is in degrees and can be negative.
from Tkinter import *
import tkSimpleDialog as tks
import cmath,math
root = Tk()
c = Canvas(root,width=200, height=200)
c.pack()
# keypress event
def key(event):
text.focus_force()
ch=event.char
# handle backspace
if ch=='\x08':
if len(text.get())>1 :
entry_text=text.get()[:-1]
if entry_text=='-': entry_text='0'
else:
entry_text='0'
else:
entry_text=text.get()+ch
# we want an integer
try:
angle_degrees=int(entry_text)
cangle = cmath.exp(angle_degrees*1j*math.pi/180)
offset = complex(center[0], center[1])
newxy = []
for x, y in triangle:
v = cangle * (complex(x, y) - offset) + offset
newxy.append(v.real)
newxy.append(v.imag)
c.coords(polygon_item, *newxy)
except ValueError:
print "not integer"
text = Entry(root)
text.bind("<Key>", key)
text.pack()
text.focus_force()
# a triangle
triangle = [(50, 50), (150, 50), (150, 150)]
polygon_item = c.create_polygon(triangle)
center = 100, 100
mainloop()
|
unpickling python 2.6 object in python 3.1.1
Question: In python 2.6, I defined a class Abc, made a dict d where keys are strings and
values are abc objects. Then I dumped this dict to a file like this-
pickle.dump(d, open('filename.pkl', 'wb'))
I can successfully load it python 2.6 with
d1 = pickle.load(open('filename.pkl', 'rb'))
(d1 is identical to d)
But when I try to load it in python 3.1, only the first key (string) is loaded
d1 = pickle.load(open('filename.pkl', 'rb'))
print(d1)
keyname1
The pickled file starts like
(dp0
S'keyname1'
p1
(iabc
ABC
p2
So it seems like in 3.1, it's only loading the first string in the file. I
don't know much about encoding etc. Any ideas on what I can do to load my dict
d in 3.1.1?
Edit- my class (abc.py) is in the same working directory both times, not sure
if this matters?
Edit after answer- I realized I should have clarified better so it can be
reproduced easily. My code was buggy both because of the name clash and
because I wasn't defining my class correctly.
Anyways, I just tried the following and learnt that I should start classes
with class ABC(object): rather than just class ABC. And that I should delete
.pyc files before importing a module the second time.
What I did --
Try 1
ABC.py
class ABC():
pass
in python-2.6
import pickle
import ABC
d = {'keyname1': ABC.ABC()}
pickle.dump(d, open('filename.pkl', 'wb'))
quit()
in python-3.1
import pickle
d1 = pickle.load(open('filename.pkl', 'rb'))
print(d1)
keyname1
quit()
Try 2
But when I changed the class definition in ABC.py so it said class
ABC(object): instead of just class ABC:, removed the old filename.pkl, ABC.pyc
and repeated,
in python-2.6
# same as before
in python-3.1
import pickle
d1 = pickle.load(open('filename.pkl', 'rb'))
print(d1)
{'keyname1': <ABC.ABC object at 0x638890>}
Answer: The following works fine with Python 2.6.6 and Python 3.1.3:
Python 2.6 code:
import pickle
class ABC(object):
pass
d = {'keyname1': ABC()}
# Dump!
pickle.dump(d, open('filename.pkl', 'wb'))
Python 3.1 code:
import pickle
class ABC(object):
pass
# Load:
d1 = pickle.load(open('filename.pkl', 'rb'))
print(d1)
The result is:
{'keyname1': <__main__.ABC object at 0x8c99eec>}
So clearly loading the ABC object worked fine. I think the problem is that you
have a name clash between your module `abc` and the module called `abc` in the
standard library, and that this name clash behaves differently in Python 2 and
Python 3.
Solution: **Rename your module.**
|
python Decimal precision
Question: For some reason Decimal object looses precision when multiplied. There is no
reason to happen so. Please check the testcase and enlighten me.
from decimal import *
getcontext().prec = 11
a = Decimal('5085.28725881485')
b = 1
print getcontext()
print 'a = '+str(a)
print 'b = '+str(b)
print 'a * b = '+str(a * b)
And the output:
Context(prec=11, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[DivisionByZero, InvalidOperation, Overflow])
a = 5085.28725881485
b = 1
a * b = 5085.2872588
Not sure if this is relevant, but python2.6 used.
Answer: The precision you specify in the context (11 places) is only applied when
performing _calculations_ , not when creating decimal.Decimal objects -- and
the result, `5085.2872588` does indeed obey that limit. Using `1` as the
multiplier does not change the rules with regards to precision; the result of
arithmetic operations always considers the precision.
If you were instead looking for `decimal.Decimal` to return a number rounded
to a particular number of places, the `create_decimal` method of the context
object will do that for you.
|
How to sign a string under iOS using encrypted key?
Question: I have keys created in Java. The private key is PKCS#8 encrypted, in PEM
string.
Here is an example of using the private key with M2Crypto in Python:
from M2Crypto import EVP, BIO
privpem = "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIICoTAbBgoqhkiG9w0BDAEDMA0ECFavEvdkv3fEAgEUBIICgAWvHvH6OktLiaaqo9v+X6XEuY3M\nZr465VmZWzP9nsbTqwSKQQjseiD/rWAxK7RS+V+hit5ZxlNRAUbkg0kwl8SRNX3v6q8noJtcB0OY\ndBEuNJDmWHMHh8qcnfRYc9WXPPmWdjQM2AkfZNfNOxHVlOMhancScy6P4h3Flri9VyUE8w2/zZqK\nBAd2w39V7gprCQXnnNenNuvr4p8MjsdBm8jh00o2HJzN0I6u+9s7M3qLXxwxNepptgU6Qt6eKHi6\njpsV/musVaohLhFMFAzQ87FeGvz/W8dyS9BtAKMRSuDu/QdWIJMRNKkPT0Tt1243V3tzXVXLjz0u\nm/FX6kfxL8r+eGtTr6NKTG75TJfooQzN/v08OEbmvYD/mfptmZ7uKezOGxDmgynn1Au7T/OxKFhx\nWZHpb9OFPIU0uiriUeyY9sbDVJ054zQ/Zd5+iaIjX5RsLoB4J+pfr4HuiVIZVj+Ss2rnPsOY3SjM\ntbHIFp/fLr/HODcDA5eYADRGpBIL9//Ejgzd7OqpU0mdajzZHcMTjeXfWB0cc769bFyHb3Ju1zNO\ng4gNN1H1kOMAXMF7p6r25f6v1BRS6bQyyiFz7Hs7h7JBylbBAgQJgZvv9Ea3XTMy+DIPMdepqu9M\nXazmmYJCtdLAfLBybWsfSBU5K6Pm6+Bwt6mPsuvYQBrP3h84BDRlbkntxUgaWmTB4dkmzhMS3gsY\nWmHGb1N+rn7xLoA70a3U/dUlI7lPkWBx9Sz7n8JlH3cM6jJUmUbmbAgHiyQkZ2mf6qo9qlnhOLvl\nFiG6AY+wpu4mzM6a4BiGMNG9D5rnNyD16K+p41LsliI/M5C36PKeMQbwjJKjmlmWDX0=\n-----END ENCRYPTED PRIVATE KEY-----\n"
msg = "This is a message."
privkeybio = BIO.MemoryBuffer(privpem)
privkey = EVP.load_key_bio(privkeybio) #pw: 123456
privkey.sign_init()
privkey.sign_update(msg)
print privkey.sign_final().encode('base64')
And here is example of how I can use the PEM (with header and footer stripped
off) in Java:
String msg = "This is a message.";
String privpem = "MIICoTAbBgoqhkiG9w0BDAEDMA0ECFavEvdkv3fEAgEUBIICgAWvHvH6OktLiaaqo9v+X6XEuY3M\nZr465VmZWzP9nsbTqwSKQQjseiD/rWAxK7RS+V+hit5ZxlNRAUbkg0kwl8SRNX3v6q8noJtcB0OY\ndBEuNJDmWHMHh8qcnfRYc9WXPPmWdjQM2AkfZNfNOxHVlOMhancScy6P4h3Flri9VyUE8w2/zZqK\nBAd2w39V7gprCQXnnNenNuvr4p8MjsdBm8jh00o2HJzN0I6u+9s7M3qLXxwxNepptgU6Qt6eKHi6\njpsV/musVaohLhFMFAzQ87FeGvz/W8dyS9BtAKMRSuDu/QdWIJMRNKkPT0Tt1243V3tzXVXLjz0u\nm/FX6kfxL8r+eGtTr6NKTG75TJfooQzN/v08OEbmvYD/mfptmZ7uKezOGxDmgynn1Au7T/OxKFhx\nWZHpb9OFPIU0uiriUeyY9sbDVJ054zQ/Zd5+iaIjX5RsLoB4J+pfr4HuiVIZVj+Ss2rnPsOY3SjM\ntbHIFp/fLr/HODcDA5eYADRGpBIL9//Ejgzd7OqpU0mdajzZHcMTjeXfWB0cc769bFyHb3Ju1zNO\ng4gNN1H1kOMAXMF7p6r25f6v1BRS6bQyyiFz7Hs7h7JBylbBAgQJgZvv9Ea3XTMy+DIPMdepqu9M\nXazmmYJCtdLAfLBybWsfSBU5K6Pm6+Bwt6mPsuvYQBrP3h84BDRlbkntxUgaWmTB4dkmzhMS3gsY\nWmHGb1N+rn7xLoA70a3U/dUlI7lPkWBx9Sz7n8JlH3cM6jJUmUbmbAgHiyQkZ2mf6qo9qlnhOLvl\nFiG6AY+wpu4mzM6a4BiGMNG9D5rnNyD16K+p41LsliI/M5C36PKeMQbwjJKjmlmWDX0=";
byte [] privkeybytes = Base64.decode(privpem);
EncryptedPrivateKeyInfo encprivki = new EncryptedPrivateKeyInfo(privkeybytes);
Cipher cipher = Cipher.getInstance(encprivki.getAlgName());
PBEKeySpec pbeKeySpec = new PBEKeySpec("123456".toCharArray());
SecretKeyFactory secFac = SecretKeyFactory.getInstance(encprivki.getAlgName());
Key pbeKey = secFac.generateSecret(pbeKeySpec);
AlgorithmParameters algParams = encprivki.getAlgParameters();
cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
KeySpec pkcs8KeySpec = encprivki.getKeySpec(cipher);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey pk = kf.generatePrivate(pkcs8KeySpec);
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initSign(pk);
sig.update(msg.getBytes("UTF8"));
byte[] signatureBytes = sig.sign();
String b = Base64.encodeBytes(signatureBytes, Base64.DO_BREAK_LINES);
System.out.println(b); // Display the string.
How would this be done in iOS? I have looked at the CryptoExercise, in
particular the SecKeyWrapper, but there is lots going on there, and it's
beyond me.
I am not personally going to be doing the iOS development, but I need some
code to give to the developer to at least show more or less how to do it. The
developer is more a UI type and not familiar with crypto. (Neither am I but
that is a different story...)
And while we're at it, how to verify a signature against a string public key
PEM? I won't put the Java and Python examples here as they are pretty straight
forward.
Answer: I had the same problem last week. The CommonCrypt library on iOS is very nice
for symmetric key encryption, but it's just too much hassle dealing with the
keyring to do simple public key things. After spending about half an hour
poking at it I just included OpenSSL. [OpenSSL-
Xcode](https://github.com/sjlombardo/openssl-xcode) made this trivial to set
up - just drop the project and the OpenSSL tarball in, set your target to link
with libssl, and you're good to go.
The OpenSSL code looks nearly the same as the M2Crypto one.
|
Python Strategy pattern: Dynamically import class files
Question: I am trying to build a software package that fixes arbitrary data
inconsistencies in one of my databases. My design includes two classes -
`Problem` and `Fix`.
The problems are SQL queries stored as `.cfg` files (e.g. `problem_001.cfg`),
and the fixers are stored as Python files (e.g. `fix_001.py`). The query
config file has a reference to the Python file name. Each fixer has a single
class `Fix`, which inherits from a base class `BaseFix`.
`-- problems
|-- problem_100.cfg
|-- problem_200.cfg
|-- problem_300.cfg
`-- ...
`-- fixer
|-- __init__.py
| |-- fixers
| | |-- fix_100.py
| | |-- fix_200.py
| | |-- fix_300.py
| | |-- ...
| `-- ...
`-- ...
I would like to instantiate `Problem` files and supply them with `Fix` objects
in a clean way. Is there a way to do it without keepping all the fixers in the
same file?
**UPDATE:**
This is the final code that worked (thanks, @Space_C0wb0y):
fixer_name='fix_100'
self.fixer=__import__('fixer.fixers', globals(), locals(),
[fixer_name]).__dict__[fixer_name].Fix()
Answer: You can dynamically import modules using the builtin `__import__`, which takes
the module-name as string-argument (see
[here](http://diveintopython.net/functional_programming/dynamic_import.html)).
The modules do have to be in the [module search
path](http://docs.python.org/tutorial/modules.html#the-module-search-path).
|
python matplotlib colorbar setting tick formator/locator changes tick labels
Question: users, I want to customize the ticks on a colorbar. However, I found the
following strange behavior. I try to change the tick formator to the default
formator (I thought this should change nothing at all) but I end up with
different labels. Does anybody know what I am doing wrong? Or is this a bug?
I use matplotlib from git (v1.0.1-961-gb516ae0 , git describe). The following
code produces the two plots:
#http://matplotlib.sourceforge.net/examples/pylab_examples/griddata_demo.html
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np
# make up data.
seed(0)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = x*np.exp(-x**2-y**2)
# define grid
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,200)
# grid the data.
zi = griddata(x,y,z,xi,yi,interp='linear')
##### FIRST PLOT
plt.figure()
CS = plt.contour(xi,yi,zi,25,cmap=plt.cm.jet)
bar = plt.colorbar() # draw colorbar
# plot data points.
#plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()
##### SECOND PLOT
plt.figure()
CS = plt.contour(xi,yi,zi,25,cmap=plt.cm.jet)
bar = plt.colorbar() # draw colorbar
bar.ax.yaxis.set_minor_locator(matplotlib.ticker.AutoLocator())
bar.ax.yaxis.set_major_locator(matplotlib.ticker.AutoLocator())
# plot data points.
#plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()
Answer: I just found the solution. One has to call
bar.update_ticks()
after the formators/locators are changed, see
<http://matplotlib.sourceforge.net/api/colorbar_api.html>
Then everything works well.
Update:
Here is also the code which changes the Formator/Locator. It is based on the
internal structure of the colorbar-code, so maybe someone else has a better
solution:
#http://matplotlib.sourceforge.net/examples/pylab_examples/griddata_demo.html
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np
# make up data.
seed(0)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = x*np.exp(-x**2-y**2)
# define grid
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,200)
# grid the data.
zi = griddata(x,y,z,xi,yi,interp='linear')
##### PLOT
plt.figure()
CS = plt.contour(xi,yi,zi,25,cmap=plt.cm.jet)
bar = plt.colorbar(orientation='horizontal') # draw colorbar
tick_locs = [-3.9e-1,-2.6e-1,-1.3e-1,0e-1,1.3e-1,2.6e-1,3.9e-1]
tick_labels = ['-0.390','-0.260','-0.130','0','0.13','0.26','0.390']
bar.locator = matplotlib.ticker.FixedLocator(tick_locs)
bar.formatter = matplotlib.ticker.FixedFormatter(tick_labels)
bar.update_ticks()
# plot data points.
#plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()
|
Numpy Array to base64 and back to Numpy Array - Python
Question: I am now trying to figure out how I can recover a numpy array from base64
data. This question and answer suggest it is possible: [Reading numpy arrays
outside of Python](http://stackoverflow.com/questions/2725602/reading-numpy-
arrays-outside-of-python) but an example is not given.
Using the code below as an example, how can I get a Numpy array from the
base64 data if I know the dtype and the shape of the array?
import base64
import numpy as np
t = np.arange(25, dtype=np.float64)
s = base64.b64encode(t)
r = base64.decodestring(s)
q = ?????
I want a python statement to set q as a numpy array of dtype float64 so the
result is an array identical to t. This is what the arrays encoded and decoded
look like:
>>> t = np.arange(25,dtype=np.float64)
>>> t
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.,
11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21.,
22., 23., 24.])
>>> s=base64.b64encode(t)
>>> s
'AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxAAAAAAAAALkAAAAAAAAAwQAAAAAAAADFAAAAAAAAAMkAAAAAAAAAzQAAAAAAAADRAAAAAAAAANUAAAAAAAAA2QAAAAAAAADdAAAAAAAAAOEA='
>>> r = base64.decodestring(s)
>>> r
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x18@\x00\x00\x00\x00\x00\x00\x1c@\x00\x00\x00\x00\x00\x00 @\x00\x00\x00\x00\x00\x00"@\x00\x00\x00\x00\x00\x00$@\x00\x00\x00\x00\x00\x00&@\x00\x00\x00\x00\x00\x00(@\x00\x00\x00\x00\x00\x00*@\x00\x00\x00\x00\x00\x00,@\x00\x00\x00\x00\x00\x00.@\x00\x00\x00\x00\x00\x000@\x00\x00\x00\x00\x00\x001@\x00\x00\x00\x00\x00\x002@\x00\x00\x00\x00\x00\x003@\x00\x00\x00\x00\x00\x004@\x00\x00\x00\x00\x00\x005@\x00\x00\x00\x00\x00\x006@\x00\x00\x00\x00\x00\x007@\x00\x00\x00\x00\x00\x008@'
>>> q = np.array( ????
The reason I am asking is because I am working on a project where I would like
to store a lot of Numpy arrays in a MySQL database in an app powered by
django.
Using this django snippet I can store base64 data in a textfield:
<http://djangosnippets.org/snippets/1669/>
I want to write the arrays to the database as base64 instead of converting the
arrays to a string of unicode.
Thanks for your help.
Answer:
import base64
import numpy as np
t = np.arange(25, dtype=np.float64)
s = base64.b64encode(t)
r = base64.decodestring(s)
q = np.frombuffer(r, dtype=np.float64)
print(np.allclose(q, t))
# True
|
About insert shell commands into python
Question: I've inserted some shell commands into python script like below:
#!/usr/bin/python
import os,sys,re
import gzip
import commands
path = "/home/x/nearline"
for file in os.listdir(path):
if re.match('.*\.recal.fastq.gz', file):
fullpath = os.path.join(path, file)
result = commands.getoutput('zcat fullpath |wc -l')
numseqs = int(result)/4.0
print numseqs
`zcat fullpath |wc -l` is the shell command inserted.
Problem is, I define `fullpath` here for all `fastq` files, but after being
put under `' '`, seems this `fullpath` doesn't work. How can I solve this
problem?
Answer: You have to concatenate the string with the value of the variable:
result = commands.getoutput('zcat ' + fullpath + ' |wc -l')
|
Synthesize musical notes (with piano sounds) in Python
Question: I would like to have a python implementation of a musical instrument library
(for instance, a piano object) that I can use to convert a list of notes and a
duration into sound. For instance, something like:
import Piano
pn = Piano()
pn.play([note, note, ..., note], duration)
Does something like this exist for python 2.7? I would like to implement it if
it doesn't. I currently have something that uses audiere, but its just sine
waves so it sounds horrible. Is there any way to hook into a midi piano or
something like that- I am using windows 7? Are there any implementing steps
that I might not expect?
Answer: A subset of @Marcelos answer: <http://code.google.com/p/mingus/>
> mingus is a package for Python used by programmers, musicians, composers and
> researchers to make and investigate music. **At the core of mingus is music
> theory, which includes topics like intervals, chords, scales and
> progressions**.
>
> The MIDI package can save and load MIDI files, and -last but not least-
> provides a general purpose sequencer for all the containers and a FluidSynth
> sequencer subclass. **This allows you to play all your data structures
> straight from Python in just a couple of lines**. Most of the icky timing
> and MIDI code has been abstracted away for you, leaving a clean, relatively
> simple API.
|
python urllib2 question
Question: I am trying to print some info from an url, but I want to skip the print if a
certain text if found, I have:
import urllib2
url_number = 1
url_number_str = number
a = 1
while a != 10:
f = urllib2.urlopen('http://example.com/?=' + str(url_number_str)
f_contents = f.read()
if f_contents != '{"Response":"Parse Error"}':
print f_contents
a += 1
url_number_str += 1
so {"Response":"Parse Error"} is the text that I want to find to avoid
printing f.read() and load the NEXT url (Number 2)
Answer: Although your question is a bit unclear, try this:
f = urllib2.urlopen('http://example.com/?id=1000')
for line in f.readlines():
if line != '{"Response":"Parse Error"}':
print line
This loops over every line in the webpage, and stops at `'{"Response":"Parse
Error"}'`.
Edit: Nevermind, this is probably what you want:
f = urllib2.urlopen('http://example.com/?id=1000')
data = f.read()
if data != '{"Response":"Parse Error"}':
print data
This will print the entire webpage, unless it is `'{"Response":"Parse
Error"}'`.
|
Why am I getting "Exception: (404, u'Not Found')" with Suds
Question: I am trying to connect to SugarCRM soap services (what's the correct
terminology?) using Suds:
from suds.client import Client
url = "http://localhost/sugarcrm/soap.php?wsdl"
client = Client(url)
session = client.service.login("usr", "pwd")
But the very last line throws an exception:
ERROR:suds.client:<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns3="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns0="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://www.sugarcrm.com/sugarcrm" xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Header/>
<ns2:Body>
<ns1:login>
<user_auth xsi:type="ns1:user_auth">usr</user_auth>
<application_name xsi:type="ns3:string">pwd</application_name>
</ns1:login>
</ns2:Body>
</SOAP-ENV:Envelope>
Traceback (most recent call last):
File "python.py", line 5, in <module>
session = client.service.login("usr", "pwd")
File "/usr/lib/pymodules/python2.6/suds/client.py", line 542, in __call__
return client.invoke(args, kwargs)
File "/usr/lib/pymodules/python2.6/suds/client.py", line 602, in invoke
result = self.send(soapenv)
File "/usr/lib/pymodules/python2.6/suds/client.py", line 653, in send
result = self.failed(binding, e)
File "/usr/lib/pymodules/python2.6/suds/client.py", line 714, in failed
raise Exception((status, reason))
Exception: (404, u'Not Found')
Answer: Try passing also the argument `location=url` to the `Client` constructor.
Sometimes the location element in WSDLs doesn't match up with URI on the
server.
client = Client(url, location=url)
|
Python: binary file to gz file and then to jpg extension and finally return again to the original binary file
Question: I want to do the following in Python:
1. Take a binary (executable) file
2. Turn it into a zip file with gzip (gz extension)
3. Then put the jpg extension
Later again the desire to recover the original (without the gz extension or
jpg).
The idea is to send binary files through GMail SMTP to recover and then get
them over IMAP and process them in ehtir original form (1).
Answer: You can use [`gzip`](http://docs.python.org/library/gzip.html) to compress the
files and
[`os.rename`](http://docs.python.org/library/os.html?highlight=os.rename#os.rename)
to change file names. In your case you could just use `gzip` and save it with
a `.jpg` extension in the first place.
import gzip
# write compressed file
with gzip.open('my_file.jpg', 'wb') as f:
f.write(content)
# read it again
with gzip.open('my_file.jpg', 'rb') as f:
content = f.read()
|
Accept a range of numbers in the form of 0-5 using Python's argparse?
Question: Using argparse, is there a way to accept a range of numbers and convert them
into a list?
For example:
python example.py --range 0-5
Is there some way input a command line argument in that form and end up with:
args.range = [0,1,2,3,4,5]
And also have the possibility to input `--range 2 = [2]`?
Answer: You could just write your own parser in the `type` argument, e.g.
from argparse import ArgumentParser, ArgumentTypeError
import re
def parseNumList(string):
m = re.match(r'(\d+)(?:-(\d+))?$', string)
# ^ (or use .split('-'). anyway you like.)
if not m:
raise ArgumentTypeError("'" + string + "' is not a range of number. Expected forms like '0-5' or '2'.")
start = m.group(1)
end = m.group(2) or start
return list(range(int(start,10), int(end,10)+1))
parser = ArgumentParser()
parser.add_argument('--range', type=parseNumList)
args = parser.parse_args()
print(args)
~$ python3 z.py --range m
usage: z.py [-h] [--range RANGE]
z.py: error: argument --range: 'm' is not a range of number. Expected forms like '0-5' or '2'.
~$ python3 z.py --range 2m
usage: z.py [-h] [--range RANGE]
z.py: error: argument --range: '2m' is not a range of number. Expected forms like '0-5' or '2'.
~$ python3 z.py --range 25
Namespace(range=[25])
~$ python3 z.py --range 2-5
Namespace(range=[2, 3, 4, 5])
|
GUI interface for sqlite data entry in Python
Question: I am making a simple sqlite database for storing some non-sensitive client
information. I am very familiar with python+sqlite and would prefer to stick
with this combo on this project. I would like to create an simple GUI
interface for data entry and searching of the database... something very
similar to what MS Access provides. I want my wife to be able to enter/search
data easily, so PHPmyadmin style things are out of the question.
I understand I could just give in and get MS Access, but if reasonbly possible
would rather just write the code myself so it will run on my computers (*nix)
and is flexible (so I can later integrate it with a web application and our
smart phones.)
Can you developers recommend any interfaces/packages/etc (preferably pythonic)
that can accomplish this with reasonable ease?
Thanks!
Answer: Since you're interested in future integration with a web application, you
might consider using a Python web framework and running the app locally on
your machine, using your web browser as the interface. In that case, one easy
option would be [web2py](http://www.web2py.com). Just
[download](http://www.web2py.com/examples/default/download), unzip, and run,
and you can use the web-based IDE
([demo](http://www.web2py.com/demo_admin/default/site)) to create a simple
CRUD app very quickly (if you really want to keep it simple, you can even use
the "New application wizard"
([demo](http://www.web2py.com/demo_admin/wizard/index)) to build the app). It
includes its own server, so you can run your app locally, just like a desktop
app.
You can use the web2py [DAL](http://web2py.com/book/default/chapter/06)
(database abstraction layer) to define and create your SQLite database and
tables (without writing any SQL). For example:
db = DAL('sqlite://storage.db')
db.define_table('customer',
Field('name', requires=IS_NOT_IN_DB(db, 'customer.name')),
Field('address'),
Field('email', requires=IS_EMAIL()))
The above code will create a SQLite database called storage.db and create a
table called 'customer'. It also specifies form validators for the 'name' and
'email' fields, so whenever those fields are filled via a form, the entries
will be validated ('name' cannot already be in the DB, and 'email' must be a
valid email address format) -- if validation fails, the form will display
appropriate error messages (which can be customized).
The DAL will also handle schema
[migrations](http://web2py.com/book/default/chapter/06#Migrations)
automatically, so if you change your table definitions, the database schema
will be updated (if necessary, you can turn off migrations completely or on a
per table basis).
Once you have your data models defined, you can use web2py's
[CRUD](http://web2py.com/book/default/chapter/07#CRUD) system to handle all
the data entry and searching. Just include these two lines (actually, they're
already included in the 'welcome' scaffolding application):
from gluon.tools import Crud
crud = Crud(db)
And in a controller, define the following action:
def data():
return dict(form=crud())
That will expose a set of pre-defined URLs that will enable you to create,
list, search, view, update, and delete records in any table.
Of course, if you don't like some of the default behavior, there are lots of
ways to customize the CRUD forms/displays, or you can use some of web2py's
other [forms functionality](http://web2py.com/book/default/chapter/07) to
build a completely custom interface. And web2py is a full-stack framework, so
it will be easy to add functionality to your app as your needs expand (e.g.,
access control, notifications, etc.).
Note, web2py requires no installation or configuration and has no
dependencies, so it's very easy to distribute your app to other machines --
just zip up the entire web2py folder (which will include your app folder) and
unzip it on another machine. It will run on *nix, Mac, and Windows (on
Windows, you will either need to install Python or download the web2py Windows
binary instead of the source version -- the Windows binary includes its own
Python interpreter).
If you have any questions, there's a very helpful and responsive [mailing
list](https://groups.google.com/forum/?fromgroups#!forum/web2py). You might
also get some ideas from some existing [web2py
applications](http://web2py.com/appliances).
|
Tornado's AsyncHTTPClient no longer works after upgrade to 2.0 from 1.2
Question: Decided I'd kick the tires of Tornado 2.0 tonight, but it appears to have done
a number on ASyncHTTPClient for me. Nothing in the release notes for 2.0
indicates any real changes are necessary to how I'm using ASyncHTTPClient:
**[EDIT: made the code more of an explicit, self-containing example ]**
import time
import threading
import functools
import tornado.ioloop
import tornado.web
from tornado.httpclient import *
class MainHandler(tornado.web.RequestHandler):
def perform_task(self,finish_function):
http_client = AsyncHTTPClient()
tornado.ioloop.IOLoop.instance().add_callback(finish_function)
# do something
for i in range(0,10):
print i
time.sleep(1)
request = tornado.httpclient.HTTPRequest("http://10.0.1.5:8888",method="POST",body="finished countdown")
resp = http_client.fetch(request, self.handle_request)
return
def join_callback(self):
# finish the request, also returns control back to ioloop's thread.
self.finish()
def handle_request(self, response):
if response.error:
print "Error:", response.error
else:
print response.body
@tornado.web.asynchronous
def get(self):
self.write("Kicking off.")
a_partial = functools.partial(self.perform_task,self.join_callback)
self.thread = threading.Thread(target=a_partial)
self.thread.start()
self.write("\n<br/>Done in here, out of my hands now.")
# just so this example has something to post to
@tornado.web.asynchronous
def post(self):
self.write("POSTED: %s" % (self.request.body))
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
when using the default (non-curl) ASyncHTTPClient I get the following:
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/tornado/simple_httpclient.py", line 259, in cleanup
yield
File "/usr/local/lib/python2.6/dist-packages/tornado/simple_httpclient.py", line 186, in __init__
functools.partial(self._on_connect, parsed))
File "/usr/local/lib/python2.6/dist-packages/tornado/iostream.py", line 120, in connect
self.socket.connect(address)
AttributeError: 'NoneType' object has no attribute 'connect'
if I add in:
tornado.httpclient.AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
to specify I want to use PyCurl, I get the following exception:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/usr/lib/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
File "migratotron.py", line 46, in perform_migration
hc.fetch(request,success)
File "/usr/local/lib/python2.6/dist-packages/tornado/curl_httpclient.py", line 81, in fetch
self._process_queue()
File "/usr/local/lib/python2.6/dist-packages/tornado/curl_httpclient.py", line 210, in _process_queue
curl.info["headers"])
File "/usr/local/lib/python2.6/dist-packages/tornado/curl_httpclient.py", line 276, in _curl_setup_request
curl.setopt(pycurl.URL, request.url
)
TypeError: invalid arguments to setopt
The only thing unusual I'm doing is calling this is another thread I created
to do some background processing, which uses add_callback to return control to
the ioloop thread. Has anyone seen this with 2.0 or anything like it?
Answer: Those error messages are a bit cryptic, but in both cases I think they're due
to your request not having a URL (unless `callback` is a URL).
2.0 switched the ASyncHTTPClient implementation to simple_httpclient (from
curl_httpclient), but I don't think the example given would have worked in
Tornado 1.2 either.
|
Need more efficient way to parse out csv file in Python
Question: Here's a sample csv file
id, serial_no
2, 500
2, 501
2, 502
3, 600
3, 601
This is the output I'm looking for (list of serial_no withing a list of ids):
[2, [500,501,502]]
[3, [600, 601]]
I have implemented my solution but it's too much code and I'm sure there are
better solutions out there. Still learning Python and I don't know all the
tricks yet.
file = 'test.csv'
data = csv.reader(open(file))
fields = data.next()
for row in data:
each_row = []
each_row.append(row[0])
each_row.append(row[1])
zipped_data.append(each_row)
for rec in zipped_data:
if rec[0] not in ids:
ids.append(rec[0])
for id in ids:
for rec in zipped_data:
if rec[0] == id:
ser_no.append(rec[1])
tmp.append(id)
tmp.append(ser_no)
print tmp
tmp = []
ser_no = []
**I've omitted var initializing for simplicity of code
print tmp
Gives me output I mentioned above. I know there's a better way to do this or
pythonic way to do it. It's just too messy! Any suggestions would be great!
Answer:
from collections import defaultdict
records = defaultdict(list)
file = 'test.csv'
data = csv.reader(open(file))
fields = data.next()
for row in data:
records[row[0]].append(row[1])
#sorting by ids since keys don't maintain order
results = sorted(records.items(), key=lambda x: x[0])
print results
If the list of serial_nos need to be unique just replace `defaultdict(list)`
with `defaultdict(set)` and `records[row[0]].append(row[1])` with
`records[row[0]].add(row[1])`
|
Looping in Python and keeping current line after sub routine
Question: I've been trying to nut out an issue when looping in python 3. When returning
from sub routine the "line" variable has not incremented.
How do I get the script to return the latest readline from the subsroutine?
Code below
def getData(line):
#print(line)
#while line in sTSDP_data:
while "/service/content/test" not in line:
line = sTSDP_data.readline()
import os, sys
sFileTSDP = "d:/ess/redo/Test.log"
sTSDP_data = open(sFileTSDP, "r")
for line in sTSDP_data:
if "MOBITV" in line:
getData(line) #call sub routine
print(line)
I'm stepping through a large file and on a certain string I need to call a sub
routine to process the next 5 (or 100) lines of data. When the sub routine
completes and returns to the main program, it would be better to have it
continue on from the last readline in the sub routine, not the last readline
in the main program.
Daan's answer did the trick.
Answer: How about using a return statement?
def getData(line):
#print(line)
#while line in sTSDP_data:
while "/service/content/test" not in line:
line = sTSDP_data.readline()
return line
import os, sys
sFileTSDP = "d:/ess/redo/Test.log"
sTSDP_data = open(sFileTSDP, "r")
for line in sTSDP_data:
if "MOBITV" in line:
line = getData(line) #call sub routine
print(line)
Beware the scope of your variables. The 'line' in your getData function is not
the same as the 'line' in your loop.
|
Class referencing Error - sometimes an issue
Question: Okay so I did not know what to search for in order to answer this question.
In my code for some reason some of my classes can be referenced as per
instructions by Python
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
x = MyClass()
In my code I have imported my custom python modules using
import [custom module]
from [custom module] import *
next I make a reference to the class
classRef = [classfunction]()
Below is my actual code, this module is called "main.py"
from Tkinter import *
import os, sys
import Tkinter, tkFileDialog
from tkFileDialog import *
from openpyxl.reader.excel import load_workbook
from openpyxl.workbook import Workbook
#custom python classes
import reader
import searchDog
from searchDog import *
from reader import *
class appGUI:
def __init__(self,frame):
#set windows size 600 by 300
#frame = Tk()
frame.geometry("600x300+30+30")
self.openExcel = Button(frame, text = "Open Defect Excel", command = lambda: self.openExcelFile())
self.openExcel.place(x=10,y=10,width=100,height=25)
self.openDefectTextFile = Button(frame, text ="Open Text File", command = lambda: self.openDefectText())
self.openDefectTextFile.place(x=10,y=40,width=100,height=25)
self.startButton = Button(frame, text="Start",command = lambda: self.startLoadProcess())
self.startButton.place(x=10,y=70,width=100,height=25)
def openExcelFile(self):
self.openTemp = tkFileDialog.askopenfilename(parent = root, title = 'Select Defect Excel File')
def openDefectText(self):
self.openDefect = tkFileDialog.askopenfilename(parent = root, title= 'Select Defect Text File')
def start(self):
self.startLoadProcess()
def startLoadProcess(self):
#text file where defect comments are stored
filePath = self.openDefect
#keyword condition to search for
keyword = "18360" #probably will put this in a loop
#create an instance of ReadFile from searchDog
readInText = ReadFile()
keywordSearch = searchFile()
#----End searchDog Reference
#create an instance of readExcel from ExcelFileHandle
i = 2
#searches for and writes the comments into a text file
while self.readData(i, 2, self.openTemp) != None:
keywordSearch.searchForKeywordText(self.readData(i,2,self.openTemp), filePath,i) #searchDog Function
self.loadExcelFile.save(self.openTemp)
i += 1
def readData(self,inputRow,inputColumn,excelFilePath):
'''
Constructor
'''
self.loadExcelFile = load_workbook(filename = self.openTemp)
self.excelWorksheet = self.loadExcelFile.get_sheet_by_name('Defects')
self.rowInput = inputRow
self.columnInput = inputColumn
self.cellValue = self.excelWorksheet.cell(row=self.rowInput,column=self.columnInput).value
return self.cellValue, inputRow
root = Tk()
app = appGUI(root)
root.mainloop()
the next module is called excelWiteIn.py
#built in modules from python
from openpyxl.reader.excel import load_workbook
from openpyxl.workbook import Workbook
#my custom modules from the project
import searchDog
import main
class excelWriteInClass():
'''
writes data coming from searchDog into Defects page
'''
def writeToExcelFile(self,textLine,writeRow):
'''
Constructor
'''
self.searchDogRef = searchFile()
self.appGuiRef = appGUI()
self.excelDefectWorksheet = self.appGuiRef.loadExcelFile.get_sheet_by_name('Defects')
self.excelDefectWorksheet.cell(row= writeRow, column = 11).value = textLine
the error I get is that the my reference is not defined specifically at this
line:
self.searchDogRef = searchFile()
self.appGuiRef = appGUI()
I don't understand why sometimes referencing classes work and sometimes they
do not. Is this a PyDev glitch, is it an Eclipse glitch?
***Computer Information:
Eclipse V. Version: 3.6.2 Build id: M20110210-1200
Compiling under Python 2.7
- installed modules --> openPyxl
using Latest PyDev plugin downloaded from Eclipse Market***
Answer: If i correctly understood you then the problem is that you are using
import/from .. import incorrectly. First of all there is no need to use both
'import module' and right after that call 'from module import ...'.
Modify main.py:
import os, sys
from tkFileDialog import <put here what you really need>
from Tkinter import <put here what you really need>
from openpyxl.reader.excel import load_workbook
from openpyxl.workbook import Workbook
#custom python classes
from searchDog import <put here what you really need>
from reader import <put here what you really need>
Modify excelWiteIn.py:
from main import appGUI
from searchDog import searchFile
#OR
self.searchDogRef = main.searchFile()# in case searchFile specified within main.py otherwise you need to specify proper path to module that contains it
self.appGuiRef = main.appGUI()# note that you have to add 'frame' here
EDITED - putting here you main.py with small fixes and questions/comments:
import os, sys # not used
from Tkinter import Tk, Button
from tkFileDialog import askopenfilename
from openpyxl.reader.excel import load_workbook
from openpyxl.workbook import Workbook
#custom python classes
from searchDog import searchFile, ReadFile
from reader import <put here what you really need>
class appGUI(object):
def __init__(self, frame):
#set windows size 600 by 300
#frame = Tk()
frame.geometry("600x300+30+30")
self.openExcel = Button(frame, text = "Open Defect Excel", command = lambda: self.openExcelFile())
self.openExcel.place(x=10, y=10, width=100, height=25)
self.openDefectTextFile = Button(frame, text ="Open Text File", command = lambda: self.openDefectText())
self.openDefectTextFile.place(x=10, y=40, width=100, height=25)
self.startButton = Button(frame, text="Start",command = lambda: self.startLoadProcess())
self.startButton.place(x=10, y=70, width=100, height=25)
def openExcelFile(self):
# root? it not specified here
self.openTemp = askopenfilename(parent=root, title='Select Defect Excel File')
def openDefectText(self):
# root? it not specified here
self.openDefect = askopenfilename(parent=root, title='Select Defect Text File')
def start(self):
self.startLoadProcess()
def startLoadProcess(self):
#text file where defect comments are stored
filePath = self.openDefect
#keyword condition to search for
keyword = "18360" #probably will put this in a loop
#create an instance of ReadFile from searchDog
readInText = ReadFile()
keywordSearch = searchFile()
#----End searchDog Reference
#create an instance of readExcel from ExcelFileHandle
i = 2
#searches for and writes the comments into a text file
while self.readData(i, 2, self.openTemp):
keywordSearch.searchForKeywordText(self.readData(i, 2, self.openTemp), filePath, i) #searchDog Function
self.loadExcelFile.save(self.openTemp)
i += 1
# excelFilePath not used at all
def readData(self, inputRow, inputColumn, excelFilePath):
'''
Constructor
'''
# not sure that this is a good idea to load workbook each time
self.loadExcelFile = load_workbook(filename = self.openTemp)
self.excelWorksheet = self.loadExcelFile.get_sheet_by_name('Defects')
self.rowInput = inputRow
self.columnInput = inputColumn
self.cellValue = self.excelWorksheet.cell(row=self.rowInput, column=self.columnInput).value
return self.cellValue, inputRow
root = Tk()
app = appGUI(root)
root.mainloop()
|
Why the Segmentation Fault! When I attempt to run / use Python Package gensim?
Question: Am attempting to use `[gensim][1]`, a Vector Space Modelling package for
python in some Machine Learning experiments of mine. I followed their
installation instructions as said
[here](http://nlp.fi.muni.cz/projekty/gensim/install.html), though
installation of `scipy` on my OpenSuse 11.3 failed when using `easy_install`
as they recommend, so I resorted to installing it from a package available on
the Official package search portal
[here](http://software.opensuse.org/search?q=scipy&baseproject=openSUSE:11.3&lang=en&exclude_debug=true).
Installation of `scipy` went ok, and then I used `easy_install` to install
`gensim` as they recommend. Which also went ok.
Now, after installation, I attempted to run the very first example they give
of using the package, which starts with a humble import statement as follows:
from gensim import corpora, models, similarities
Lo! When I attempted to run that in my python interpreter, the dear thing
crashed with `Segmentation Fault`! This is what happened:
>>> from gensim import corpora, models, similarities
Segmentation fault
Someone save me, because I don't know where the error could possibly be coming
from.
I understand the segfault usually is due to illegal memory access by a
process, so could this be happening due to the import? or some error within
`gensim`?
For more info, it is said that after installing the package it can be tested,
so I did this to test my `gensim`, Lo! the same `Segmentation Fault`! Here is
the ouput:
python setup.py test
running test
running egg_info
writing requirements to gensim.egg-info/requires.txt
writing gensim.egg-info/PKG-INFO
writing top-level names to gensim.egg-info/top_level.txt
writing dependency_links to gensim.egg-info/dependency_links.txt
reading manifest file 'gensim.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching '*.sh' under directory '.'
writing manifest file 'gensim.egg-info/SOURCES.txt'
running build_ext
Segmentation fault
For the dependent packages, I have:
>>> numpy.version.version
'1.3.0'
>>> scipy.version.version
'0.8.0'
Ok, as requested in the comments, I did hook gdb to the interpreter, and then
tried the import statement again, then this is what gdb gave when the segfault
occurred again:
(gdb) continue
Continuing.
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/time.so
Try: zypper install -C "debuginfo(build-id)=da29868e88d517efc61eed319c4a87b41404f932"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/strop.so
Try: zypper install -C "debuginfo(build-id)=1a5723f070198420ae565b728f267f00ae7e9885"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/cStringIO.so
Try: zypper install -C "debuginfo(build-id)=d02dafc8dd403786b35ee44d946fc67461c7af34"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/_functools.so
Try: zypper install -C "debuginfo(build-id)=4d3d7d73a2d7abe3d4ac45bdc07a070abde67a3b"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/_collections.so
Try: zypper install -C "debuginfo(build-id)=86c7e2481ef3930f858927648d270a96ef65e0d9"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/operator.so
Try: zypper install -C "debuginfo(build-id)=ecdf6c9dfbb007d3698e4108e2412b575b14c3f0"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/unicodedata.so
Try: zypper install -C "debuginfo(build-id)=b84b2bd4061ce43b8fe6e7319d0e3fe90431f3f9"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/cPickle.so
Try: zypper install -C "debuginfo(build-id)=0cb3d3c8e51cd264b7fc0cfd6ad6cea7da6173f1"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/itertools.so
Try: zypper install -C "debuginfo(build-id)=88125d7ede2ef83a18e46901c9b7bd938d7554b9"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/_bisect.so
Try: zypper install -C "debuginfo(build-id)=e872da9d2f7456947a21d6cf8ac05115da084ee0"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/_heapq.so
Try: zypper install -C "debuginfo(build-id)=0c250b23be656b9984a8fbf67c232930141c6a79"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/math.so
Try: zypper install -C "debuginfo(build-id)=48f975758f43cffc37703cda98615cb2daaf8a08"
Missing separate debuginfo for /usr/lib/python2.6/site-packages/numpy/core/multiarray.so
Try: zypper install -C "debuginfo(build-id)=adcbae28e6012eecb870c60af4805f25554c9148"
Missing separate debuginfo for /usr/lib/python2.6/site-packages/numpy/core/umath.so
Try: zypper install -C "debuginfo(build-id)=1087f0837567a96e6db9fadb8258f21113173f01"
Missing separate debuginfo for /usr/lib/python2.6/site-packages/numpy/core/_sort.so
Try: zypper install -C "debuginfo(build-id)=c70e9c08253546b727376f7643cc9b6cc796465e"
Missing separate debuginfo for /usr/lib/python2.6/site-packages/numpy/core/scalarmath.so
Try: zypper install -C "debuginfo(build-id)=cbc4ec89676c6072f64ae92a2917548479141eee"
Missing separate debuginfo for /usr/lib/python2.6/site-packages/numpy/lib/_compiled_base.so
Try: zypper install -C "debuginfo(build-id)=6f71bf761290527c07afe78736211d2393caa95e"
Missing separate debuginfo for /usr/lib/python2.6/site-packages/numpy/linalg/lapack_lite.so
Try: zypper install -C "debuginfo(build-id)=ac2cb74a8a055e3d58e15f4ac0012159abbf7d1a"
Missing separate debuginfo for /usr/lib/liblapack.so.3
Try: zypper install -C "debuginfo(build-id)=5c9cf054c3e366ea04681d3c3b1e4d1fa8b46da5"
Missing separate debuginfo for /usr/lib/libblas.so.3
Try: zypper install -C "debuginfo(build-id)=c7ea0a3cdf0da62f1f07f81838207e6070e86449"
Missing separate debuginfo for /usr/lib/libgfortran.so.3
Try: zypper install -C "debuginfo(build-id)=6889f5fdc16cb8d7cb4d5e97c59080336c2e6e01"
Missing separate debuginfo for /lib/libgcc_s.so.1
Try: zypper install -C "debuginfo(build-id)=ea12a9f70518dd6b807755150f1d2c6ba8550fe1"
Missing separate debuginfo for /usr/lib/python2.6/site-packages/numpy/fft/fftpack_lite.so
Try: zypper install -C "debuginfo(build-id)=32599ba87256834ebc65a962e4718aa1f9134b0e"
Missing separate debuginfo for /usr/lib/python2.6/site-packages/numpy/random/mtrand.so
Try: zypper install -C "debuginfo(build-id)=e43ddcab2e8e2961f3ab58087ac55dffa4094993"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/_ctypes.so
Try: zypper install -C "debuginfo(build-id)=40cde5dd7ee47a3caac1ce1f94b6ef7fa28792ff"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/_struct.so
Try: zypper install -C "debuginfo(build-id)=a5c456fe75e29e3424d7881fc05be8321fa65707"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/binascii.so
Try: zypper install -C "debuginfo(build-id)=d3a2d6b38432a2b5076e238aef398cd3776bed20"
Missing separate debuginfo for /lib/libz.so.1
Try: zypper install -C "debuginfo(build-id)=afddd839a6c18dd308b04b5289c56cc3abd1384f"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/_random.so
Try: zypper install -C "debuginfo(build-id)=683d2819c1613d54dcd68c9169fc043ecb1b5444"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/fcntl.so
Try: zypper install -C "debuginfo(build-id)=aaabeb0dbb01b7a14698fd221d09fedc6de19521"
Missing separate debuginfo for /usr/lib/libjpeg.so.8
Try: zypper install -C "debuginfo(build-id)=5656b9563c388beee6e716dbe832ecb4480895ba"
Missing separate debuginfo for /usr/lib/python2.6/lib-dynload/array.so
Try: zypper install -C "debuginfo(build-id)=4e4aea1f2106d4a7a7b4dbd51199e337549b83e2"
Missing separate debuginfo for /usr/lib/libstdc++.so.6
Try: zypper install -C "debuginfo(build-id)=181385b3f6f58b2e13543468f07e08c5edd2cd86"
Program received signal SIGSEGV, Segmentation fault.
0x00000000 in ?? ()
Answer: You are probably trying to run a 64-bit binary (or use a 64-bit library) on a
32-bit system.
Use `python -v` when you run the task that produces the segmentation fault to
see if you can pinpoint where it is. If this isn't clear enough, then try
`strace python` instead of just `python`. If the segmentation fault appears
just after an attempt to "open" a .so file, then use a tool like `file` or
`readelf` to find out how many bits the binary or .so library requires.
If you have a 686 Linux then everything must be 32 bits. If you have an x86_64
Linux then it should all be 64 bits.
|
Obtaining loaded images from a given URL via Python
Question: Is there anyway to load a URL via Python and then retrieve a list of all of
the images that were loaded via that URL? I'm essentially looking to do
something similar to TamperData or Fiddler and retrieve a list of all images
that a given website loaded.
Answer: Interesting task. Here's one way of solving it, along the line suggested by
Jochen Ritzel.
It uses [pylibpcap](http://pylibpcap.sourceforge.net/) instead of
[pycap](http://pycap.sourceforge.net/). Personally, I find _pycap_ to be hard
to work with due to little amount of documentation available. For _pylibpcap_
, you can translate most code directly from the _libpcap_ examples (see for
example [this tutorial](http://www.tcpdump.org/pcap.html) for a nice
introduction). The man pages for [tcpdump](http://linux.die.net/man/8/tcpdump)
and [pcap](http://www.tcpdump.org/pcap3_man.html) are also great resources.
You may want to look at the standards for
[Ethernet](https://secure.wikimedia.org/wikipedia/en/wiki/Ethernet_frame),
[IPv4](https://secure.wikimedia.org/wikipedia/en/wiki/IPv4),
[TCP](https://secure.wikimedia.org/wikipedia/en/wiki/Tcp_protocol), and
[HTTP](https://secure.wikimedia.org/wikipedia/en/wiki/Http).
Note 1: The code below only prints out the HTTP _GET_ requests. Filtering out
the images and downloading them using the [urllib
module](http://docs.python.org/library/urllib.html) should pose no problem.
Note 2: This code works on Linux, not sure what device names you need to use
on Windows/MacOS. You'll also need root privileges.
#!/usr/bin/env python
import pcap
import struct
def parse_packet(data):
"""
Parse Ethernet/IP/TCP packet.
"""
# See the Ethernet, IP, and TCP standards for details.
data = data[14:] # Strip Ethernet header
header_length = 4 * (ord(data[0]) & 0x0f) # in bytes
data = data[header_length:] # Strip IP header
dest_port = struct.unpack('!H', data[2:4])[0]
if not dest_port == 80: # This is an outgoing package
return
header_length = 4 * ((ord(data[12]) & 0xf0) >> 4) # in bytes
data = data[header_length:] # Strip TCP header
return data
def parse_get(data):
"""
Parse a HTTP GET request, returning the request URI.
"""
if data is None or not data.startswith('GET'):
return
fields = data.split('\n')
uri = fields[0].split()[1]
for field in fields[1:]:
if field.lower().startswith('host:'):
return field[5:].strip() + uri
def packet_handler(length, data, timestamp):
uri = parse_get(parse_packet(data))
if not uri is None:
print uri
# Set up pcap sniffer
INTERFACE = 'wlan0'
FILTER = 'tcp port 80'
p = pcap.pcapObject()
p.open_live(INTERFACE, 1600, 0, 100)
p.setfilter(FILTER, 0, 0)
try:
while True:
p.dispatch(1, packet_handler)
except KeyboardInterrupt:
pass
|
Debugging a simple pygame game
Question: When I run this, it executes to an error in one of the imports. I posted the
error at tend end of the code. The program essentially doesn't run, I can't
tell what errors are occurring from the tracebacks. Any insight would be
appreciated.
from livewires import games, color
import random
games.init (screen_width = 640, screen_height = 480, fps = 50)
class Pizza (games.Sprite):
def __init__(self, screen, x, y, image):
self.pizzaimage = games.load_image ("pizza.bmp", transparent = True)
self.init_sprite (screen = screen,
x = x,
y = 90,
image = self.pizzaimage,
dy = 1)
def moved (self):
if self.bottom > 480:
self.game_over()
def handle_caught (self):
self.destroy()
def game_over(self):
games.Message(value = "Game Over",
size = 90,
color = color.red,
x = 320,
y = 240,
lifetime = 250,
after_death = games.screen.quit())
class Pan (games.Sprite):
def __init__(self, screen, x, image ):
self.panimage = games.load_image ("pan.bmp", transparent = True)
self.init_sprite (screen = screen,
x = games.mouse.x,
image = self.panimage)
self.score_value = 0
self.score_text = games.Text (value = "Score"+str(self.score_value),
size = 20,
color = color.black,
x = 500,
y = 20)
def update (self):
self.x = games.mouse.x
#When it reaches end, return value to corner. Example:
if self.left < 0:
self.left = 0
if self.right > 640:
self.right = 640
def handling_pizzas (self):
for Pizza in self.overlapping_sprites:
self.score_value += 10
Pizza.handle_caught()
class Chef (games.Sprite):
def __init__(self, screen, x, y, image, dx, dy,):
self.chefimage = games.load_image ("chef.bmp", transparent = True)
self.timer = 80
self.init_sprite (screen = screen,
x = random.randrange(640),
y = y,
dx = 20,
dy = 0)
def update (self):
if self.left < 0:
self.dx = -self.dx
if self.right > 640:
self.dx = -self.dx
elif random.randrange (10) == 5:
self.dx = -self.dx
def add_teh_pizzas (self):
if self.timer > 80:
self.timer = self.timer - 1
else:
new_pizza = Pizza (x = self.x)
games.screen.add (new_pizza)
self.timer = 80
#main
def main ():
backgroundwall = games.load_image ("wall.jpg", transparent = False)
games.screen.background = backgroundwall
le_chef = Chef = ()
games.screen.add(le_chef)
le_pan = Pan = ()
games.screen.add (le_pan)
games.mouse.is_visible = False
games.screen.event_grab = False
games.screen.mainloop()
main()
ERRORS REPORT:
Traceback (most recent call last):
File "C:\Users\COMPAQ\My Documents\Aptana Studio Workspace\Pythonic Things\PizzaPanicAttempt\PizzaPanicAttempt1.py", line 98, in <module>
main()
File "C:\Users\COMPAQ\My Documents\Aptana Studio Workspace\Pythonic Things\PizzaPanicAttempt\PizzaPanicAttempt1.py", line 96, in main
games.screen.mainloop()
File "C:\Python27\lib\site-packages\livewires\games.py", line 303, in mainloop
object._erase()
AttributeError: 'tuple' object has no attribute '_erase'
Answer: Don't know anything about _livewires_ , but the following looks suspicious:
le_chef = Chef = ()
games.screen.add(le_chef)
le_pan = Pan = ()
games.screen.add (le_pan)
You have classes called Chef, and Pan, but you're not doing anything with
these - just assigning these things an empty tuple, and then adding them to
games.screen. Were they supposed to be initialized instead?
eg.
le_chef = Chef(<some args>)
le_pan = Pan(<some args>)
|
Python Regular Expressions to extract date
Question: I have strings that look like these:
{server}_{date:YYYYMMDD}{int:######}
{server}_{date:MON DAY YYYY}{int:######}
...plus more, in different date formats. Also, there can be any number of {}
blocks, and they can appear in any order.
I'm trying to get just the "date" part between the curly braces in Python 3.2.
So for the first string, I want to get just "{date:YYYYMMDD}" and for the
second string I want just "{date:MON DAY YYYY}". The only characters I want
inside the "date" block are alpha and whitespace.
My regex pattern is:
\{date:(\w|\s)*\}
I've tested this out on [this Regex builder](http://gskinner.com/RegExr/ "this
Regex builder"), but it's not matching as expected. This is my output on
Python:
>>> import re
>>> re.findall('\{date:(\w|\s)*\}', '{server}_{date:YYYYMMDD}{date:MONDAYYYYY}{int:######}')
['D', 'Y']
>>> re.findall('\{date:(\w|\s)*\}', '{server}_{date:MON DAY YYYY}{int:######}')
['Y']
Can someone please point out what's wrong with my pattern?
Answer: `'(\{date:[\w\s]+\})'` gives what you want:
>>> import re
>>> re.findall('(\{date:[\w\s]+\})', '{server}_{date:YYYYMMDD}{date:MONDAYYYYY}{int:######}')
['{date:YYYYMMDD}', '{date:MONDAYYYYY}']
>>> re.findall('(\{date:[\w\s]+\})', '{server}_{date:MON DAY YYYY}{int:######}')
['{date:MON DAY YYYY}']
If you want only data value, use `'\{date:([\w\s]+)\}'`.
|
How to delete a s3 version from a bucket using boto and python
Question: When I try to delete a bucket using the lines:
conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
print conn.delete_Bucket('BucketNameHere').message
It tells me the bucket I tried to delete is not empty.
The bucket has no keys in it. But it does have versions.
How can I delete the versions?
I can see the list of versions using bucket.list_versions()
Java has a deleteVersion Method on its s3 connection. I found that code here:
<http://bytecoded.blogspot.com/2011/01/recursive-delete-utility-for-
version.html>
He does this line to delete the version:
s3.deleteVersion(new DeleteVersionRequest(bucketName, keyName, versionId));
Is there anything comparable in boto?
Answer: Boto does support versioned buckets after version 1.9c. Here's how it works:
import boto
s3 = boto.connect_s3()
#Create a versioned bucket
bucket = s3.create_bucket("versioned.example.com")
bucket.configure_versioning(True)
#Create a new key and make a few versions
key = new_key("versioned_object")
key.set_contents_from_string("Version 1")
key.set_contents_from_string("Version 2")
#Try to delete bucket
bucket.delete() ## FAILS with 409 Conflict
#Delete our key then try to delete our bucket again
bucket.delete_key("versioned_object")
bucket.delete() ## STILL FAILS with 409 Conflict
#Let's see what's in there
list(bucket.list()) ## Returns empty list []
#What's in there including versions?
list(bucket.list_versions()) ## Returns list of keys and delete markers
#This time delete all versions including delete markers
for version in bucket.list_versions():
#NOTE we're still using bucket.delete, we're just adding the version_id parameter
bucket.delete_key(version.name, version_id = version.version_id)
#Now what's in there
list(bucket.list_versions()) ## Returns empty list []
#Ok, now delete the bucket
bucket.delete() ## SUCCESS!!
|
Why does printing to a utf-8 file fail?
Question: So I ran into a problem this afternoon, I was able to solve it, but I don't
quite understand why it worked.
this is related to a problem I had the other week: [python check if utf-8
string is uppercase.](http://stackoverflow.com/questions/6391442/python-check-
if-utf-8-string-is-uppercase)
basically, the following will not work:
#!/usr/bin/python
import codecs
from lxml import etree
outFile = codecs.open('test.xml', 'w', 'utf-8') #cannot use codecs.open()
root = etree.Element('root')
sect = etree.SubElement(root,'sect')
words = ( u'\u041c\u041e\u0421\u041a\u0412\u0410', # capital of Russia, all uppercase
u'R\xc9SUM\xc9', # RESUME with accents
u'R\xe9sum\xe9', # Resume with accents
u'R\xe9SUM\xe9', ) # ReSUMe with accents
for word in words:
print word
if word.encode('utf8').decode('utf8').isupper(): #.isupper won't function on utf8
title = etree.SubElement(sect,'title')
title.text = word
else:
item = etree.SubElement(sect,'item')
item.text = word
print>>outFile,etree.tostring(root,pretty_print=True,xml_declaration=True,encoding='utf-8')
it fails with the following:
> Traceback (most recent call last):
> File "./temp.py", line 25, in
> print
> >>outFile,etree.tostring(root,pretty_print=True,xml_declaration=True,encoding='utf-8')
> File "/usr/lib/python2.7/codecs.py",
> line 691, in write
> return self.writer.write(data) File "/usr/lib/python2.7/codecs.py",
> line 351, in write
> data, consumed = self.encode(object, self.errors)
> UnicodeDecodeError: 'ascii' codec
> can't decode byte 0xd0 in position 66:
> ordinal not in range(128)
but if I open the new file without `codecs.open('test.xml', 'w', 'utf-8')` and
instead use `outFile = open('test.xml', 'w')` it works perfectly.
**So whats happening??**
* since `encoding='utf-8'` is specified in `etree.tostring()` is it encoding the file again?
* if I leave `codecs.open()` and remove `encoding='utf-8'` the file then becomes an ascii file. Why? becuase `etree.tostring()` has a default encoding of ascii I persume?
* but `etree.tostring()` is simply being written to stdout, and is then redirect to a file that was created as a utf-8 file??
* is `print>>` not workings as I expect? `outFile.write(etree.tostring())` behaves the same way.
Basically, why wouldn't this work? what is going on here. It might be trivial,
but I am obviously a bit confused and have a desire to figure out why my
solution works,
Answer: You've opened the file with UTF-8 encoding, which means that it expects
Unicode strings.
tostring is encoding to UTF-8 (in the form of bytestrings, str), which you're
writing to the file.
Because the file is expecting Unicode, it's decoding the bytestrings to
Unicode using the default ASCII encoding so that it can then encode the
Unicode to UTF-8.
Unfortunately, the bytestrings aren't ASCII.
EDIT: The best advice to avoid this kind of problem is to use Unicode
internally, decoding on input and encoding on output.
|
how to encode url in python
Question: I have created a function for decoding url.
from urllib import unquote
def unquote_u(source):
result = source
if '%u' in result:
result = result.replace('%u','\\u').decode('unicode_escape')
result = unquote(result)
print result
return result
if __name__=='__main__':
unquote_u('{%22%22%3A%22test_%E5%93%A6%E4%BA%88%E4%BB%A5%E8%85%BF%E5%93%A6.doc.txt%22%2C%22mimeType%22%3A%22text%2Fplain%22%2C%22compressed%22%3Afalse%7D')
But, I am not ale to get proper file name. proper file name is :
test_哦予以腿哦.doc
can anyone tell me how to do that?
Answer: urllib.unquote can do it:
>>> urllib.unquote('{%22%22%3A%22test_%E5%93%A6%E4%BA%88%E4%BB%A5%E8%85%BF%E5%93%A6.doc.txt%22%2C%22mimeType%22%3A%22text%2Fplain%22%2C%22compressed%22%3AFalse%7D')
'{"":"test_\xe5\x93\xa6\xe4\xba\x88\xe4\xbb\xa5\xe8\x85\xbf\xe5\x93\xa6.doc.txt","mimeType":"text/plain","compressed":False}'
>>> eval(_)
{'': 'test_\xe5\x93\xa6\xe4\xba\x88\xe4\xbb\xa5\xe8\x85\xbf\xe5\x93\xa6.doc.txt', 'mimeType': 'text/plain', 'compressed': False}
>>> _['']
'test_\xe5\x93\xa6\xe4\xba\x88\xe4\xbb\xa5\xe8\x85\xbf\xe5\x93\xa6.doc.txt'
>>> print _
test_哦予以腿哦.doc.txt
Note that I had to change "false" to "False" in the quoted string. Also that
the string after unquote is still UTF-8 encoded; you can use
str.decode('utf8') to get a Unicode string if that is what you require.
* * *
As JBernardo mentions, eval() of unsafe data is a very bad idea. Anybody
knowing, or even suspecting, that a server-side script is eval()-ing form data
can easily craft a POST with commands that can compromise the server. Better
would be this:
>>> import json, urllib
>>> json.loads(urllib.unquote('{%22%22%3A%22test_%E5%93%A6%E4%BA%88%E4%BB%A5%E8%85%BF%E5%93%A6.doc.txt%22%2C%22mimeType%22%3A%22text%2Fplain%22%2C%22compressed%22%3Afalse%7D'))['']
u'test_\u54e6\u4e88\u4ee5\u817f\u54e6.doc.txt'
>>> print _
test_哦予以腿哦.doc.txt
Also note that this later approach didn't require changing false to False; in
fact it doesn't work if I do. The json package takes care of that.
|
Why does Python's itertools.permutations contain duplicates? (When the original list has duplicates)
Question: It is universally agreed that a list of n _distinct_ symbols has n!
permutations. However, when the symbols are not distinct, the most common
convention, in mathematics and elsewhere, seems to be to count only distinct
permutations. Thus the permutations of the list `[1, 1, 2]` are usually
considered to be
`[1, 1, 2], [1, 2, 1], [2, 1, 1]`. Indeed, the following C++ code prints
precisely those three:
int a[] = {1, 1, 2};
do {
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
} while(next_permutation(a,a+3));
On the other hand, Python's `itertools.permutations` seems to print something
else:
import itertools
for a in itertools.permutations([1, 1, 2]):
print a
This prints
(1, 1, 2)
(1, 2, 1)
(1, 1, 2)
(1, 2, 1)
(2, 1, 1)
(2, 1, 1)
As user Artsiom Rudzenka pointed out in an answer, the [Python
documentation](http://docs.python.org/release/2.6.6/library/itertools.html?highlight=itertools#itertools.permutations)
says so:
> Elements are treated as unique based on their position, not on their value.
My question: why was this design decision made?
It seems that following the usual convention would give results that are more
useful (and indeed it is usually exactly what I want)... or is there some
application of Python's behaviour that I'm missing?
[Or is it some implementation issue? The algorithm as in `next_permutation` —
for instance explained on StackOverflow [here (by
me)](http://stackoverflow.com/questions/352203/generating-permutations-
lazily/353248#353248) and [shown here to be O(1)
amortised](http://stackoverflow.com/questions/4973077/the-amortized-
complexity-of-stdnext-permutation) — seems efficient and implementable in
Python, but is Python doing something even more efficient since it doesn't
guarantee lexicographic order based on value? And if so, was the increase in
efficiency considered worth it?]
Answer: I can't speak for the designer of `itertools.permutations` (Raymond
Hettinger), but it seems to me that there are a couple of points in favour of
the design:
First, if you used a `next_permutation`-style approach, then you'd be
restricted to passing in objects that support a linear ordering. Whereas
`itertools.permutations` provides permutations of _any_ kind of object.
Imagine how annoying this would be:
>>> list(itertools.permutations([1+2j, 1-2j, 2+j, 2-j]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: no ordering relation is defined for complex numbers
Second, by not testing for equality on objects, `itertools.permutations`
avoids paying the cost of calling the `__eq__` method in the usual case where
it's not necessary.
Basically, `itertools.permutations` solves the common case reliably and
cheaply. There's certainly an argument to be made that `itertools` ought to
provide a function that avoids duplicate permutations, but such a function
should be in addition to `itertools.permutations`, not instead of it. Why not
write such a function and submit a patch?
|
Python json memory bloat
Question:
import json
import time
from itertools import count
def keygen(size):
for i in count(1):
s = str(i)
yield '0' * (size - len(s)) + str(s)
def jsontest(num):
keys = keygen(20)
kvjson = json.dumps(dict((keys.next(), '0' * 200) for i in range(num)))
kvpairs = json.loads(kvjson)
del kvpairs # Not required. Just to check if it makes any difference
print 'load completed'
jsontest(500000)
while 1:
time.sleep(1)
Linux **top** indicates that the python process holds ~450Mb of RAM after
completion of 'jsontest' function. If the call to '**json.loads** ' is omitted
then this issue is not observed. A **gc.collect** after this function
execution **does releases the memory**.
Looks like the memory is not held in any caches or python's internal memory
allocator as explicit call to gc.collect is releasing memory.
**Is this happening because the threshold for garbage collection (700, 10, 10)
was never reached ?**
I did put some code after **jsontest** to simulate threshold. But it didn't
help.
Answer: Put this at the top of your program
import gc
gc.set_debug(gc.DEBUG_STATS)
and you'll get printed output whenever there's a collection. You'll see that
in your example code there is no collection after `jsontest` completes, until
the program exits.
You can put
print gc.get_count()
to see the current counts. The first number is the excess of allocations over
deallocations since the last collection of generation 0; the second (resp.
third) is the number of times generation 0 (resp. 1) has been collected since
the last collection of generation 1 (resp. 2). If you print these immediately
after `jsontest` completes you'll see that the counts are `(548, 6, 0)` or
something similar (no doubt this varies according to Python version). So the
threshold was not reached and no collection took place.
This is typical behaviour for threshold-based garbage collection scheduling.
If you need free memory to be returned to the operating system in a timely
manner, then you need to combine threshold-based scheduling with time-based
scheduling (that is, request another collection after a certain amount of time
has passed since the last collection, even if the threshold has not been
reached).
|
Is there a more "Pythonic" way to combine CSV elements?
Question: Basically I am using a python cron to read data from the web and place it in a
CSV list in the form of:
.....
###1309482902.37
entry1,36,257.21,16.15,16.168
entry2,4,103.97,16.36,16.499
entry3,2,114.83,16.1,16.3
entry4,130.69,15.6737,16.7498
entry5,5.20,14.4,17
$$$
###1309482902.37
entry1,36,257.21,16.15,16.168
entry2,4,103.97,16.36,16.499
entry3,2,114.83,16.1,16.3
entry4,130.69,15.6737,16.7498
entry5,5.20,14.4,17
$$$
.....
My code is to basically do a regex search and itterate through all the matches
between ### and $$$, then go through each match line by line, taking each line
and splitting by commas. As you can see some entries have 4 commas, some have
5. That is because I was dumb and didn't realize the web source puts commas in
it's 4 digit numbers. IE
entry1,36,257.21,16.15,16.168
is suposed to really be
entry1,36257.21,16.15,16.168
I already collected a lot of data and do not want to rewrite, so I thought of
a cumbersome workaround. Is there a more pythonic way to do this?
===
contents = ifp.read()
#Pull all entries from the market data
for entry in re.finditer("###(.*\n)*?\$\$\$",contents):
dataSet = contents[entry.start():entry.end()]
dataSet = dataSet.split('\n');
timeStamp = dataSet[0][3:]
print timeStamp
for i in xrange(1,8):
splits = dataSet[i].split(',')
if(len(splits) == 5):
remove = splits[1]
splits[2] = splits[1] + splits[2]
splits.remove(splits[1])
print splits
## DO SOME USEFUL WORK WITH THE DATA ##
===
Answer: I'd use Python's [`csv` module](http://docs.python.org/library/csv.html) to
read in the CSV file, fix the broken rows as I encountered them, then use
`csv.writer` to write the CSV back out. Like so (assuming your original file,
with commas in the wrong place, is `ugly.csv`, and the new, cleaned up output
file will be `pretty.csv`):
import csv
inputCsv = csv.reader(open("ugly.csv", "rb"))
outputCsv = csv.writer(open("pretty.csv", "wb"))
for row in inputCsv:
if len(row) >= 5:
row[1] = row[1] + row[2] #note that csv entries are strings, so this is string concatenation, not addition
del row[2]
outputCsv.writerow(row)
Clean and simple, and, since you're using the proper CSV parser and writer,
you shouldn't have to worry about introducing any new weird corner cases (if
you had used this in your first script, parsing web results, your commas in
your input data would have been escaped).
|