text
stringlengths 226
34.5k
|
---|
Python TLS handshake XMPP
Question: I'm trying to connect to an XMPP server using python. I have the XML to
connect, I'm just not sure how to do the TLS portion of the connection? I can
find lots of examples for HTTPS TLS and examples for XMPP just not how to put
both together.
Has anyone got an example of an XMPP connection in python using TLS? I'm
trying to connect to talk.google.com if that helps.
Answer: First off, use someone else's existing XMPP [library](http://xmpp.org/xmpp-
software/libraries/) instead of writing your own, please. There are plenty
already. Start with [SleekXMPP](https://github.com/fritzy/SleekXMPP).
To answer your question, call
[ssl.wrap_socket](http://docs.python.org/library/ssl.html#ssl.wrap_socket)
when you want to do Start-TLS. For example:
import socket
import ssl
sock = socket.create_connection(("example.com", 5222))
sock.write("""<stream:stream
to='example.com'
version='1.0'
xml:lang='en'
xmlns='jabber:client'
xmlns:stream='http://etherx.jabber.org/streams'>""")
sock.recv(1000) # reads the stream:stream and stream:features. Obviously bad code, to get the point accross
sock.write("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>")
sock.recv(1000) # read the proceed
ssl_sock = ssl.wrap_socket(sock)
ssl_sock.write("""<stream:stream
to='example.com'
version='1.0'
xml:lang='en'
xmlns='jabber:client'
xmlns:stream='http://etherx.jabber.org/streams'>""")
Etc.
|
php's strtr for python
Question: php has the [`strtr`](http://php.net/manual/en/function.strtr.php) function:
strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y
It replaces dictionary keys in a string with corresponding values and
(important) doesn't replace already replaced strings. A naive attempt to write
the same in python:
def strtr(strng, replace):
for s, r in replace.items():
strng = strng.replace(s, r)
return strng
strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'})
returns `xz-x-y` which is not we want (`bb` got replaced again). How to change
the above function so that it behaves like its php counterpart?
(I would prefer an answer without regular expressions, if possible).
Upd: some great answers here. I timed them and found that for short strings
Gumbo's version appears to be the fastest, on longer strings the winner is the
`re` solution:
# 'aa-bb-cc'
0.0258 strtr_thg
0.0274 strtr_gumbo
0.0447 strtr_kojiro
0.0701 strtr_aix
# 'aa-bb-cc'*10
0.1474 strtr_aix
0.2261 strtr_thg
0.2366 strtr_gumbo
0.3226 strtr_kojiro
My own version (which is slightly optimized Gumbo's):
def strtr(strng, replace):
buf, i = [], 0
while i < len(strng):
for s, r in replace.items():
if strng[i:len(s)+i] == s:
buf.append(r)
i += len(s)
break
else:
buf.append(strng[i])
i += 1
return ''.join(buf)
Complete codes and timings: <https://gist.github.com/2889181>
Answer: The following uses regular expressions to do it:
import re
def strtr(s, repl):
pattern = '|'.join(map(re.escape, sorted(repl, key=len, reverse=True)))
return re.sub(pattern, lambda m: repl[m.group()], s)
print(strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}))
Like the PHP's version, this gives preference to longer matches.
|
PyDBG process snapshots not working
Question: I'm following Gray Hat Python book and have copied their code for the process
snapshots using PyDBG. When I run the script I get no errors and expected
output however my program is not actually reverting to the snapshot. When I go
in debug it seems like values are in the snapshot variables as if it is
storing snapshot info but I don't really know enough to say for sure.
Here is code:
from pydbg import *
from pydbg.defines import *
import threading
import time
import sys
class snapshotter(object):
def __init__(self,exe_path):
self.exe_path = exe_path
self.pid = None
self.dbg = None
self.running = True
pydbg_thread = threading.Thread(target=self.start_debugger)
pydbg_thread.setDaemon(0)
pydbg_thread.start()
while self.pid == None:
time.sleep(1)
monitor_thread = threading.Thread(target=self.monitor_debugger)
monitor_thread.setDaemon(0)
monitor_thread.start()
def monitor_debugger(self):
while self.running == True:
input = raw_input("Enter: 'snap','restore' or 'quit'")
input = input.lower().strip()
if input == "quit":
print "[*] Exiting the snapshotter."
self.running = False
self.dbg.terminate_process()
elif input == "snap":
print "[*] Suspending all threads."
self.dbg.suspend_all_threads()
print "[*] Obtaining snapshot."
self.dbg.process_snapshot()
print "[*] Resuming operation."
self.dbg.resume_all_threads()
elif input == "restore":
print "[*] Suspending all threads."
self.dbg.suspend_all_threads()
print "[*] Restoring snapshot."
self.dbg.process_restore()
print "[*] Resuming operation."
self.dbg.resume_all_threads()
def start_debugger(self):
self.dbg = pydbg()
pid = self.dbg.load(self.exe_path)
self.pid = self.dbg.pid
self.dbg.run()
exe_path = "C:\\WINDOWS\\System32\\calc.exe"
snapshotter(exe_path)
Answer: Your code worked for me on Python 2.7 on XP SP1 (Virtual machine). Which
version of Windows are you running? Also, could it be your pydbg install? I'm
using a binary I found at:
<http://www.lfd.uci.edu/~gohlke/pythonlibs/#pydbg>
|
Handling recurring events in a Django calendar app
Question: I'm developing a calendaring application in Django.
The relevant model structure is as follows:
class Lesson(models.Model):
RECURRENCE_CHOICES = (
(0, 'None'),
(1, 'Daily'),
(7, 'Weekly'),
(14, 'Biweekly')
)
frequency = models.IntegerField(choices=RECURRENCE_CHOICES)
lessonTime = models.TimeField('Lesson Time')
startDate = models.DateField('Start Date')
endDate = models.DateField('End Date')
student = models.ForeignKey(Student)
class CancelledLesson(models.Model):
lesson = models.ForeignKey(Lesson)
student = models.ForeignKey(Student)
cancelledLessonDate = models.DateField() # Actual date lesson has been cancelled, this is startDate + Frequency
class PaidLesson(models.Model):
lesson = models.ForeignKey(Lesson)
student = models.ForeignKey(Student)
actualDate = models.DateField() # Actual date lesson took place
paidAmt = models.DecimalField('Amount Paid', max_digits=5, decimal_places=2)
paidDate = models.DateField('date paid')
class CompositeLesson(models.Model):
# only used to aggregate lessons for individual lesson management
lesson = models.ForeignKey(Lesson)
student = models.ForeignKey(Student)
actualDate = models.DateTimeField()
isCancelled = models.BooleanField()
canLesson = models.ForeignKey(CancelledLesson, blank=True, null=True)
payLesson = models.ForeignKey(PaidLesson, blank=True, null=True)
Apparently this is all causing issues with displaying the lessons that belong
to a particular student. What I am attempting to do is display a table that
shows the Student name plus all instances of scheduled lessons. I am
calculating the recurrence dynamically to avoid blowing up my database.
Exceptions to the recurrences (i.e. lesson cancellations) are stored in their
own tables. Recurrences are checked against the cancelled lesson table when
the recurrences are generated.
See my code to generate recurrences (as well as a small catalog of what issues
this is causing) here: [Can't get key to display in Django
template](http://stackoverflow.com/questions/10935801/cant-get-key-to-display-
in-django-template)
I'm relatively inexperienced with Python, and am using this project as a way
to get my head around a lot of the concepts, so if I'm missing something
that's inherently "Pythonic", I apologize.
Answer: The key part of your problem is that you're using a handful of models to track
just one concept, so you're introducing a lot of duplication and complexity.
Each of the additional models is a "type" of `Lesson`, so you should be using
inheritance here. Additionally, most of the additional models are merely
tracking a particular characteristic of a `Lesson`, and as a result should not
actually be models themselves. This is how I would have set it up:
class Lesson(models.Model):
RECURRENCE_CHOICES = (
(0, 'None'),
(1, 'Daily'),
(7, 'Weekly'),
(14, 'Biweekly')
)
student = models.ForeignKey(Student)
frequency = models.IntegerField(choices=RECURRENCE_CHOICES)
lessonTime = models.TimeField('Lesson Time')
startDate = models.DateField('Start Date')
endDate = models.DateField('End Date')
cancelledDate = models.DateField('Cancelled Date', blank=True, null=True)
paidAmt = models.DecimalField('Amount Paid', max_digits=5, decimal_places=2, blank=True, null=True)
paidDate = models.DateField('Date Paid', blank=True, null=True)
class CancelledLessonManager(models.Manager):
def get_query_set(self):
return self.filter(cancelledDate__isnull=False)
class CancelledLesson(Lesson):
class Meta:
proxy = True
objects = CancelledLessonManager()
class PaidLessonManager(models.Manager):
def get_query_set(self):
return self.filter(paidDate__isnull=False)
class PaidLesson(Lesson):
class Meta:
proxy = True
objects = PaidLessonManager()
You'll notice that I moved all the attributes onto `Lesson`. This is the way
it should be. For example, `Lesson` has a `cancelledDate` field. If that field
is NULL then it's not cancelled. If it's an actual date, then it is cancelled.
There's no need for another model.
However, I have left both `CancelledLesson` and `PaidLesson` for instructive
purposes. These are now what's called in Django "proxy models". They don't get
their own database table (so no nasty data duplication). They're purely for
convenience. Each has a custom manager to return the appropriate matching
`Lessons`, so you can do `CancelledLesson.objects.all()` and get only those
`Lesson`s that are cancelled, for example. You can also use proxy models to
create unique views in the admin. If you wanted to have an administration area
only for `CancelledLesson`s you can, while all the data still goes into the
one table for `Lesson`.
`CompositeLesson` is gone, and good riddance. This was a product of trying to
compose these three other models into one cohesive thing. That's no longer
necessary, and your queries will be _dramatically_ easier as a result.
**EDIT**
I neglected to mention that you can and should add utility methods to the
`Lesson` model. For example, while tracking cancelled/not by whether the field
is NULL or not makes sense from a database perspective, from programming
perspective it's not as intuitive as it could be. As a result, you might want
to do things like:
@property
def is_cancelled(self):
return self.cancelledDate is not None
...
if lesson.is_cancelled:
print 'This lesson is cancelled'
Or:
import datetime
...
def cancel(self, date=None, commit=True):
self.cancelledDate = date or datetime.date.today()
if commit:
self.save()
Then, you can cancel a lesson simply by calling `lesson.cancel()`, and it will
default to cancelling it today. If you want to future cancel it, you can pass
a date: `lesson.cancel(date=tommorrow)` (where `tomorrow` is a `datetime`). If
you want to do other processing before saving, pass `commit=False`, and it
won't actually save the object to the database yet. Then, call `lesson.save()`
when you're ready.
|
Display an image read from a zip archive python
Question: I want to create a comic archive reader in python as an exercise to teach
myself more python but I've been having troubles trying to read different
image files from a zip archive without extracting the files and then display
them.
I found a website with an example (http://www.python-
forum.org/pythonforum/viewtopic.php?f=4&t=3607) that could only display .gif
images. The example uses `PhotoImage` (The Tkinter version not the PIL
version) which can accept a 64bit encoded string instead of an actual file.
From most of my research it looks like PIL is what I want to use to deal with
images other than gif but I can't find a way to call `PIL.ImageTk.PhotoImage`
in a similar way to the `Tkinter.PhotoImage`. to take a stream of data instead
of an actual file.
Is there any way that I can hand the data received from `zipfile.read()` to
`PIL.ImageTk.PhotoImage`? Is there another library I could use to handle the
images? Tkinter is not a requirement for the program I'm writing so if there
is a better widget framework that I should be using I don't mind changing.
EDIT: So I figured a way to do this with PIL and tkinter.
z = zipfile.ZipFile("zipfile.zip", "r")
data = z.read(z.namelist()[0]) #Read in the first image data
dataEnc = StringIO(data) #Encode the raw data to be used by Image.open()
img = Image.open(dataEnc) #Open the image
pimg = ImageTk.PhotoImage(img) #Make tk compatible image
Answer: You can use PythonMagick to create an `Image` like so:
from PythonMagick import *
data = zipfile.read()
img = Image(Blob(data))
Then display it using wxPython as suggested in the PythonMagick
[readme](http://www.imagemagick.org/download/python/README.txt) under the
"Display" section.
|
How to print absolute line number in uncaught exception?
Question: When error occured Python prints something like this:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 8, in m
File "<stdin>", line 5, in exec_st
File "<stdin>", line 9, in exec_assign
File "<stdin>", line 48, in ref_by_id
IndexError: list index out of range
where 2, ... , 48 are relative line numbers which are not very convenient. How
to print absolute line numbers in such error messages?
EDIT: Maybe it's a dumb question, but answer will facilitate development a
little. I'm printing text in several files. When done, press shortcut which
runs python and copies contents of current file to console. Proposed solution
forces to press excess keystrokes (Ctrl+S, Alt+Tab) and create additional
files. I hope I have put it clear.
Answer: A few minutes of hacking around gives me this Read-Eval-Print Loop in Python
2.7:
#!/usr/bin/env python
import code
import sys
LINE_NUMBER=0
def reset_linenum():
global LINE_NUMBER
LINE_NUMBER=-1
def resettable_REPL():
global LINE_NUMBER
BUFFERED_LINES=[]
ii=code.InteractiveInterpreter({"reset_linenum":reset_linenum})
while True:
try:
BUFFERED_LINES.append(raw_input("!"+sys.ps1)+'\n')
while (BUFFERED_LINES[-1][:1] in " \t" or
ii.runsource("\n"*LINE_NUMBER+"".join(BUFFERED_LINES), "console")):
BUFFERED_LINES.append(raw_input("!"+sys.ps2)+'\n')
LINE_NUMBER+=len(BUFFERED_LINES)
BUFFERED_LINES=[]
except EOFError:
break
if __name__=='__main__':
resettable_REPL()
It's a bit hackish, but it keeps track of line numbers as the session
continues, and allows the current count to be reset by a call to
`reset_linenum()`. An example session:
!!!> print "hello" # line 1
hello
!!!> def badfunc(): # line 2
!... raise Exception("doh") # line 3
!!!> badfunc() # line 4
Traceback (most recent call last):
File "console", line 4, in <module>
File "console", line 3, in badfunc
Exception: doh
!!!> ? # line 5
File "console", line 5
?
^
SyntaxError: invalid syntax
!!!> reset_linenum() # RESET
!!!> raise Exception("!") # line 1
Traceback (most recent call last):
File "console", line 1, in <module>
Exception: !
!!!>
**EDIT** : Fixed REPL to not execute indented blocks quite so prematurely.
|
Parsing Source Code (Python) Approach: Beautiful Soup, lxml, html5lib difference?
Question: I have a large HTML source code I would like to parse (~200,000) lines, and
I'm fairly certain there is some poor formatting throughout. I've been
researching some parsers, and it seems Beautiful Soup, lxml, html5lib are the
most popular. From reading this website, it seems lxml is the most commonly
used and fastest, while Beautiful Soup is slower but accounts for more errors
and variation.
I'm a little confused on the Beautiful Soup documentation,
<http://www.crummy.com/software/BeautifulSoup/bs4/doc/>, and commands like
BeautifulSoup(markup, "lxml") or BeautifulSoup(markup, html5lib). In such
instances is it using both Beautiful Soup and html5lib/lxml? Speed is not
really an issue here, but accuracy is. The end goal is to parse get the source
code using urllib2, and retrieve all the text data from the file as if I were
to just copy/paste the webpage.
P.S. Is there anyway to parse the file without returning any whitespace that
were not present in the webpage view?
Answer: My understanding (having used BeautifulSoup for a handful of things) is that
it is a wrapper for parsers like lxml or html5lib. Using whichever parser is
specified (I believe the default is HTMLParser, the default parser for
python), BeautifulSoup creates a tree of tag elements and such that make it
quite easy to navigate and search the HTML for useful data continued within
tags. If you really just need the text from the webpages and not more specific
data from specific HTML tags, you might only need a code snippet similar to
this:
from bs4 import BeautifulSoup
import urllib2
soup = BeautifulSoup(urllib2.urlopen("http://www.google.com")
soup.get_text()
get_text isn't that great with complex webpages (it gets random javascript or
css occasionally), but if you get the hang of how to use BeautifulSoup, it
shouldn't be hard to get only the text you want.
For your purposes it seems like you don't need to worry about getting one of
those other parsers to use with BeautifulSoup (html5lib or lxml).
BeautifulSoup can deal with some sloppiness on its own, and if it can't, it
will give an obvious error about "malformed HTML" or something of the sort,
and that would be an indication to install html5lib or lxml.
|
Decrease execution time for a given database-handling Python 2.7 program.
Question: The following function fetches data from a database:
def findid(name,parent):
conn = MySQLdb.connect (host = "localhost",
user = "arunkamaly",
passwd = "code",
db = "se")
cursor=conn.cursor()
cursor.execute(" select xbrl_id from se_xbrl_concepts where xbrl_name=%s;",name)
name=cursor.fetchone()
cursor.execute(" select xbrl_id from se_xbrl_concepts where xbrl_name=%s;",parent)
pname=cursor.fetchone()
cursor.close()
if pname==None:
return name[0],0
return name[0],pname[0]
And here the function above is used, but also the insert method introduced:
def prsentparse():
conn = MySQLdb.connect (host = "localhost",\
user = "arunkamaly",\
passwd = "code",\
db = "se")
cursor=conn.cursor()
f = open(csvfile, 'rb')
spamReader = csv.reader(f, delimiter=',', quotechar='"')
for clist in spamReader:
if clist[0]=='LinkRole' or clist[0] =='' or clist[0]=='prefix':
continue
name=clist[0]+':'+clist[1]
parent=clist[6].strip()
xid,pid=findid(name,parent)
prio=0 if clist[5].strip()=='' else clist[5]
order=0 if clist[4].strip()=='' else clist[4]
depth=0 if clist[3].strip()=='' else clist[3]
#print clist
#cursor.execute("INSERT INTO se_xbrl_presentation (xbrl_id,xbrl_parent_id,priority,order,depth) VALUES (%s,%s,%s,%s,%s);",(xid,pid,prio,order,depth) )
#sql = "insert into se_xbrl_presentation (xbrl_id, xbrl_parent_id, priority, order, depth) values (" + xid + ", " + pid + ", " + prio + ", " + order + ", " + depth + ");"
try:
cursor.execute("INSERT INTO `se_xbrl_presentation`(`xbrl_id`, `xbrl_parent_id`, `priority`, `order`, `depth`) VALUES (%s,%s,%s,%s,%s);",(xid,pid,prio,order,depth) )
except MySQLdb.Error,e:
print "mysql Error %d:%s"%(e.args[0],e.args[1])
conn.commit
cursor.close()
This approach appears to be too slow. Could you please advise any performance-
increasing improvements?
Answer: You are opening a connection inside the findid function. That means that you
are opening a connection in every iteration of the for loop. Instead, pass the
connection that you already have to the findid function and you won't have to
open one every time.
Another thing that could be important: do you have an index in the xbrl_name
field of the se_xbrl_concepts table? You are doing two selects in each
iteration of the for loop.
|
Python dictionary optimize this script
Question: I have a string like `rdb_master_mongodb` where `rdb_` is fixed and `master`
is a database name which can be anything and `mongodb` can be one among
`mysql`, `mongodb`, `postgres`, `mssql` or `bdb`. I need to fetch the value
for this string from the dictionary which has the value in
`myDict[master][mongodb]`. In order to get this I need to split the string
`rdb_master_mongodb` and get the values of `master` and `mongodb`. I can't use
split because sometimes the string becomes `rdb_master_test_mongodb`. Hence I
have to use `endswith` to get the exact key. Howeveer, `endswith` does not
work on a list.
I have to get the matching tuple value from a tuple. Right now I do this like:
import re
name = 'rdb_master_mongodb'
s = re.sub('rdb_', "", name)
VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb')
(a, b, c, d, e) = VALID_DB
if s.endswith(a):
db = a
if s.endswith(b):
db = b
if s.endswith(c):
db = c
if s.endswith(d):
db = d
if s.endswith(e):
db = e
db_name = re.sub('_'+db, "", s)
print db_name+" is "+db
Is there a better way to do this?
Answer:
db = name.rsplit('_', 1)[1]
if db not in VALID_DB:
raise ValueError('Incorrect DB name: %s' % db)
|
Is there any API for formatting Sphinx text?
Question: I want to use Sphinx text converting in my Python program. For example, I have
a `string` variable which contains this text:
.. note::
This is a note.
.. code-block:: ruby
Some Ruby code.
and I want to call `magic_convert_function(string)` that will produce a HTML
string like this one:
<p class="note">This is a note.</p>
<p><code class="ruby">Some ruby code.</code></p>
Is there any such function in Sphinx API?
Note that I am not satisfied with "pure" reStructuredText, I want to use some
Sphinx-specific language features.
Answer: I'm not sure about the Sphinx API, but since Sphinx is just built on top on
[Docutils](http://docutils.sourceforge.net/), which has a very well documented
API you can try and use and extend this. As a quick example, to get an XML
representation of some string of reStructuredText you could do something like:
from docutils.core import publish_doctree
source = """Test
====
.. note::
This is a note.
This is just a paragraph.
"""
# Parse reStructuredText input, returning the Docutils doctree as
# an `xml.dom.minidom.Document` instance.
doctree = publish_doctree(source).asdom()
print doctree.toprettyxml()
The result of this is:
<?xml version="1.0" ?>
<document ids="test" names="test" source="<string>" title="Test">
<title>
Test
</title>
<note>
<paragraph>
This is a note.
</paragraph>
</note>
<paragraph>
This is just a paragraph.
</paragraph>
</document>
Now in my version of Docutils, 0.8, there is no `code-block` directive.
However, this is meant to be included in later versions and Sphinx in fact
extends Docutils to include this. So you can:
* see how Sphinx does this;
* get a later version of Docutils;
* use the experimental code-block implementation in the [Docuitls sandbox](http://docutils.sourceforge.net/sandbox/code-block-directive/) (this has examples of how to use this code);
* [write you own directive](http://docutils.sourceforge.net/docs/howto/rst-directives.html).
Note, here I have used `docutils.core.publish_doctree` to get an XML
representation of the reStructuredText source. If you just want the HTML you
can use the HTML writer with
[`docutils.core.publish_parts`](http://docutils.sourceforge.net/docs/api/publisher.html#publish-
parts-details) like so:
from docutils.core import publish_parts
source = ...as above...
document = publish_parts(source, writer_name='html')
print document['body']
which results in
<div class="note">
<p class="first admonition-title">Note</p>
<p class="last">This is a note.</p>
</div>
<p>This is just a paragraph.</p>
|
How to reproduce a wget-like speed interface on a linux terminal?
Question: Wget prints out speed information to stdout in a very clear manner, where the
speed is shown and refreshed whilst the file is downloaded, and a bar scrolls
across the screen. I'd like to replicate this sort of output, in a Python
program. How is this possible?
I thought the [curses](http://docs.python.org/library/curses.html) library
should be able to do this; this is what I came up with:-
import curses, time
class Speeder( object ):
"""Show and refresh time and download speed in a curses interface."""
t1 = 0. # start time
t = 0. # current time
tf = 0. # end time
def start(self, filename=None ):
"""Start timer"""
self.t1 = self.t = time.time()
curses.use_env(True)
curses.initscr()
self.win = curses.newwin(4, 0)
if filename is not None:
self.win.addnstr(filename, 50 )
self.win.refresh()
def update(self, rbytes):
"""Refresh speed."""
t = time.time()
td = t - self.t
self.t = t
speed = rbytes / td
self.win.addstr(0,54,str('{0:.02f} B/s'.format(speed)))
self.win.refresh()
def end(self):
"""End timer"""
self.tf = time.time()
curses.endwin()
try:
speed = Speeder()
speed.start(filename='foo.bar')
for i in xrange(10):
time.sleep(0.5)
speed.update(200)
finally:
speed.end()
The problem is that it takes up an entire window, and I only really need a
line at a time. I'd rather not push all the command line history back above
the terminal window. Please correct me if I'm wrong, but I currently think
curses apps always take up the entire terminal window.
So I had a look at the [tty](http://docs.python.org/library/tty.html) and
[termios](http://docs.python.org/library/termios.html#module-termios) modules,
but I can't find any examples doing what I want to do.
Finally, I came across [a blog
post](http://www.mutaku.com/wp/index.php/2011/06/python-dynamically-printing-
to-single-line-of-stdout/) which does it by simply writing some special
characters to sys.stdout. Applying his code to my Speeder class, I came up
with this:-
import sys
class Speeder( object ):
"""Show and refresh time and download speed."""
t1 = 0. # start time
t = 0. # current time
tf = 0. # end time
def start(self, filename=None ):
"""Start timer"""
self.t1 = self.t = time.time()
if filename is not None:
sys.stdout.write( '\r\x1b[K' + filename.ljust(50) )
sys.stdout.flush()
def update(self, rbytes):
"""Refresh speed."""
t = time.time()
td = t - self.t
self.t = t
speed = '{0} B/s'.format( rbytes / td )
sys.stdout.write( "\r\x1b[K" + speed.rjust(65) )
sys.stdout.flush()
def end(self):
"""End timer"""
self.tf = time.time()
sys.stdout.write('\n')
This has fewer lines of code, which I like, but tbh I don't have a clue what's
going on, or how to modify it to only update part of the line, similar to the
curses.addstr function. Currently, the filename is overwritten with white-
space. I could of course modify the class to construct the entire line each
time from python, but I'd like to understand this in order to tailor it to my
own needs.
The author says this is possible only on VT100 terminals. So I guess this
would only work on Unix terminals then? That's fine, but are there any Unix
terminals that this would not work on?
Is there better documentation on the subject, or more complicated examples
(e.g. updating multiple lines, one line of many, or single characters on a
line), preferably for Python? This doesn't seem like a feature of Python, but
the tty, which is why I guess I've failed to find anything. Is there a man
page or something I should read?
Answer: The code above is using ANSI escape codes:
<https://en.wikipedia.org/wiki/ANSI_escape_code>. I think that's the
documentation you are looking for when trying to grok the code you found.
|
JPEG and PNG Library Use in PIL
Question: I'm relatively new to development and I've been attempting to setup an
application I'm building in Django (on Windows 7, 64 bit) to accept image
uploads via ImageField. I initially installed PIL, but found that I needed
JPEG and PNG libraries first. So I uninstalled PIL using "pip uninstall pil"
and setup the libraries at C:\zlib-1.2.7\zlib.lib and C:\jpeg-8d\libjpeg.lib.
Afterwards, I went into the setup.py in PIL and changed the following:
JPEG_ROOT = "C:/jpeg-8d"
ZLIB_ROOT = "C:/zlib-1.2.7"
I then install via:
pip install C:\Imaging-1.1.7\
I got the following at the end of the install, which suggests there's JPEG and
PNG support:
Installing collected packages: PIL
Running setup.py install for PIL
WARNING: '' not a valid package name; please use only.-separated package nam
es in setup.py
--------------------------------------------------------------------
PIL 1.1.7 SETUP SUMMARY
--------------------------------------------------------------------
version 1.1.7
platform win32 2.6.6 (r266:84297, Aug 24 2010, 18:46:32)
[MSC v.1500 32 bit (Intel)]
--------------------------------------------------------------------
*** TKINTER support not available (Tcl/Tk 8.5 libraries needed)
--- JPEG support available
--- ZLIB (PNG/ZIP) support available
*** FREETYPE2 support not available
*** LITTLECMS support not available
--------------------------------------------------------------------
To add a missing option, make sure you have the required
library, and set the corresponding ROOT variable in the
setup.py script.
To check the build, run the selftest.py script.
Successfully installed PIL
Cleaning up...
However, I got following when testing with selftest.py, which suggests no
support:
C:\Windows\system32>python C:\Imaging-1.1.7\selftest.py
--------------------------------------------------------------------
PIL 1.1.7 TEST SUMMARY
--------------------------------------------------------------------
Python modules loaded from C:\Users\ayan\Desktop\Imaging-1.1.7\PIL
Binary modules loaded from C:\Python26_x86\lib\site-packages\PIL
--------------------------------------------------------------------
*** PIL CORE support not installed
*** TKINTER support not installed
*** JPEG support not installed
*** ZLIB (PNG/ZIP) support not installed
*** FREETYPE2 support not installed
*** LITTLECMS support not installed
--------------------------------------------------------------------
I also tried to work with a JPEG and got following IOError:
C:\Users\Public\Pictures\Sample Pictures>python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL
>>> import os, sys
>>> import Image
>>> img = Image.open(Desert.jpg)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Desert' is not defined
>>> img = Image.open("Desert.jpg")
>>> img.save("Desert_test.jpg")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26_x86\lib\site-packages\PIL\Image.py", line 1406, in save
self.load()
File "C:\Python26_x86\lib\site-packages\PIL\ImageFile.py", line 189, in load
d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
File "C:\Python26_x86\lib\site-packages\PIL\Image.py", line 385, in _getdecode
r
raise IOError("decoder %s not available" % decoder_name)
IOError: decoder jpeg not available
This is somewhat similar to what was reported at [PIL installation / run
issue](http://stackoverflow.com/questions/10543581/pil-installation-run-
issue); however, it appears that in this case, JPEGs actually aren't working.
A similar problem is observed with PNGs.
It's not clear to me where in the process I've made a mistake, so any comments
would be greatly appreciated. Please let me know if additional information is
required, I'll endeavor to do by best to provide it.
Many thanks.
Answer: I have solved something similar but just for png support. I believe you can do
the same for jpeg support as well.
First I would recommend using Pillow, a fork of PIL. The solution I used is to
manually compile on my machine (win7 64 bit) the zlib library. And then
manualy compiling the Pillow Package. I edited the Setup.py like you did to
point at a directory where I put the zlib I just compiled.
I would suggest you manually compile the jpeg lib as well, and the zlib and
then compile Pillow again. Make sure to uninstall previous versions of
PIL/Pillow before doing it.
The link for my detailed answer of how to do it with zlib is:
<http://stackoverflow.com/a/17190972/2501083>
Hope this helps
|
Python Flask, SQLAlchemy relationship
Question: I've been trying to fix this problems for a few hours already, I cannot manage
to get SQLAlchemy working (it was working untill I put the two new functions,
User and Registration)
from flask.ext.sqlalchemy import SQLAlchemy
from . import app
from datetime import datetime
db = SQLAlchemy(app)
class PasteCode(db.Model):
id = db.Column(db.Integer, primary_key = True)
codetitle = db.Column(db.String(60), unique = True)
codebody = db.Column(db.Text)
pub_date = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
parent_id = db.Column(db.Integer, db.ForeignKey('paste_code.id'))
parent = db.relationship('PasteCode', lazy = True, backref = 'children', uselist = False, remote_side = [id])
def __init__(self, codetitle, codebody, parent = None):
self.codetitle = codetitle
self.codebody = codebody
self.pub_date = datetime.utcnow()
self.parent = parent
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
display_name = db.Column(db.String(30))
#pastes = db.Column(db.Integer, db.ForeignKey('paste_code.id'))
pastes = db.relationship(PasteCode, lazy = "dynamic", backref = "user")
class Registration(db.Model):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(30), unique = True)
password = db.Column(db.String(100), unique = False)
This is the traceback it gives me when running:
OperationalError: (OperationalError) no such table: paste_code u'SELECT paste_code.id AS paste_code_id, paste_code.codetitle AS paste_code_codetitle, paste_code.codebody AS paste_code_codebody, paste_code.pub_date AS paste_code_pub_date, paste_code.user_id AS paste_code_user_id, paste_code.parent_id AS paste_code_parent_id \nFROM paste_code' ()
I also tried this:
from flask.ext.sqlalchemy import SQLAlchemy
from . import app
from datetime import datetime
db = SQLAlchemy(app)
class PasteCode(db.Model):
id = db.Column(db.Integer, primary_key = True)
codetitle = db.Column(db.String(60), unique = True)
codebody = db.Column(db.Text)
pub_date = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
parent_id = db.Column(db.Integer, db.ForeignKey('pastecode.id'))
parent = db.relationship('PasteCode', lazy = True, backref = 'children', uselist = False, remote_side = [id])
def __init__(self, codetitle, codebody, parent = None):
self.codetitle = codetitle
self.codebody = codebody
self.pub_date = datetime.utcnow()
self.parent = parent
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
display_name = db.Column(db.String(30))
pastes = db.relationship(PasteCode, lazy = 'dynamic', backref = 'user')
#pastes = db.relationship(PasteCode, lazy = "dynamic", backref = "user")
class Registration(db.Model):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(30), unique = True)
password = db.Column(db.String(100), unique = False)
And I got this error:
ArgumentError: Could not determine join condition between parent/child tables on relationship PasteCode.parent. Specify a 'primaryjoin' expression. If 'secondary' is present, 'secondaryjoin' is needed as well.
Any idea? Thank you!
Answer: The way I fixed it was simple, I added
__tablename__ = "paste_code"
and everything worked as it should, I think SQLAlchemy wasn't checking the
table name properly.
|
Why is Qt losing my thin space unicode character when loading an XML file?
Question: I have an XML document, part of which has the following in it:
<math display='block'><mtext> </mtext></math>
If this is loaded into Qt (specifically the Qt MathML widget where I found
this problem), the QDomDocument object loses the unicode thin space character
(U+2009). This Python example code demonstrates the problem:
from PyQt4.QtXml import *
d = QDomDocument()
d.setContent("<math display='block'><mtext> </mtext></math>")
print repr(unicode(d.toString()))
The output from this code is:
u'<math display="block">\n <mtext/>\n</math>\n'
Inserting an extra non-space character after the thin space stops the thin
space being lost.
Is this my mistake, an XML feature, or does Qt have a bug?
Answer: From [QDomDocument's documentation](http://qt-
project.org/doc/qt-4.8/qdomdocument.html):
> Text nodes consisting only of whitespace are stripped and won't appear in
> the QDomDocument. If this behavior is not desired, one can use the
> setContent() overload that allows a QXmlReader to be supplied.
So this way you do not lose the white space only data (example is in C++):
QXmlSimpleReader reader;
QXmlInputSource source;
QDomDocument dom;
source.setData(QString("<mtext> </mtext>"));
dom.setContent(&source, &reader);
|
Using tweepy to access Twitter's Streaming API
Question: I'm currently having trouble getting example code for using tweepy to access
Twitter's Streaming API to run correctly (err...or at least how I expect it to
run). I'm using a recent clone of tweepy from GitHub (labeled version 1.9) and
Python 2.7.1.
I've tried example code from three sources, in each case using "twitter" as a
test term for tracking:
1. O'Rilley Answers code: [How to Capture Tweets in Real-time with Twitter's Streaming API](http://answers.oreilly.com/topic/2605-how-to-capture-tweets-in-real-time-with-twitters-streaming-api/)
2. Andrew Robinson's blog: [Using Tweepy to access the Twitter Stream](http://andrewbrobinson.com/2011/07/15/using-tweepy-to-access-the-twitter-stream/)
3. Tweepy examples repository on GitHub (which, as Andrew Robinson has done, can be easily modified to support OAuth authentication): streamwatcher.py
In all three cases I get the same result: Authentication is successful, no
errors are produced, and the main program loop seems to be executing w/o any
problems. I see network usage jump to about 200KB/s, and the python process
jumps to near 100% CPU usage, so I think data is being received. Nothing is
output to the console, however.
I suspect that tweepy's Stream class is not calling the custom callback method
for some reason. I've tried rewriting the callback methods in each example to
produce output _whenever_ they're called, which seems to confirm this. This is
one very simple bit of test code based on Andrew Robinson's blog entry (with
my app's keys removed, of course):
# -*- coding: utf-8 -*-
import tweepy
consumer_key = ''
consumer_secret = ''
access_token_key = ''
access_token_secret = ''
auth1 = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth1.set_access_token(access_token_key, access_token_secret)
class StreamListener(tweepy.StreamListener):
def on_status(self, tweet):
print 'Ran on_status'
def on_error(self, status_code):
print 'Error: ' + repr(status_code)
return False
def on_data(self, data):
print 'Ok, this is actually running'
l = StreamListener()
streamer = tweepy.Stream(auth=auth1, listener=l)
#setTerms = ['hello', 'goodbye', 'goodnight', 'good morning']
setTerms = ['twitter']
streamer.filter(track = setTerms)
What am I doing wrong?
Answer: I ran into this as well and fixed it on my local checkout by changing line 160
in streaming.py to
if delimited_string.strip().isdigit():
This seems to be a known issue/bug in Tweepy - should have checked the issues
list before doing all that debugging :) -
<https://github.com/tweepy/tweepy/pull/173>
<https://github.com/tweepy/tweepy/pull/182>
|
Detect if an image has a border, programmatically (return boolean)
Question: First off, I have read this post. [How to detect an image border
programmatically?](http://stackoverflow.com/questions/1954742/how-to-detect-
an-image-border-programmatically) He seems to be asking a slightly different
question, on finding the X/Y coordinates though.
I am just trying to find whether or not a **solid** border exists around a
given photo. I've explored using ImageMagick, but is this the best option?
I've never done any Image-related programming so I'm hoping there's just a
simple api out there that can solve this problem. I'm also fairly new to how
to use these libraries, so any advice is appreciated. I'd prefer solutions in
Python or Java, anything is fine though.
Thanks!
Answer: I answered a related question
[here](http://stackoverflow.com/questions/10615901/trim-whitespace-using-
pil/10616717#10616717), that removes any border around an image, it uses
[PIL](http://www.pythonware.com/products/pil/). You can easily adapt the code
so it returns `True` or `False` for whether there is a border or not, like
this:
from PIL import Image, ImageChops
def is_there_a_border(im):
bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
return bbox != (0,0,im.size[0],im.size[1])
However, this will return `True` even if only one side of an image has a
border. But it sounds like you want to know if there is a border all the way
around an image. To do that change the last line to:
return all((bbox[0], bbox[1], (bbox[0] + bbox[2]) <= im.size[0],
(bbox[1] + bbox[3]) <= im.size[1]))
This only returns true if there is a border on every side.
For example:
`False:`

`False:`

`True:`

|
AllegroGraph - UTF-8 characters in N-Triples
Question: When I use the AllegroGraph 4.6 Python API, I can use the
connection.addTriple() method to try to add a triple that ends in a literal
containing a unicode character (×):
`conn.addTriple( ..., ..., '5 × 10**5' )`
This doesn't work. I get the error:
`UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position...`
Here's the full traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/openrdf/repository/repositoryconnection.py", line 357, in addTriple
self._convert_term_to_mini_term(obj), cxt)
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/openrdf/repository/repositoryconnection.py", line 235, in _convert_term_to_mini_term
return self._to_ntriples(term)
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/openrdf/repository/repositoryconnection.py", line 367, in _to_ntriples
else: return term.toNTriples();
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/openrdf/model/literal.py", line 182, in toNTriples
sb.append(strings.encode_ntriple_string(self.getLabel()))
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/openrdf/util/strings.py", line 52, in encode_ntriple_string
string = unicode(string)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 18: ordinal not in range(128)
Instead I can add the triple like this:
`conn.addTriple( ..., ..., u'5 × 10**5' )`
That way I don't get an error.
But if I load a file of ntriples that contains some UTF-8 encoded characters
using `connection.addFile(filename, format=RDFFormat.NTRIPLES)`, I get this
error message if the ntriples file is saved as ANSI encoding from Notepad++:
400 MALFORMED DATA: N-Triples parser error while parsing
#<http request stream @ #x10046f9ea2> at line 12764 (last character was
#\×): nil
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/openrdf/repository/repositoryconnection.py", line 341, in addFile
commitEvery=self.add_commit_size)
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/miniclient/repository.py", line 342, in loadFile
nullRequest(self, "POST", "/statements?" + params, body, contentType=mime)
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/miniclient/request.py", line 198, in nullRequest
if (status < 200 or status > 204): raise RequestError(status, body)
franz.miniclient.request.RequestError: Server returned 400: N-Triples parser error while parsing
I get this error message if the file is saved as UTF-8 encoding:
400 MALFORMED DATA: N-Triples parser error while parsing
#<http request stream @ #x100486e8b2> at line 1 (last character was
#\): Subjects must be resources (i.e., URIs or blank nodes)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/openrdf/repository/repositoryconnection.py", line 341, in addFile
commitEvery=self.add_commit_size)
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/miniclient/repository.py", line 342, in loadFile
nullRequest(self, "POST", "/statements?" + params, body, contentType=mime)
File "/cygdrive/c/agraph-4.6-client-python/src2/franz/miniclient/request.py", line 198, in nullRequest
if (status < 200 or status > 204): raise RequestError(status, body)
franz.miniclient.request.RequestError: Server returned 400: N-Triples parser error while parsing
However, if the file is set to ANSI encoding in Notepad++, I can go in and
paste the `×` character, save, and then the file loads fine. Or, if I change
the file encoding to UTF-8 after I paste the character, then the character
changes to some strange xD7 character. If the file is set to UTF-8 encoding
and I paste the `×` in there, then if I change the encoding to ANSI the `×`
changes to a `×`.
When the file was given to me, it had `×` where the `×` should have been, and
when I tried to load it in AllegroGraph I got the first 400 MALFORMED DATA
error, which fails at the line where the character actually appears in the
file (12764), instead of just at the first line. I assume that the reason I
get the second 400 MALFORMED DATA error on line 1 has something to do with the
header written by Notepad++ for UTF-8 encoded files. So apparently, I have to
save a file as ANSI if I want AllegroGraph not to hiccup immediately, but
there has to be some way to tell AllegroGraph to read things like `×` as
UTF-8 characters.
In the file, the triple looks like:
`<...some subject URI...> <...some predicate URI...> "5 × 10**5" .`
Answer: use codecs module.
import codecs
f = codecs.open('file.txt','r','utf8')
this will open your file forcing the utf8 encoding
|
Python: How to toggle between two values
Question: I want to toggle between two values in Python, that is, between 0 and 1.
For example, when I run a function the first time, it yields the number 0.
Next time, it yields 1. Third time it's back to zero, and so on.
Sorry if this doesn't make sense, but does anyone know a way to do this?
Answer: Use `itertools.cycle()`:
from itertools import cycle
myIterator = cycle(range(2))
myIterator.next() # or next(myIterator) which works in Python 3.x. Yields 0
myIterator.next() # or next(myIterator) which works in Python 3.x. Yields 1
# etc.
Note that if you need a more complicated cycle than `[0, 1]`, this solution
becomes MUCH more attractive than the other ones posted here...
from itertools import cycle
mySmallSquareIterator = cycle(i*i for i in range(10))
# Will yield 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4, ...
|
How to detect (view) an area of the screen surrounding a mouse pointer
Question: I'm on Linux, and want to try to recreate Nattyware's Pixie tool for my web
development. gPick is ok, but Pixie is just all around better.
I want to be able to detect and display the area around the mouse pointer.
I've been trying to find a way to show an area around the mouse pointer,
zoomed in with Python.
I have no idea where to start with something like that. I don't want to _save_
any of the images, just show a zoomed in area of where the mouse is in a
window.
**EDIT** : I got something can potentially works. **DON'T RUN THIS, IT
CRASHES!**
import sys, evdev
from Xlib import display, X
from PyQt4 import QtGui
from PyQt4.QtGui import QPixmap, QApplication, QColor
class printImage():
def __init__(self):
self.window = QtGui.QMainWindow()
self.window.setGeometry(0,0,400,200)
self.winId = QApplication.desktop().winId()
self.width = 150
self.height = 150
self.label = QtGui.QLabel('Hi')
self.label.setGeometry(10, 10, 400, 100)
self.label.show()
def drawView(self, x, y):
self.label.setText('abc')
pix = self.getScreenArea(x, y)
self.pic.setPixmap(pix)
def render(self):
self.window.show()
def getScreenArea(self, areaX, areaY):
image = QPixmap.grabWindow(
self.winId,
x = areaX,
y = areaY,
width = self.width,
height = self.height
)
return image
if __name__ == '__main__':
app = QApplication(sys.argv)
view = printImage()
view.render()
display = display.Display(':0')
root = display.screen().root
root.grab_pointer(
True,
X.PointerMotionMask | X.ButtonReleaseMask,
X.GrabModeAsync,
X.GrabModeAsync,
0, 0,
X.CurrentTime
)
while True:
ev = display.next_event()
view.drawView(ev.event_x, ev.event_y)
app.exec_()
Any idea why it just destroys itself? It crashes on the grabWindow()
function.. Is there something else that I can use?
Answer: This works for me on linux, probably it is cross-platform:
import wx
ff=wx.App()
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem
#bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
im = bmp.ConvertToImage()
from the `help`:
ConvertToImage
Creates a platform-independent image from a platform-dependent
bitmap. This preserves mask information so that bitmaps and images can
be converted back and forth without loss in that respect.
|
Cannot compile mysql-python with XCode 4.3/homebrew
Question: Just installed XCode 4.3, now cannot install mysql-python package. I use OS X
Lion 10.7.4, XCode 4.3, homebrew, all installed just few hours ago. Using
homebrew'ed python 2.7.3, mysql 5.5.25
Here is the output:
(lukasz) ~ > pip install MySQL-python
Downloading/unpacking MySQL-python
Running setup.py egg_info for package MySQL-python
warning: no files found matching 'MANIFEST'
warning: no files found matching 'ChangeLog'
warning: no files found matching 'GPL'
Installing collected packages: MySQL-python
Running setup.py install for MySQL-python
building '_mysql' extension
/usr/bin/gcc-4.2 -fno-strict-aliasing -Os -w -pipe -march=native -Qunused-arguments -fwrapv -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/local/Cellar/mysql/5.5.25/include -I/usr/local/Cellar/python/2.7.3/include/python2.7 -c _mysql.c -o build/temp.macosx-10.4-x86_64-2.7/_mysql.o -Qunused-arguments -g
_mysql.c:1: error: bad value (native) for -march= switch
_mysql.c:1: error: bad value (native) for -mtune= switch
error: command '/usr/bin/gcc-4.2' failed with exit status 1
Complete output from command /usr/local/Cellar/python/2.7.3/bin/python -c "import setuptools;__file__='/Users/lukasz/build/MySQL-python/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/lv/p8rbhkk559x1337twh8flq0r0000gn/T/pip-Bvu67T-record/install-record.txt:
running install
running build
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.4-x86_64-2.7/MySQLdb
running build_ext
building '_mysql' extension
/usr/bin/gcc-4.2 -fno-strict-aliasing -Os -w -pipe -march=native -Qunused-arguments -fwrapv -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/local/Cellar/mysql/5.5.25/include -I/usr/local/Cellar/python/2.7.3/include/python2.7 -c _mysql.c -o build/temp.macosx-10.4-x86_64-2.7/_mysql.o -Qunused-arguments -g
_mysql.c:1: error: bad value (native) for -march= switch
_mysql.c:1: error: bad value (native) for -mtune= switch
error: command '/usr/bin/gcc-4.2' failed with exit status 1
----------------------------------------
Command /usr/local/Cellar/python/2.7.3/bin/python -c "import setuptools;__file__='/Users/lukasz/build/MySQL-python/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /var/folders/lv/p8rbhkk559x1337twh8flq0r0000gn/T/pip-Bvu67T-record/install-record.txt failed with error code 1 in /Users/lukasz/build/MySQL-python
Storing complete log in /Users/lukasz/.pip/pip.log
(lukasz) ~ >
Mysql was installed with homebrew without an issue:
(lukasz) ~ > brew info mysql
mysql 5.5.25
http://dev.mysql.com/doc/refman/5.5/en/
Depends on: cmake, readline, pidof
/usr/local/Cellar/mysql/5.5.25 (6382 files, 222M) *
fatal: Not a git repository (or any of the parent directories): .git
https://github.com//homebrew/commits/master/Library/Formula/mysql.rb
Is there a way to manually change that _march_ flag ?
UPDATE:
Oh, I've also installed _Command Line Tools_ (Xcode -> Preferences ->
Downloads) which apparently creates link for _gcc-4.2_ :
(lukasz) ~ > which gcc-4.2
/usr/bin/gcc-4.2
(lukasz) ~ > ls -l `which gcc-4.2`
lrwxr-xr-x 1 root wheel 12 12 Jun 01:36 /usr/bin/gcc-4.2 -> /usr/bin/gcc
(lukasz) ~ > gcc-4.2 --version
i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)
...
Answer: This is may be somewhat off-topic, but if in the end you'll fail to compile
MySQL-python, you can try [PyMySQL](http://www.pymysql.org/) which is pure
python mysql client and can be drop-in replacement for MySQL-python. It works
quite fast.
|
python django dynamic zipping and download
Question: I have a checkbox form. I am trying to make it so if a user checks the "video"
box and submits the form then the video files gets zipped and django generates
a dynamic download that pops up on the user screen. I want the same to happen
for the audio. BUT if the user selects both checkboxes and submits, the the
audio and video files are combined in a zip and a download pops up for the
user. I dont want any of this stored on the disk so I am using StringIO. No
download popup comes up
html
<form>
<input type="checkbox" name="list" value="audio"/> Audio<br />
<input type="checkbox" name="list" value="video"/> Video<br />
<input type="submit" value="submit" />
</form>
python
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cgitb; cgitb.enable()
import cgi
from zipfile import ZipFile
from StringIO import StringIO
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
files = 0
def zip (content):
buffer= StringIO.StringIO()
z= zipfile.ZipFile( buffer, "w" )
z.writestr(content)
z.close()
# generate the file
response = HttpResponse(FileWrapper(z), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=z.zip'
return response
form = cgi.FieldStorage()
mylist = form.getlist('list')
print 'Content-Type: text/plain\n'
for item in mylist:
if item == 'video':
files = '../download/video.html'
zip(files)
elif item == 'audio':
files = '../download/audio.html'
zip(files)
elif item == 'audio' and 'video':
files = '../download/audio.html'+'../download/video.html'
zip(files)
else:
print 'nothing selected'
Answer: For sure the for loop cant work, the third code within the last elif will
never be executed since it is the same as the second `item == 'audio' and
'video'` is the same as `item == 'audio and True'` which is the same as `item
== 'audio'`
I would change the loop code to look a bit more simple
files = []
for item in mylist:
if item == 'video':
files.append('../download/video.html')
elif item == 'audio':
files.append('../download/audio.html')
zip(files)
and then refacor the zip to handle lists of files
def zip (filenames):
buffer= StringIO.StringIO()
z= zipfile.ZipFile( buffer, "w" )
[z.writestr(f) for f in filenames]
z.close()
# generate the file
response = HttpResponse(FileWrapper(z), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=z.zip'
return response
You also have to make sure that the view functions returns what the zip
function returns.
|
python unhandled exception
Question: I am working with **MODO** python scripts. I imported the MODO setting data
into **.cfg** file with the **XML format** .
My .cfg file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<camera>
<Position>
<X>
2.0
</X>
<Y>
0.75
</Y>
<Z>
4.0
</Z>
</Position>
"
"
so on......
Now,i wanted to export this file into my **MODO** application.So,i need to
parse this .**cfg** file (xml format).
I tried this:
#python
import lx
import xml.dom.minidom
from xml.dom.minidom import Node
dom1 = xml.dom.minidom.parse("c:\myfile.cfg")
When i try to run this script in my MODO application,it gives me following
error:

Line 26 is `dom1 = xml.dom.minidom.parse("c:\myfile.cfg")`
How do i parse my .cfg file with xml format using **minidom** object in
**python** ??? Thanx in advance.
Answer: There's a pretty good example on Python [mindom documentation
page](http://docs.python.org/library/xml.dom.minidom.html) you can also
consider using JSON which is easier to write, or serialise Python objects to
JSON.
|
Powerful table widget for a Python GUI
Question: I'd like to program a table-like GUI. Do you know a powerful table widget (for
any GUI), which has ready-made functionality like filtering, sorting, editing
and alike (as seen in Excel)?
Answer: You can use wxGrid - here's some demo code - you need to manage/wire up all
the events yourself on the underlying Table. Its a bit complicated to gove an
explaination in words, here's some code (mostly based on the wx examples
code):
import wx
from wx import EVT_MENU, EVT_CLOSE
import wx.grid as gridlib
from statusclient import JobDataTable, JobDataGrid
app = wx.App()
log = Logger(__name__)
class JobManager(wx.Frame):
def __init__(self, parent, title):
super(JobManager, self).__init__(parent, title=title)
panel = wx.Panel(self, -1)
self.client_id = job_server.register()
log.info('Registered with server as {}'.format(self.client_id))
self.jobs = job_server.get_all_jobs()
grid = self.create_grid(panel, self.jobs)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(grid, 1, wx.ALL|wx.EXPAND)
panel.SetSizer(sizer)
# Bind Close Event
EVT_CLOSE(self, self.exit)
self.Center()
self.Show()
def exit(self, event):
log.info('Unregistering {0} from server...'.format(self.client_id))
job_server.unregister(self.client_id)
job_server.close()
exit()
def create_grid(self, panel, data):
table = JobDataTable(jobs=data)
grid = JobDataGrid(panel)
grid.CreateGrid(len(data), len(data[0].keys()))
grid.SetTable(table)
grid.AutoSize()
grid.AutoSizeColumns(True)
return grid
def main():
frame = JobManager(None, 'Larskhill Job Manager')
app.MainLoop()
if __name__ == '__main__':
job_server = zerorpc.Client()
job_server.connect('tcp://0.0.0.0:4242')
main()
####
ui/client.py
####
import wx
import wx.grid as gridlib
EVEN_ROW_COLOUR = '#CCE6FF'
GRID_LINE_COLOUR = '#ccc'
COLUMNS = {0:('id', 'ID'), 1:('name', 'Name'), 2:('created_at', 'Created'), 3:('status', 'Current Status')}
log = Logger(__name__)
class JobDataTable(gridlib.PyGridTableBase):
"""
A custom wxGrid Table that expects a user supplied data source.
"""
def __init__(self, jobs=None):
gridlib.PyGridTableBase.__init__(self)
self.headerRows = 0
self.jobs = jobs
#-------------------------------------------------------------------------------
# Required methods for the wxPyGridTableBase interface
#-------------------------------------------------------------------------------
def GetNumberRows(self):
return len(self.jobs)
def GetNumberCols(self):
return len(COLUMNS.keys())
#---------------------------------------------------------------------------
# Get/Set values in the table. The Python version of these
# methods can handle any data-type, (as long as the Editor and
# Renderer understands the type too,) not just strings as in the
# C++ version. We load thises directly from the Jobs Data.
#---------------------------------------------------------------------------
def GetValue(self, row, col):
prop, label = COLUMNS.get(col)
#log.debug('Setting cell value')
return self.jobs[row][prop]
def SetValue(self, row, col, value):
pass
#---------------------------------------------------------------------------
# Some optional methods
# Called when the grid needs to display labels
#---------------------------------------------------------------------------
def GetColLabelValue(self, col):
prop, label = COLUMNS.get(col)
return label
#---------------------------------------------------------------------------
# Called to determine the kind of editor/renderer to use by
# default, doesn't necessarily have to be the same type used
# natively by the editor/renderer if they know how to convert.
#---------------------------------------------------------------------------
def GetTypeName(self, row, col):
return gridlib.GRID_VALUE_STRING
#---------------------------------------------------------------------------`
# Called to determine how the data can be fetched and stored by the
# editor and renderer. This allows you to enforce some type-safety
# in the grid.
#---------------------------------------------------------------------------
def CanGetValueAs(self, row, col, typeName):
pass
def CanSetValueAs(self, row, col, typeName):
pass
#---------------------------------------------------------------------------
# Style the table, stripy rows and also highlight changed rows.
#---------------------------------------------------------------------------
def GetAttr(self, row, col, prop):
attr = gridlib.GridCellAttr()
# Odd Even Rows
if row % 2 == 1:
bg_colour = EVEN_ROW_COLOUR
attr.SetBackgroundColour(bg_colour)
return attr
#-------------------------------------------------------------------------------
# Custom Job Grid
#-------------------------------------------------------------------------------
class JobDataGrid(gridlib.Grid):
def __init__(self, parent, size=wx.Size(1000, 500), data_table=None):
self.parent = parent
gridlib.Grid.__init__(self, self.parent, -1) # so grid references a weak reference to the parent
self.SetGridLineColour(GRID_LINE_COLOUR)
self.SetRowLabelSize(0)
self.SetColLabelSize(30)
self.table = JobDataTable()
Give me a shout if it needs clarification.
|
Something like pyHook on OS X
Question: I am actually working with **pyHook** , but I'd like to write my program for
OS X too. If someone know such a module ... I've been looking on the internet
for a while, but nothing really relevant.
-> The idea is to be able to record keystrokes outside the python app. My application is a _community statistics_ builder, so it would be great to have statistics from OS X too.
Thanks in advance ;)
**Edit** : PyHook : Record keystrokes and other things outside the python app
<http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=PyHook_Tutorial>
http://pyhook.sourceforge.net/doc_1.5.0/
<http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=Main_Page>
Answer: As far as I know, there is no Python library for this, so you're going to be
calling native APIs. The good news is that PyObjC (which comes with the built-
in Python on recent OS releases) often makes that easy.
There are two major options. For either of these to work, your app has to have
a Cocoa/CoreFoundation runloop (just as in Windows, a lot of things require
you to be a "Windows GUI executable" rather than a "command line executable"),
which I won't explain how to do here. (Find a good tutorial for building GUI
apps in Python, if you don't know how, because that's the simplest way.)
The easy option is the Cocoa global event monitor API. However, it has some
major limitations. You only get events that are going to another app--which
means media keys, global hotkeys, and keys that are for whatever reason
ignored will not show up. Also, you need to be "trusted for accessibility".
(The simplest way to do that is to ask the user to turn it on globally, in the
Universal Access panel of System Preferences.)
The hard option is the Quartz event tap API. It's a lot more flexible, and it
only requires exactly the appropriate rights (which, depending on the settings
you use, may include being trusted for accessibility and/or running as root),
and it's a lot more powerful, but it takes a lot more work to get started, and
it's possible to screw up your system if you get it wrong (e.g., by eating all
keystrokes and mouse events so they never get to the OS and you can't reboot
except with the power button).
For references on all of the relevant functions, see
<https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/nsevent_Class/Reference/Reference.html>
(for NSEvent) and
<https://developer.apple.com/library/mac/#documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html>
(for Quartz events). A bit of googling should turn up lots of sample code out
there in Objective C (for NSEvent) or C (for CGEventTap), but little or
nothing in Python, so I'll show some little fragments that illustrate how
you'd port the samples to Python:
import Cocoa
def evthandler(event):
pass # this is where you do stuff; see NSEvent documentation for event
observer = Cocoa.NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDown, evthandler)
# when you're done
Cocoa.NSEvent.removeMonitor_(observer)
import Quartz
def evthandler(proxy, type, event, refcon):
pass # Here's where you do your stuff; see CGEventTapCallback
return event
source = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState)
tap = Quartz.CGEventTapCreate(Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionListenOnly,
(Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp)),
handler,
refcon)
Another option, at about the same level as Quartz events, is Carbon events
(starting with InstallEventHandler). However, Carbon is obsolete, and on top
of that, it's harder to get at from Python, so unless you have some specific
reason to go this way, don't.
There are some other ways to get to the same point—e.g., use
DYLD_INSERT_LIBRARIES or SIMBL to get some code inserted into each app—but I
can't think of anything else that can be done in pure Python.
|
Get raw POST body in Python Flask regardless of Content-Type header
Question: So, while ago I asked similar question: [How to get whole request POST body in
Python (Flask)](http://stackoverflow.com/questions/10434599/how-to-get-whole-
request-post-body-in-python-flask)
And I got an answer that actually `flask.request.data` is the raw POST BODY.
But that seems to work only if the request has few additional headers:
headers = {
'Content-type': 'binary/octet-stream',
'Content-length': len(postBody),
'Content-transfer-encoding': 'binary',
}
If those headers are not present, the `flask.request.data` will be empty:
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=['POST'])
def parse_request():
data = flask.request.data # but data will be empty unless the request has the proper content-type header...
So now I found the request is actually `application/x-www-form-urlencoded`
(which is default mimetype) then I could take the data like this:
app = Flask(__name__)
@app.route('/', methods=['POST'])
def parse_request():
data = flask.request.data # but data will be empty unless the request has the proper content-type header...
if not data:
data = request.form.keys()[0]
But I'm not sure that I could count on it...
So, is there a way to be able to obtain the raw post body of any post request,
regardless of the headers?
Answer: I'm using Flask 0.10.1, and if you look at the source code, it turns out that
you can call
request.get_data()
To get the raw data, regardless of content type. The request data is then
cached, and you can subsequently access `request.data, request.json,
request.form` at will.
However, if you access `request.data` first, it will call `get_data` with
different options, where the form parsing runs first, and the actual request
data read from the stream is never stored; `request.form, request.json` etc.
then has nothing to work with.
|
Hiding command-line dialog in py2exe
Question: Hi When I compile my python script with py2exe, everything works well except a
usless command-line dialog appears as well as my GUI. Any way to fix this? I
have python 2.7 and my setup script looks like this:
from distutils.core import setup
import py2exe
setup(console=['Main.py'])
Please help!
Answer: Using `setup(windows=['Main.py'])` should remove the command line dialog and
use Main.py as your console, instead.
|
Would this be a reasonable use-case for lazy evaluation?
Question: I have a python class called Video, which represents YouTube videos. Given the
ID of a YouTube video, Video returns an object representing that video.
However, when a Video object is first created, YouTube is not queried. YouTube
is only queried once an attribute is asked for that requires information from
YouTube. Here's how it works:
>>> from video import Video
>>> video = Video('B11msns6wPU')
# 'B11msns6wPU' is the ID of a video
>>> video
Video(youtube_id="B11msns6wPU")
### As of now, no call to YouTube's API has been made
### Next, I ask for the title attribute. The object queries YouTube's API to get
### this information. In doing so, the object is completely initialized
>>> video.title
u'Badly Drawn Boy - Disillusion (directed by Garth Jennings)'
>>> video.duration
u'275'
# no query was made to the API because the object has been already been initialized
I'm not sure if this is technically "lazy evaluation", but it is similar in
flavor. Video objects aren't initialized until the first call for an attribute
is made. I'm wondering if this technique was worth implementing. Obviously, it
makes my code a bit more complicated. What are your thoughts?
Answer: This is sort of a general judgement call, not a hard-and-fast decision.
If the lazy object, the `Video` class instance, is central to your application
then it might make sense to fully initialize it before doing anything else; if
your app is useless without the data, get the data first.
But if your app might have hundreds or thousands of these `Video` instances,
and most of them will not be used, it doesn't make sense to make the user wait
while you init them all. In this case, it would make a lot of sense to defer
the initialization until it is really needed. For example, if you will be
showing a "wall of thumbnails" display, you might need the thumbnail for each
video and the title but you might not need anything else unless the user
clicks on a thumbnail.
I do like the general approach, that the code using the object doesn't need to
know or care whether the object was pre-initialized or not.
|
elaborate SQL query, count(*) limiter not working
Question: I'm afraid I'm no great shakes at SQL, so I'm not surprised I'm having trouble
with this, but if you could help me get it to work (doesn't even have to be
one query), I'd be grateful. trying to analyze some Twitter data using MySQLdb
in Python, I'm running:
for u_id in list:
"
select e.user_id
from table_entities e
inner join table_tweets t on e.id = t.id
where e.type='mention' and t.user_id=%s
group by e.type having count('hashtag') < 3
"
%
(u_id)
(python syntax faked slightly to not show the unimportant stuff)
now, everything before the "group by" statement works fine. I'm able to
extract user_ids mentioned in a given tweet (id is the PK for table_tweets,
whereas there's another row in table_entities for each mention, hashtag, or
URL) matching the current position of my loop.
however -- and I don't think I'm formatting it anywhere near correctly -- the
group by statement doesn't do a thing. what I mean to do is exclude all
user_ids belonging to tweets (ids) that have 3 or more entries in table_entity
with type=hashtag. I can sort of tell it's not going to work as it is, since
it doesn't actually refer to the id column, but any way that I've tried to do
that (e.g. by trying to make it part of the join clause) throws a syntax
error.
advice is appreciated!
Answer: This doesn't really do what you want.
select e.user_id
from table_entities e
inner join table_tweets t on e.id = t.id
where e.type='mention' and t.user_id=%s
group by e.type having count('hashtag') < 3
* The Select And group by clause aren't doing what you expect. By putting `e.user_id` in the SELECT clause and not in the GROUP BY MySQL will select one arbitrary user_id for each e.type.
* `Having count('literalString')` is the equivalent of `Having COUNT(*)` you can see this yourself by moving the Count('hashtag') to the select clause.
Here's a [Live DEMO](http://sqlfiddle.com/#!2/ad7bb/2) of these points
The result is that your query will only records if there are fewer than 3
mentions for the user.
There are many way to accomplish what you're trying I chose IN (you could also
use Exists or an INNER JOIN to a subquery)
SELECT e.user_id
FROM table_entities e
INNER JOIN table_tweets t
ON e.id = t.id
WHERE e.type = 'mentions'
AND t.user_id =% s
AND e.user_ID IN (SELECT e.user_id
FROM table_entities e
INNER JOIN table_tweets t
ON e.id = t.id
WHERE e.type = 'hashtag'
AND t.user_id =% s
GROUP BY e.user_id
HAVING Count(*) >= 3)
the sub select finds all user ids that have less than 3 records in
table_enties that have an e.type of "hashtag" and the user that matches `% s`
The main select filter for 'mentions' and the user id again. This allows you
you to select for one e.type and filtering on a count of another e.type.
|
Python - checking for characters in date string
Question: I'm just kind of confused with Python at the moment. I want to ask the user to
input the date in a specific format. But I also want to check if there are two
"/" in the input. Ex: MM/DD/YYYY.... or else I would output an error message.
This is what I have so far:
date = str((raw_input("Please enter a date in the form MM/DD/YYYY: ")))
while date[(2),(5)]!="/":
date_input=(str(raw_input("Error: Your date must be in the format YYYY/MM/DD including the slashes, try again: ")))
But I'm pretty stuck. Can anyone help me? Thanks.
Answer: Use `datetime.strptime` to parse the date, and it will tell you when the
format is wrong:
import datetime
d = datetime.datetime.now()
try:
d.strptime(date_str, "%d/%m/%Y")
except ValueError:
print "Bad format!"
|
Django redirect loop in form submit
Question: Just to clarify, this is the first time I'm putting a django website to
production.
I have a simple website in django that works locally. But when I deploy it in
the production server it enters in redirect loop when I submit a form. Then
the browser just tells me that a redirect loop occurred and asks to empty the
cache and so on...
This problem happens in the admin. I don't know if it would happen in the
frontend because it just doesn't have any form in the frontend.
Notes:
* I don't have any funky middlewares.
* I tested in a virtual machine with more or less the same specs of the production server and it works fine.
* The submitted data is correctly handled and saved
* The rest of the website is fine
I'm using apache with wsgi in a shared host, through a .htaccess.
At this point I don't rule out the chance of a dns misconfiguration, but I
already checked and looks fine.
.htaccess:
AddHandler wsgi-script .wsgi
DirectoryIndex app22.wsgi
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app22.wsgi/$1 [QSA,PT,L]
</IfModule>
app22.wsgi:
import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'BTT.settings'
path = '/home/bttmonch/apps'
if path not in sys.path:
sys.path.append(path)
path = '/home/bttmonch/apps/ENV/lib/python2.7/site-packages'
if path not in sys.path:
sys.path.append(path)
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
* * *
At this point I created a fresh new app with just the admin activated, to see
if it was some codding issue and put it on the server. And the same thing
happens.
I am using the same .htaccess and .wsgi files that I mentioned before.
My urls.py is just the basic:
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
I am accessing the app via test.domainname.com. I already tried accessing it
through test.domainname.com, test.domainname.com/app22.wsgi,
domainname.com/test/ and domainname.com/test/app22.wsgi...
Answer: After poking around in the server I stopped getting a redirect loop. But now
every time I save a form I get a 403 error. Than I clear the browser cookies
and all comes back to normal, and the form data is successfully saved in the
database.
At this point a just don't now what else to try...
|
Extract function names and their comments from C code with python (to understand the Linux kernel)
Question: ## Backrground Information
I've just started to learn stuff about drivers and the linux kernel. I want to
understand how a user `write()` and `read()` works. So I started using
[ftrace](http://lwn.net/Articles/322666/) to hopefully see the path the
functions go. But a trace from a single programm like the following is
"enormous".
int main() {
int w;
char buffer[] = "test string mit 512 byte";
int fd = open("/dev/sdd",O_DIRECT | O_RDWR | O_SYNC);
w = write(fd,buffer,sizeof(buffer));
}
I also don't know which functions I could filter, because I don't know the
Linux Kernel and I don't want to throw something important away.
So I've started to work through a function_graph trace. Here is a snip.
[...]
12) 0.468 us | .down_write();
12) 0.548 us | .do_brk();
12) 0.472 us | .up_write();
12) 0.762 us | .kfree();
12) 0.472 us | .fput();
[...]
I saw these `.down_write()` and `.up_write()` and I thought, this is exactly
what I search. So I looked it up. [down_write()
sourcecode](http://lxr.oss.org.cn/source/kernel/rwsem.c#L46):
/*
* lock for writing
*/
void __sched down_write(struct rw_semaphore *sem)
{
might_sleep();
rwsem_acquire(&sem->dep_map, 0, 0, _RET_IP_);
LOCK_CONTENDED(sem, __down_write_trylock, __down_write);
}
But it turned out, that this is just to lock and release locks. Then I've
starte to write a small reference for me, so I don't have to always look up
this stuff, because it fells like there are over 9000. Then I had the idea,
why not, parse these functions and their comments and write them behind the
functions in the trace file? Like this:
[...]
12) 0.468 us | .down_write(); lock for writing
12) 0.548 us | .do_brk();
12) 0.472 us | .up_write(); release a write lock
12) 0.762 us | .kfree();
12) 0.472 us | .fput();
[...]
## The main Problem
So I've started to think about how I can achieve this. I would like to do it
with python, because I feel most comfortable with it.
**1\. Problem**
To match the C functions and comments, I have to define and implement a
recursive matching grammar :(
**2\. Problem**
Some functions are just wrappers and have no comments. For example `do_brk()`
wraps `__do_brk()` and the comment is only over the `__do_brk()`
So I thought, that maybe there are other sources for the comments. Maybe docs?
Also it's possible, that this "doc generation" with python has somebody
already implemented.
Or is my way to understand a system `read()` `write()` very unintelligent? Can
you give me tipps how I should dig deeper?
Thank you very much for reading,
Fabian
Answer: Parsing comments is quite hard in practice. Parsing kernel code is not
specially easy.
First, you should understand _precisely_ what a [system
call](http://en.wikipedia.org/wiki/System_call) is in the [linux
kernel](http://en.wikipedia.org/wiki/Linux_kernel), and how applications use
them. The [Linux Assembly HowTo](http://tldp.org/HOWTO/Assembly-HOWTO/) has
good explanations.
Then, you should understand the organization of the Linux kernel. I strongly
suggest reading some good books on this.
Exploring the kernel source code with automatic tools is a big amount of work
(months, not days). You might consider the
[coccinelle](http://coccinelle.lip6.fr/) tool (for so called "semantic
patches"). You could also consider customizing the GCC compiler with plugins,
or better yet, with [MELT](http://gcc-melt.org/) extensions
(MELT is a high-level domain specific language to extend GCC; I am its main
designer & implementor).
If working with GCC, you'll get all the power of GCC internal representations
and processing in the middle-end (but at this stage comments are lost).
What you are trying to do is probably much more ambitious that what you
initially thought. See also Alexandre Lissy's work, e.g. [model-checking the
linux kernel](http://blip.tv/opensuse/model-checking-the-linux-kernel-
alexandre-lissy-4764861) and the papers he will present at [Linux Symposium
2012](http://www.linuxsymposium.org/2012/) (july 2012)
|
How do I fix this image upload error in my website? Site is built on Python
Question: My site, which is built on Python/Postgresql with django, has an area where
you can upload an image. When I try to upload an image on it, nothing happens
and I receive this error message notification via e-mail:
> Traceback (most recent call last):
>
> File ".. /lib/python/django/core/handlers/b ase.py ", line 85, in
> get_response response = callback(request, *callback_args, **callback_kwargs)
>
> File “../lib/python/django/contrib/auth/de corators.py ", line 67, in
> **call** return self.view_func(request, *args, **kwargs)
>
> File ".. /app/bmwrr/views/assessment.py ", line 231, in
> upload_assessment_media import Image
>
> ImportError: No module named Image
>
> , POST:, COOKIES:{'sessionid': '1918628422885ccc8265fe7f9229332f'},
> META:{'CONTENT_LENGTH': '1741174', 'CONTENT_TYPE': 'multipart/form-data;
> boundary=---- WebKitFormBoundary5S1a4kvt7BfnTMgl', 'DOCUMENT_ROOT':
> '/home/bmwrr/www.sitename.com/app/bmwrr', 'GATEWAY_INTERFACE': 'CGI/1.1',
> 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/
> xml;q=0.9,*/*;q=0.8', 'HTTP_ACCEPT_CHARSET':
> 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_ENCODING':
> 'gzip,deflate,sdch', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',
> 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'keep-alive',
> 'HTTP_CONTENT_LENGTH': '1741174', 'HTTP_COOKIE':
> 'sessionid=1918628422885ccc8265fe7f9229332f', 'HTTP_HOST': 'sitename.com',
> 'HTTP_ORIGIN': 'http://sitename.com', 'HTTP_REFERER':
> 'http://sitename.com/assessment/4127/', 'HTTP_USER_AGENT': 'Mozilla/5.0
> (Windows NT 6.1; WOW64) AppleWebKit/ 536.5 (KHTML, like Gecko)
> Chrome/19.0.1084.56 Safari/536.5', 'PATH_INFO': '/assessment/upload/4127/',
> 'PATH_TRANSLATED': '../app/bmwrr/assessment/upload/4127/' , 'QUERY_STRING':
> '', 'REDIRECT_STATUS': '200', 'REDIRECT_URI':
> '/app.fcgi/assessment/upload/4127/', 'REMOTE_ADDR': '108.36.115.245',
> 'REMOTE_PORT': '49482', 'REQUEST_METHOD': 'POST', 'REQUEST_URI':
> '/assessment/upload/4127/', 'SCRIPT_FILENAME':
> '/home/bmwrr/www.sitename.com/app/bmwrr/app.fcgi' , 'SCRIPT_NAME':
> '/app.fcgi', 'SERVER_ADDR': '108.179.XXX.XXX', 'SERVER_NAME':
> ‘sitename.com', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1',
> 'SERVER_SOFTWARE': 'lighttpd/1.4.28', 'wsgi.errors': , 'wsgi.input': ,
> 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once':
> False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0)}>
Answer: You neeed to install [PIL](http://www.pythonware.com/products/pil/), if you
have installed pip, you only need to install it with:
pip install pil
But do you could need some libraries like libjpeg62-dev
|
Performance of individual vs. total import
Question: I've started to obsess about imports relative to instance spin-up latency. Got
me thinking...
I use a separate, central kinds.py module for all my Model.db class
definitions. Different handler/task modules will import the classes they use
from it. Was wondering about the tradeoffs of doing a global "import kinds"
vs. a series of "from kinds import ...". If the entire kinds.py is not needed,
is it faster to do the individual imports? Or, is the process python/GAE uses
to work through the individual imports going to be faster? Maybe some break
even point at n% of the global total exists?
Answer: There is no difference in speed between these two options. Python has to parse
the whole file anyway.
In fact strictly speaking, there might even be a difference in the other
direction: with `from kinds import ...`, Python would have to create and
assign each reference, which adds a (tiny, tiny) load.
|
Plotting a masked surface plot using python, numpy and matplotlib
Question: I'm plotting a surface using matplotlib 1.1.0.
The plot Z axis is masked like so:
Zm = ma.masked_where((abs(z_grid) < 1.09) & (abs(z_grid) > 0.91), (z_surface))
surf = ax.plot_surface(X, Y,Zm, rstride=2, cstride=2, cmap=colors,linewidth=0, antialiased=False)
But I'm not seeing the mask applied on the plot. I plotted the mask itself as
a subplot
surf = ax.plot_surface(X, Y,ma.getmask(Zm), rstride=2, cstride=2, cmap=colors,linewidth=0, antialiased=False)
Which worked, so I know my mask does actually contain True values.
Full code:
from pylab import *
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy
from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib import patches
from matplotlib.figure import Figure
from matplotlib import rcParams
fig = plt.figure(figsize=plt.figaspect(0.5))
ax = fig.add_subplot(1, 2, 1,projection='3d')
pole_positions_orig = [-0.6+0.73j];
zero_positions_orig = [0.29-0.41j];
surface_limit = 1.7;
min_val = -surface_limit;
max_val = surface_limit;
surface_resolution = 0.0333;
X = numpy.arange(min_val,max_val,surface_resolution)
Y = numpy.arange(min_val,max_val,surface_resolution)
X, Y = numpy.meshgrid(X, Y)
z_grid = X + Y*1j;
z_surface = z_grid*0;
pole_positions = numpy.round(pole_positions_orig,1) + surface_resolution/2+(surface_resolution/2)*1j;
zero_positions = numpy.round(zero_positions_orig,1) + surface_resolution/2 +(surface_resolution/2)*1j;
for k in range(0, len(zero_positions)):
z_surface = z_surface + 20*log10((z_grid - zero_positions[k].real - zero_positions[k].imag*1j));
z_surface = z_surface + 20*log10((z_grid - zero_positions[k].real + zero_positions[k].imag*1j));
for k in range(0, len(pole_positions)):
z_surface = z_surface - 20*log10((z_grid - pole_positions[k].real - pole_positions[k].imag*1j));
z_surface = z_surface - 20*log10((z_grid - pole_positions[k].real + pole_positions[k].imag*1j));
colors = cm.jet;
colors.set_bad('k');
Zm = ma.masked_where((abs(z_grid) < 1.09) & (abs(z_grid) > 0.91), (z_surface))
z_surface = Zm;
surf = ax.plot_surface(X, Y,z_surface, rstride=2, cstride=2, cmap=colors,linewidth=0, antialiased=False)
ticks = [-1, 1];
z_ticks = [-30,-20,-10,0,10,20,30];
ax.set_xticks(ticks);
ax.set_yticks(ticks);
ax.set_zticks(z_ticks);
ax.set_xlabel('Re')
ax.set_ylabel('Im')
ax.set_zlabel('Mag(db)',ha='left')
plt.setp(ax.get_zticklabels(), fontsize=7)
plt.setp(ax.get_xticklabels(), fontsize=7)
plt.setp(ax.get_yticklabels(), fontsize=7)
ax = fig.add_subplot(1, 2, 2,projection='3d')
surf = ax.plot_surface(X, Y,ma.getmask(z_surface), rstride=2, cstride=2, cmap=colors,linewidth=0, antialiased=False)
ax.grid(b=None);
show();
This is what I have:

This is what I want (from matlab):

What am I missing?
Answer: Fraxel mentioned that surface_plot doesn't support masking. In order to get
around the issue, this is what I did:
I basically manually masked the z axis data by setting every masked value to
numpy.nan like so:
Zm = ma.masked_where((abs(z_grid) < 1.02) & (abs(z_grid) > 0.98), (z_surface))
z_surface[where(ma.getmask(Zm)==True)] = numpy.nan

However, it messed up my colormap scaling. To fix that, I did this:
cmap = cm.jet
lev = numpy.arange(-30,30,1);
norml = colors.BoundaryNorm(lev, 256)
surf = ax.plot_surface(X, Y, z_surface,...,norm = norml)

Not 100% what I wanted, but a good compromise nonetheless.
|
Python: How to correctly use external functions
Question: This is something I've seen a fair bit of documentation on but I can't get an
exact answer to this specific gap in my knowledge and I keep running into
walls because of it, nothing seems to really cover it on this level:
I have a few windows, all of them should be draggable, so I'm building a
utilities file. In this file I have this:
def mouseMoveEvent(self, event):
if self.moving: self.move(event.globalPos()-self.offset)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.moving = True; self.offset = event.pos()
def mouseReleaseEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.moving = False
And this will work if I put it into a single file (and don't call from another
one) with the actual window.
The question is, how do I call to this from another file (the one that has the
UI window)?
I am calling to it by
from utils import *
So technically those functions are all accessible simply by typing
mouseReleaseEvent(x,x)
But I need the UI to import those functions, so in the main file after putting
up the 'from utils import *' I type:
self.moving = False
But that errors no matter what I do. So the question is what is the proper way
to enclose the functions listed first (first code block) so that I can call to
them from within my UI file?
Here is my UI code:
#!/usr/bin/env python
import sys
import os
from PyQt4 import QtCore, QtGui
from vibotCss import css
from viUtils import *
class viBadOSUI(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
#setup window
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.resize(300, 150)
center(self)
self.setMouseTracking(True)
#additional code
self.show()
self.setStyleSheet(css)
app = QtGui.QApplication(sys.argv)
window = viBadOSUI()
sys.exit(app.exec_())
I have large gaps in my Python knowledge due to learning and using it solely
from within Autodesk Maya for a long time - I am trying to bridge said gaps
now. Thank you for any help.
Answer: I think what you are looking for are mixins:
For example, in **viUtils.py** you could define:
from PyQt4 import QtCore, QtGui
class Draggable(object):
def mouseMoveEvent(self, event):
try:
if self.moving:
self.move(event.globalPos()-self.offset)
except AttributeError:
pass
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.moving = True; self.offset = event.pos()
def mouseReleaseEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.moving = False
class Centerable(object):
pass # add code here
class CountdownTimer(object):
pass # add code here
By bundling related methods together in mixins, you can add functionality to
your classes (windows) by simply adding the mixin(s) to the base classes:
import sys
import os
from PyQt4 import QtCore, QtGui
from vibotCss import css
import viUtils
class viBadOSUI(QtGui.QDialog,
viUtils.Draggable, viUtils.CountdownTimer):
def __init__(self):
QtGui.QDialog.__init__(self)
#setup window
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.resize(300, 150)
center(self) # You should probably make `center` a method instead of a function and call `self.center()` instead.
self.setMouseTracking(True)
#additional code
self.show()
self.setStyleSheet(css)
app = QtGui.QApplication(sys.argv)
window = viBadOSUI()
sys.exit(app.exec_())
One thing I do not like about my code above is that I could not figure out how
to define a mixin (e.g. `Draggable`) with an `__init__` which gets called
automatically by `viBadOSUI.__init__`. Normally you would use `super` for
this, but it appears `QtGui.QDialog.__init__` does not itself call `super`.
(Actually, I think it might be possible to use `super` **if** you put the
mixins **before** `QtGui.QDialog`, but this relies on trickery which will
break once someone forgets that `QtGui.QDialog` must appear last in the list
of bases.)
Because I could not define an `__init__` method which would work robustly:
class Draggable(object):
def __init__(self):
...
self.moving = False
I instead modified `mouseMoveEvent` to use a `try..except`. This is better
than adding `self.moving = False` directly to `viBadOSUI.__init__` because
this attribute is used only by Draggable, and therefore should be somehow
bundled with `Draggable`. Setting the mixin and then **also** having to
remember to initialize an attribute just so the mixin will work is ugly
programming.
Using `try..except` here is perhaps slightly better than using `if
hasattr(self, 'moving')` since the try is quicker as long as an exception is
not raised, and the exception will be raised only at the beginning before the
first mousePressEvent.
Still, there is room for improvement and I hope someone here will show us a
better way.
An alternative approach would have been to define
class viBadOSUI(QtGui.QDialog):
mouseMoveEvent = viUtils.mouseMoveEvent
mousePressEvent = viUtils.mousePressEvent
mouseReleaseEvent = viUtils.mouseReleaseEvent
This gives you a lot of flexibility to add exactly those methods you want from
viUtils directly into any class you define. However, I think it is a bit too
much flexibility since mouseMoveEvent, mousePressEvent, and mouseReleaseEvent
seem "bundled" to me. They all work together to implement a single piece of
functionality. This is why I like the mixin approach better. Also, adding
`viUtils.Draggable` to the base classes is less typing than adding those 3
lines to every window subclass that you want to be draggable.
By the way, I'd recommend eschewing `from viUtils import *` and using `import
viUtils` instead. It will keep your code more organized in the long run.
|
How do I get SWIG to automatically wrap an emulated "this" pointer to a C struct?
Question: I've got a simple C "class" I have implemented, using function pointers in a
struct to implement the member functions, and passing a pointer to the struct
as the first argument to each function, similar to the implicit "this" pointer
in C++.
%module mytest
%{
typedef struct mytest mytest;
struct mytest {
int data;
int (*func1)(mytest *,int);
void (*func2)(mytest *,int);
};
int f1(mytest *me,int n) { return me->data + n; }
void f2(mytest *me,int n) { me->data += n; }
mytest *mytestNew(int n) {
mytest *me = (mytest*) malloc(sizeof(mytest));
me->data = n;
me->func1 = f1;
me->func2 = f2;
return me;
}
%}
typedef struct mytest mytest;
struct mytest {
int data;
int func1(mytest *,int);
void func2(mytest *,int);
};
extern mytest *mytestNew(int n);
Now my problem is, when the interface is created to whatever language I choose
in the front end, I wind up having to explicitly pass the "this" pointer to
the object, even though the language itself supports hiding this.
For instance, suppose I choose Python. I have to do something like this:
from mytest import *
m = mytestNew(1)
m.func1(m,0)
Where what I really want is to do it like this:
from mytest import *
m = mytestNew(1)
m.func1(0)
I know I could just write some wrapping code, but for my actual project I have
a lot of functions in a lot of objects of existing C code, and multiplying
this by every language that I want to support, this is just too much work! Is
there some way to get SWIG to do this automatically?
Answer: You can do this in a language neutral way in SWIG with just two typemaps
provided you name the parameter something consistent in the SWIG interface as
well as the definitions to allow the typemaps to be applied selectively.
(Unless you wanted all pointers to `mytest` to become "this" pointers by
default of course)
The typemaps you need are:
// Make sure the wraqpped function doesn't expect an input for this:
%typemap(in,numinputs=0) mytest *me "$1=NULL;"
// Slightly abuse check typemap, but it needs to happen after the rest of the arguments have been set:
%typemap(check) mytest *me {
$1 = arg1;
}
The check typemap isn't really intended for use like this, but it's the
easiest way to get the code to be injected after the arguments have been
extracted from the target language and before the actual call is made.
You can also simplify the module with the help of a macro to avoid having to
write and keep in sync the mapping between the function pointers and the
members trick. I ended up with `test.h` as:
#ifdef SWIG
#define MEMBER(name, args) name args
#else
#define MEMBER(name, args) (*name) args
#endif
typedef struct mytest mytest;
struct mytest {
int data;
int MEMBER(func1,(mytest *me,int));
void MEMBER(func2,(mytest *me,int));
};
And the corresponding interface file (test.i):
%module test
%{
#include "test.h"
static int f1(mytest *me,int n) { return me->data + n; }
static void f2(mytest *me,int n) { me->data += n; }
%}
%extend mytest {
mytest(int n) {
$self->data = n;
$self->func1 = f1;
$self->func2 = f2;
}
}
%typemap(in,numinputs=0) mytest *me "$1=NULL;"
%typemap(check) mytest *me {
$1 = arg1;
}
%include "test.h"
(This interface file provides a constructor that "creates" the "object"
exactly how a Java programmer would expect - you can call `new` and it sets
the function pointers behind the scenes)
|
Python - run Excel macro
Question: I would like to use Python to run a macro contained in MacroBook.xlsm on a
worksheet in Data.csv.
Normally in excel, I have both files open and shift focus to the Data.csv file
and run the macro from MacroBook. The python script downloads the Data.csv
file daily, so I can't put the macro in that file.
Here's my code:
import win32com.client
import os
import xl
excel = win32com.client.Dispatch("Excel.Application")
macrowb = xl.Workbook('C:\MacroBook.xlsm')
wb1 = xl.Workbook('C:\Database.csv')
excel.Run("FilterLoans")
I get an error, "pywintypes.com_error: (-2147352567, 'Exception occurred.',
(0, u'Microsoft Excel', u"Cannot run the macro 'FilterLoans'. The macro may
not be available in this workbook or all macros may be disabled.",
u'xlmain11.chm', 0, -2146827284), None)"
The error states that FilterLoans is not available in the Database.csv
file...how can I import it?
Answer: 1) you can't have VBA on a *.csv file. You need the *.xlsm file to be the
active workbook. I don't think you need to open the *.csv file at all if your
macro know how to find it.
2) Enable VBA module access in your Office Excel:
File
options
Trust Center
Trust Center Settings
Macro Settings
Enable VBA access
3)I am using this function to run macros:
excel.Application.Run("FilterLoans")
|
Python Mechanize for form with options populated by Javascript
Question: I'm trying to use mechanize to grab prices for New York's metro-north railroad
from this site: <http://as0.mta.info/mnr/fares/choosestation.cfm>
The problem is that when you select the first option, the site uses javascript
to populate your list of possible destinations. I have written equivalent code
in python, but I can't seem to get it all working. Here's what I have so far:
import mechanize
import cookielib
from bs4 import BeautifulSoup
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
br.open("http://as0.mta.info/mnr/fares/choosestation.cfm")
br.select_form(name="form1")
br.form.set_all_readonly(False)
origin_control = br.form.find_control("orig_stat", type="select")
origin_control_list = origin_control.items
origin_control.value = [origin_control.items[0].name]
destination_control_list = reFillList(0, origin_control_list)
destination_control = br.form.find_control("dest_stat", type="select")
destination_control.items = destination_control_list
destination_control.value = [destination_control.items[0].name]
response = br.submit()
response_text = response.read()
print response_text
I know I didn't give you code for the reFillList() method, because it's long,
but assume it correctly creates a list of mechanize.option objects. Python
doesn't complain about me about anything, but on submit I get the html for
this alert:
"Fare information for travel between two lines is not available on-line.
Please contact our Customer Information Center at 511 and ask to speak to a
representative for further information."
Am I missing something here? Thanks for all the help!
Answer: It can't really be done without trying to make sense of the crazy logic in
that function. I suggest a js solution or a full browser like selenium.
|
Change specific value in CSV file via Python
Question: I need the way to change specific value of the column of csv file. For example
I have csv file:
"Ip","Sites"
"127.0.0.1",10
"127.0.0.2",23
"127.0.0.3",50
and I need to change value 23 to 30 of the "127.0.0.2".
I use csv library: import csv
Appreciate any help as I'm new in Python. Thanks!
Answer: This is the solution opening the csv file, changing the values in memory and
then writing back the changes to disk.
r = csv.reader(open('/tmp/test.csv')) # Here your csv file
lines = [l for l in r]
Content of lines:
[['Ip', 'Sites'],
['127.0.0.1', '10'],
['127.0.0.2', '23'],
['127.0.0.3', '50']]
Modifying the values:
lines[2][1] = '30'
Content of lines:
[['Ip', 'Sites'],
['127.0.0.1', '10'],
['127.0.0.2', '30'],
['127.0.0.3', '50']]
Now we only have to write it back to a file
writer = csv.writer(open('/tmp/output.csv', 'w'))
writer.writerows(lines)
|
Eclipse PyDev Breakpoints Show an Different Icon and Don't Work
Question: Breakpoints have been working for me for many weeks, but yesterday they
stopped working. When I create a breakpoint icon shown is not the usual
magnifying glass, but instead is the magnifying glass with a line through it.
I tried the suggestions in [pydev breakpoints not
working](http://stackoverflow.com/questions/9486871/pydev-breakpoints-not-
working)
E.g.
import sys
print 'current trace function', sys.gettrace()
which reports "current trace function main.PyDB object at 0x101416090>> "
I tried accessing breakpoints in another Python project and the breakpoints
there have the same problem. Restarting Eclipse, the Mac and reinstalling
PyDev had no effect.
I tried installing PyDev in another Eclipse installation on my Mac and
breakpoints in Python work find there.
Any ideas, anyone?
Answer: screenshot should be like this:

That is because you have enable "skip all breakpoints" in Eclipse, show it
here: 
Also useful info:
[skip all breakpoints in
eclipse](http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fviews%2Fbreakpoints%2Fref-
skipall_viewaction.htm)
[different breakpoints annotations meanings in
eclipse](http://stackoverflow.com/questions/4079000/what-different-breakpoint-
annotations-mean-in-eclipse)
another alias question:[eclipse-pydev-breakpoint-does-not-stop-and-show-a-
different-icon](http://stackoverflow.com/questions/16851290/eclipse-pydev-
breakpoint-does-not-stop-and-show-a-different-icon)
|
python nested list: replace repeted items in nested list while retaining first occurrence
Question: I have a list of lists and want to replace all the occurrences of the same
word within the entire list/matrix with a dash except the first occurrence. I
have created a separate list that has a count of how many of each element is
in the original list of lists. I want the first occurrence of the word to be
replaced by the item in the count list so the number is there.
table = [['Bacteria', 'Aquificae', 'Persephonella'],
['Bacteria', 'Aquificae', 'Thermovibrio'],
['Bateria', 'Firmicutes', 'Bacillus']]
countlist = ['Bacteria3', 'Aquificae2', 'Persephonella1', 'Thermovibrio1', 'Firmicutes1', 'Bacillus1']
So I want the list to be like this when I'm done:
table = [['Bacteria3', 'Aquificae2', 'Persephonella1'],
['-', '-', 'Thermovibrio1'],
['-', 'Firmicutes1', 'Bacillus1']]
I want to put this into a tab delimited table after so it won't look so
confusing in the end.
This is what I have currently for replacing the word with the count list
version but is not working:
for num in range(1525):
for n in table[num]:
for s in count:
if n in s:
n = s
I'm stuck on this and any help would be greatly appreciated.
**EDIT** Working in Python 2.6.1
Answer: I can't tell if your table with dashes in is required, or just a step you
think you need to get to the tab delimitated table, this code will get a list
with names appended with totals that can be used to make the tab delimitated
table
from collections import Counter
count= Counter([item for sublist in table for item in sublist])
totals= ["%s%i"%(e,c) for e,c in count.most_common()]
#can then be tab deliminated
"\t".join(totals)
|
How can i use xaxis_date() with barh()?
Question: in the code below, bdate and edate are both datetime.datetime() objects:
pylab.barh(ypos, edate - bdate, left=bdate, height=TRMWidth )
but this throws an AttributeError way down in dates.py._to_ordinalf() :
> File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
> packages/matplotlib/pyplot.py", line 1926, in barh ret = ax.barh(bottom,
> width, height, left, **kwargs) File
> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
> packages/matplotlib/axes.py", line 4774, in barh orientation='horizontal',
> **kwargs) File
> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
> packages/matplotlib/axes.py", line 4624, in bar width = self.convert_xunits(
> width ) File
> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
> packages/matplotlib/artist.py", line 147, in convert_xunits return
> ax.xaxis.convert_units(x) File
> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
> packages/matplotlib/axis.py", line 1312, in convert_units ret =
> self.converter.convert(x, self.units, self) File
> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
> packages/matplotlib/dates.py", line 1125, in convert return date2num(value)
> File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
> packages/matplotlib/dates.py", line 260, in date2num else: return
> np.asarray([_to_ordinalf(val) for val in d]) File
> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
> packages/matplotlib/dates.py", line 189, in _to_ordinalf base =
> float(dt.toordinal())
>
> AttributeError: 'datetime.timedelta' object has no attribute 'toordinal'
i thought it'd be great if i could just shove datetimes at xaxis and have it
work out the details; not so much. any suggestions as to how to make dates
agreaable to xaxis?
Answer: What's happening is that matplotlib doesn't actually use datetime objects for
plotting.
Dates are first converted into an internal floating point format. The
conversion isn't set up to handle timedeltas (which is arguably an oversight).
You can basically do exactly what you wanted, you just need to explictly
convert the dates to matplotlib's internal format first, and then call
`ax.xaxis_date()`.
As a quick example (Most of this is generating data to plot...):
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def drange(start, end, interval=dt.timedelta(days=1)):
output = []
while start <= end:
output.append(start)
start += interval
return output
# Generate a series of dates for plotting...
edate = drange(dt.datetime(2012, 2, 1), dt.datetime(2012, 6, 15),
dt.timedelta(days=5))
bdate = drange(dt.datetime(2012, 1, 1), dt.datetime(2012, 5, 15),
dt.timedelta(days=5))
# Now convert them to matplotlib's internal format...
edate, bdate = [mdates.date2num(item) for item in (edate, bdate)]
ypos = range(len(edate))
fig, ax = plt.subplots()
# Plot the data
ax.barh(ypos, edate - bdate, left=bdate, height=0.8, align='center')
ax.axis('tight')
# We need to tell matplotlib that these are dates...
ax.xaxis_date()
plt.show()

|
Pika basic_publish hangs when publishing on multiple queues
Question: I need to setup multiple queues on an exchange. I would like to create a
single connection, then declare multiple queues (this works) then, publish
messages on the multiple queues (this does not work).
I setup some test code to do this, but it gets hung up on the 2nd publish
everytime. I think it does not like publishing on multiple queues without
closing the connection, as this code works when I publish on a single queue
(even multiple messages on a single queue).
Is there something I need to add to make this work? I would really like to not
have to close the connection between publishes. Also, when I have my consumers
up, they do not see anything when I send to basic_publish()'s when sending on
multiple queues. I do see messages appear almost instantly when I am
publishing on a single queue.
#!/usr/bin/env python
import pika
queue_names = ['1a', '2b', '3c', '4d']
# Variables to hold our connection and channel
connection = None
channel = None
# Called when our connection to RabbitMQ is closed
def on_closed(frame):
global connection
# connection.ioloop is blocking, this will stop and exit the app
connection.ioloop.stop()
def on_connected(connection):
"""
Called when we have connected to RabbitMQ
This creates a channel on the connection
"""
global channel #TODO: Test removing this global call
connection.add_on_close_callback(on_closed)
# Create a channel on our connection passing the on_channel_open callback
connection.channel(on_channel_open)
def on_channel_open(channel_):
"""
Called when channel opened
Declare a queue on the channel
"""
global channel
# Our usable channel has been passed to us, assign it for future use
channel = channel_
# Declare a set of queues on this channel
for queue_name in reversed(queue_names):
channel.queue_declare(queue=queue_name, durable=True,
exclusive=False, auto_delete=False,
callback=on_queue_declared)
#print "done making hash"
def on_queue_declared(frame):
"""
Called when a queue is declared
"""
global channel
print "Sending 'Hello World!' on ", frame.method.queue
# Send a message
channel.basic_publish(exchange='',
routing_key=frame.method.queue,
body='Hello World!')
# Create our connection parameters and connect to RabbitMQ
connection = pika.SelectConnection(pika.ConnectionParameters('localhost'), \
on_connected)
# Start our IO/Event loop
try:
connection.ioloop.start()
except KeyboardInterrupt:
print "interrupt"
# Gracefully close the connection
connection.close()
# Loop until we're fully closed, will stop on its own
#connection.ioloop.start()
Answer: My solution to this was to have a variable keep track of whether all my queues
were declared or not.
In on_queue_declared(), I would check this variable and, if all my queues were
declared, then I start publishing messages. I believe attempting to publish
messages before getting back all the Queue.DeclareOks was causing the issues.
|
How to execute shell command get the output and pwd after the command in Python
Question: How can I execute a shell command, can be complicated like normal command in
bash command line, get the output of that command and pwd after execution?
I used function like this:
import subprocess as sub
def execv(command, path):
p = sub.Popen(['/bin/bash', '-c', command],
stdout=sub.PIPE, stderr=sub.STDOUT, cwd=path)
return p.stdout.read()[:-1]
And I check if user use `cd` command but that will not work when user use
symlink to cd or other wierd way to change directory.
and I need a dictionary that hold `{'cwd': '<NEW PATH>', 'result': '<COMMAND
OUTPUT>'}`
Answer: If you use `subprocess.Popen`, you should get a pipe object that you can
`communicate()` for the command output and use `.pid()` to get the process id.
I'd be _really_ surprised if you can't find a method to get the current
working directory of a process by pid...
e.g.: <http://www.cyberciti.biz/tips/linux-report-current-working-directory-
of-process.html>
|
django remove tags from string python
Question: I want to remove all html tags except from my string with python i use this:
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
But this remove all my html tags.
Answer: If I understand it right, you want to strip html tags, but to keep some
specific ones ? If that's the case - then just keep monitoring the start/end
tags, and process them if needed. Example:
MY_TAGS = ["tag1", "tag2"]
MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def handle_starttag(self, tag, attrs):
if tag in MY_TAGS:
self.fed.append("<%s>" % tag) # tag is only string, no < or >.
def handle_endtag(self, tag):
if tag in MY_TAGS:
self.fed.append("</%s>" % tag)
|
Python win32com.adsi module limits number of returned members from AD
Question: Using the following code...
import win32com.adsi
DNC=win32com.adsi.ADsGetObject('LDAP://rootDSE').Get('DefaultNamingContext')
path = 'LDAP://cn=BIG_GROUP,ou=Groups,'+DNC
groupobj = win32com.adsi.ADsGetObject(path)
users = groupobj.member
print len(users)
The output is always a maximum 1500, even if BIG_GROUP contains several
thousand members. How can I execute this query in a way that returns all
members of BIG_GROUP?
Answer: AD returns N results at a time from a large attribute (like member), where N
is the max range retrieval size. The directory supports something called
ranged retrieval where you can fetch groupings of up to 1500 values per fetch.
You should use the ranged retrieval control against the directory. I don't
know if your LDAP API supports this but the docs should answer.
Here is a bit more in the way of info, from the [MSFT
docs](http://msdn.microsoft.com/en-
us/library/windows/desktop/aa367017%28v=vs.85%29.aspx)
|
Best way to eliminate duplicates in a list, but keep previous relative order
Question: > **Possible Duplicate:**
> [How do you remove duplicates from a list in Python whilst preserving
> order?](http://stackoverflow.com/questions/480214/how-do-you-remove-
> duplicates-from-a-list-in-python-whilst-preserving-order)
> [Does Python have an ordered
> set?](http://stackoverflow.com/questions/1653970/does-python-have-an-
> ordered-set)
I find myself doing the following quite frequently:
list_of_items # I have a list of items
set(list_of_items) # I want to remove duplicates
However, in converting to a `set`, I lose the initial ordering I had in the
list, which is important.
What is the best way to remove duplicates in a list AND keep the initial
(relative) ordering of the list?
Answer: This is somewhat of an abuse of list comprehensions, but:
seen = set()
item_list = [seen.add(item) or item for item in item_list if item not in seen]
|
parsing a tab-separated file in Python
Question: I'm trying to parse a tab-separated file in Python where a number placed k
tabs apart from the beginning of a row, should be placed into the k-th array.
Is there a built-in function to do this, or a better way, other than reading
line by line and do all the obvious processing a naive solution would perform?
Answer: You can use [the `csv` module](http://docs.python.org/library/csv.html) to
parse tab seperated value files easily.
import csv
with open("tab-separated-values") as tsv:
for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
...
Where `line` is a list of the values on the current row for each iteration.
Edit: As suggested below, if you want to read by column, and not by row, then
the best thing to do is use the `zip()` builtin:
with open("tab-separated-values") as tsv:
for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
...
|
how do I make a fork or non-blocking system call in python
Question: This is related to [this
question](http://stackoverflow.com/questions/204017/how-do-i-execute-a-
program-from-python-os-system-fails-due-to-spaces-in-path) but with a
different take.
In Ubuntu, I use Autokey, which uses python to automate keystrokes it
observes. So I have `<super>+e` mapped to open Gedit, `<shift>+<super>+3` to
open OOwriter, etc etc. When I make one of these calls, I cannot make another
one until the previous program called has exited.
Here's a sample of the script it executes:
import subprocess
subprocess.call("/opt/openoffice.org3/program/scalc")
... same behavior using:
import os
os.system("/opt/openoffice.org3/program/scalc")
This all worked smoothly in my previous Ubuntu 10.04LTS, but things have
changed since then and I can't repeated make these calls.
**Would you please help me with how to fork or do something to "get back" from
that subprocess.call() without waiting for the program to exit?** I tried
nohup and backgrounding `/opt/openoffice.org3/program/scalc &` but those do
nothing (probably breaks something in Autokey and Py)
* * *
**Answer:** the answer below didn't actually work, but got me snooping around
more and I found another [SO
answer](http://stackoverflow.com/questions/1613713/in-python-how-can-i-do-a-
non-blocking-system-call) which did work for my situation!
#Enter script code -- mapped to <super>+e
import thread
thread.start_new_thread(os.system,('gedit',))
This totally worked!! I can hit `<super>+e` 2 or 3 times in a row and it keeps
adding tabs to gedit. :) This script makes Autokey act as though the command
in quotes is typed at the command line.
Answer: It's as easy as using `Popen` instead of `call`:
import subprocess
subprocess.Popen("/opt/openoffice.org3/program/scalc")
`call` should never have worked that way since it has to return the exit code,
meaning the program would actually have to exit.
|
qmtest not running on CENTOS. build on Mac OS x
Question: I downloaded qmtest for Mac OS X, and build and installed it on MAc OS-X m/c
and then copied the relevant site-packages/binary file into CENT-OS m/c so
that I could run qmtest from cENT-os m/c.
But an error that I am getting.
Traceback (most recent call last):
File "/usr/bin/qmtest", line 74, in <module>
import qm.test.cmdline
File "/data/build/spike/python/install/lib/python2.7/site-packages/qm/test/cmdline.py", line 20, in <module>
import base
File "/data/build/spike/python/install/lib/python2.7/site-packages/qm/test/base.py", line 483, in <module>
import qm.host
File "/data/build/spike/python/install/lib/python2.7/site-packages/qm/host.py", line 18, in <module>
from qm.executable import RedirectedExecutable
File "/data/build/spike/python/install/lib/python2.7/site-packages/qm/executable.py", line 41, in <module>
import qm.sigmask
ImportError: /data/build/spike/python/install/lib/python2.7/site-packages/qm/sigmask.so: invalid ELF header
As the m/c where I want to run qmtest is CENTOS type, so how could i remove
this error, or where can i get the version of QMTEST for centos m/c so that i
could copy relevant files over there, and then work it out.
qmtest is running perfectly on MacOS X m/c.
Answer: You should take the source for QMTest and build it on CentOS itself.
CentOS and Mac are not binary compatible.
|
background process in python with -e option on terminal
Question: I want to write a console based wrapper to launch a program, and it works fine
unless I try to run it using 'urxvt -e myscript' or some variant. For example:
test.py
#!/usr/bin/python2.7
import subprocess
print 'Press enter to launch'
raw_input()
subprocess.Popen( ['firefox'] )
If i run this in a terminal with ./test.py, it works as expected. Firefox
launches, the script exists. But if i try this with 'urxvt -e ./test.py' the
script opens, runs, and firefox launches. But when the script exits firefox is
killed.
How can I launch a program so its not killed when the script exits if I run
the script using 'term -e script'.
Edit: To be more clear: I want to launch a new terminal which runs the python
script. The script does its thing and launches the program. Then the script
exits, the terminal closes, and the program remains running.
Answer: add the ampersand symbol (&) to the command you launch.
subprocess.Popen( ['firefox &'] )
|
Call non-native Java code from Python
Question: I want to be able to call certain methods and such that are contained in a
Java jar that is already running (It is guaranteed that it will be running). I
have found things like Jython, but those only seem to be able to access Java's
native classes and such.
Answer: **Check out this:[Calling Java from
Python](http://stackoverflow.com/questions/3652554/calling-java-from-python)**
"**You could also use Py4J. There is an example on the frontpage and lots of
documentation, but essentially, you just call Java methods from your python
code as if they were python methods:**
from py4j.java_gateway import JavaGateway
> > > gateway = JavaGateway() # connect to the JVM
>>>
>>> java_object = gateway.jvm.mypackage.MyClass() # invoke constructor
>>>
>>> other_object = java_object.doThat()
>>>
>>> other_object.doThis(1,'abc')
>>>
>>> gateway.jvm.java.lang.System.out.println('Hello World!') # call a static
method
As opposed to Jython, one part of Py4J runs in the Python VM so it is always
"up to date" with the latest version of Python and you can use libraries that
do not run well on Jython (e.g., lxml). The other part runs in the Java VM you
want to call.
**The communication is done through sockets instead of JNI and Py4J has its
own protocol (to optimize certain cases, to manage memory, etc.)** "
|
Symbol not found: _PQbackendPID with Django project
Question: Running on MAC os 10.6.8 with postgresSQL installed, as well django - using
python2.7 Also installed psycopg2 and dj-database-url using pip in my virtual
env And added these two lines to my setting.py:
import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
Based on instructions for Heroku in:
<https://devcenter.heroku.com/articles/django#database_settings> When running:
python manage.py runserver
I am getting this error:
ImportError: dlopen(/Users.... venv/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Symbol not found: _PQbackendPID
Referenced from: /Users.... venv/lib/python2.7/site-packages/psycopg2/_psycopg.so
Expected in: dynamic lookup
I kept searching for hours and tried all kind of thing including the advice
on: [Mac OS X Lion Psycopg2: Symbol not found:
_PQbackendPID](http://stackoverflow.com/questions/6999105/mac-os-x-lion-
psycopg2-symbol-not-found-pqbackendpid) to no avail.
Wonder if anyone had such an issue and had any luck.
Answer: I had the same problem. Instead of installing the dependencies as Heroku
suggests using
pip install Django psycopg2 dj-database-url
clone whatever repo you're hoping to run in venv, keeping its original
settings.py. Then:
source venv/bin/activate
to activate the new environment, `cd` into your new repo, and `python
manage.py runserver`. Should be set.
Alternatively, you could remake PostGreSQL, and run again, but that's a bit
more of a task - it would work for psycopg2, though. As far as I can tell that
issue comes from using an 64 or i386 build when you should be using a 32 build
- but I'm not sure about this, and the above solution works well to solve the
problem and use venv for what you're actually going to be using it for, most
likely.
|
python 3 new to classes
Question: I'm .self taught in python and need some help with a really simple class I'm
trying to write. I would like to use everything outside of the InitLog class
in various modules WITHOUT needing to declare a new class variable everytime i
use it (eg i dont want to declare betty = Initlog in every (numerous) module i
wish to use the class ... is there a way i can do this? Thanks in advance
import os
import sys
import pdb
import fileinput
import Tools
class InitLog:
def __init__(self):
pass
def Update(self):
self.sound = sound
self.engine = engine
def save(self):
self.summery = 'sound: ' + self.sound + '\n'
self.summery += 'engine: ' + self.engine + '\n'
#lock for use within threads
Tools.Locked.State.LogAddress = False
while Tools.Locked.State.LogAddress == True: pass
Tools.Locked.State.LogAddress = True
try: os.remove(path + '/' + self.dest + '/init.log')
except: pass
path = os.getcwd()
if not os.path.exists(self.dest): os.makedirs(self.dest)
if os.path.isfile(path + '/' + self.dest + '/init.log') == True: os.remove(path + '/' + self.dest + '/init.log')
with open (path + '/' + self.dest + '/init.log', mode='a', encoding='utf-8') as a_file:
a_file.write(self.summery)
Tools.Locked.State.LogAddress = False
InitLog.Update.sound = 'on'
InitLog.Update.engine = 'google.txt'
InitLog.save()
error: `TypeError: save() takes exactly 1 positional argument (0 given)`
**EDIT:**
I have shorted the above example to be less redundant.
Here is the working code i was previously using (before attepting my original
request to use InitLog without declaring a new class variable)
import os
import sys
import pdb
import fileinput
import Tools
class InitLog:
def __init__(self):
pass
def setLaws(self):
self.sound = 'off'
self.engine = 'google.txt'
def Update(self):
while Tools.Locked.State.LogAddress == True: pass
Tools.Locked.State.LogAddress = True
try: os.remove(path + '/' + self.dest + '/init.log')
except: pass
summery = 'sound: ' + self.sound + '\n'
summery += 'engine: ' + self.engine + '\n'
path = os.getcwd()
if not os.path.exists(self.dest): os.makedirs(self.dest)
if os.path.isfile(path + '/' + self.dest + '/init.log') == True: os.remove(path + '/' + self.dest + '/init.log')
with open (path + '/' + self.dest + '/init.log', mode='a', encoding='utf-8') as a_file:
a_file.write(summery)
Tools.Locked.State.LogAddress = False
Tools.Locked.State.LogAddress = False
log = InitLog()
log.setLaws()
log.sound = 'on'
log.Update()
I would like to not need to say `log = InitLog()` for every module i need to
use this class
Answer: You are not properly using classes.
The following code:
InitLog.Update.sound = 'on'
InitLog.Update.engine = 'google.txt'
InitLog.Update.countryspec = '.com'
InitLog.Update.limit = '10'
....
is accessing the method object of Update of the class InitLog, and adding
attributes to it on the fly. This attributes are being attached to the
function object not the class or an object of that class.
`error: TypeError: save() takes exactly 1 positional argument (0 given)` save
is a method it requires a parameter self which is set implicitly when an
instance of an InitLog object calls it.
If you want a single instance through your code, then you can follow the
singleton design pattern.
first I recommend you go through
<http://docs.python.org/tutorial/classes.html>
Maybe you are tying to achieve something like this:
class InitLog:
sound = None
engine = None
summary = ""
@classmethod
def save(cls):
cls.summary = 'sound: ' + cls.sound + '\n'
cls.summary += 'engine: ' + cls.engine + '\n'
InitLog.sound = 'On'
InitLog.engine = 'google.txt'
InitLog.save()
print InitLog.summary
Heres a different design which may be more reusable later on.
class InitLog:
custom_instance = None
def __init__(self):
self.sound = None
self.engine = None
self.summary = ''
@property
def sound(self):
return self.sound
@sound.setter
def set_sound(self, sound):
self.sound = sound
@property
def engine(self):
return self.engine
@engine.setter
def set_engine(self, engine):
self.engine = engine
@property
def summary(self):
return self.summary
@summary.setter
def set_summary(self, summary):
self.summary = summary
def update(self, **kwargs):
if 'sound' in kwargs:
self.sound = kwargs['sound']
if 'engine' in kwargs:
self.engine = kwargs['engine']
def save(self):
self.summary = 'sound: ' + self.sound + '\n'
self.summary += 'engine: ' + self.engine + '\n'
@classmethod
def get_custom_instance(cls):
if not cls.custom_instance:
cls.custom_instance = InitLoc()
cls.custom_instance.engine = 'google.txt'
cls.custom_instance.sound = 'on'
return cls.custom_instance
obj = InitLog.get_custom_instance()
obj.save()
print obj.summary #ouput => 'sound: on\nengine: google.txt\n'
print obj.update(sound = 'Off')
obj.save()
print obj.summary #output =>'sound: Off\nengine: google.txt\n'
There are many ways of designing python classes or classes in general for that
matter, this are just 2, please go through the guide and find the best design
that suits your needs.
|
PySide - QSvgWidget renders embedded SVG files incorrectly
Question: I try to render embedded svg file using QSvgWidget. My file "front.svg" looks
like this:
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" width="500" height="500" id="svgfile">
<rect style="fill:#ff0000;" id="rect1" width="150" height="200"/>
<svg x="100" y="100">
<rect style="fill:#00ff00;" id="rect2" width="200" height="120"/>
</svg>
</svg>
This file looks quite normal in Chrome, or Inkscape, but in svgwidget it looks
strange. Only green rectangle is visible, and red is very small, and hidden
behind the green one. Here is my python code:
import sys
from PySide.QtGui import QApplication
from PySide.QtSvg import QSvgWidget
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = QSvgWidget('front.svg')
widget.show()
sys.exit(app.exec_())
Does anybody knows, whether I do something wrong, or is it some bug in PySide?
Answer: You can get it to render correctly by removing the extra internal `<svg>` tag,
and moving the x and y attributes to the `<rect>` element:
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" width="500" height="500" id="svgfile">
<rect style="fill:#ff0000;" id="rect1" width="150" height="200"/>
<rect style="fill:#00ff00;" id="rect2" x="100" y="100" width="200" height="120"/>
</svg>
I assume this is a contrived example to test that specific case, though? Is
there a reason you need nested `<svg>` elements?
|
regular expression to split
Question: I try to understand the regex in python. How can i split the following
sentence with regular expression?
"familyname, Givenname A.15.10"
this is like the phonebook in python regex
<http://docs.python.org/library/re.html>. The person maybe have 2 or more
familynames and 2 or more givennames. After the familynames exist ', ' and
after givennames exist ''. the last one is the office of the person. What i
did until know is
import re
file=open('file.txt','r')
data=file.readlines()
for i in range(90):
person=re.split('[,\.]',data[i],maxsplit=2)
print(person)
it gives me a result like this
['Wegner', ' Sven Ake G', '15.10\n']
i want to have something like
['Wegner', ' Sven Ake', 'G', '15', '10']. any idea?
Answer: In the regex world it's often easier to "match" rather than "split". When
you're "matching" you tell the RE engine directly what kinds of substrings
you're looking for, instead of concentrating on separating characters. The
requirements in your question are a bit unclear, but let's assume that
* "surname" is everything before the first comma
* "name" is everything before the "office"
* "office" consists of non-space characters at the end of the string
This translates to regex language like this:
rr = r"""
^ # begin
([^,]+) # match everything but a comma
(.+?) # match everything, until next match occurs
(\S+) # non-space characters
$ # end
"""
Testing:
import re
rr = re.compile(rr, re.VERBOSE)
print rr.findall("de Batz de Castelmore d'Artagnan, Charles Ogier W.12.345")
# [("de Batz de Castelmore d'Artagnan", ', Charles Ogier ', 'W.12.345')]
Update:
rr = r"""
^ # begin
([^,]+) # match everything but a comma
[,\s]+ # a comma and spaces
(.+?) # match everything until the next match
\s* # spaces
([A-Z]) # an uppercase letter
\. # a dot
(\d+) # some digits
\. # a dot
(\d+) # some digits
\s* # maybe some spaces or newlines
$ # end
"""
import re
rr = re.compile(rr, re.VERBOSE)
s = 'Wegner, Sven Ake G.15.10\n'
print rr.findall(s)
# [('Wegner', 'Sven Ake', 'G', '15', '10')]
|
dynamically instantiate classes in Python
Question: I want to dynamically add `threading.Thread` classes to a thread `queue` based
on a database query. Is that possible?
For example:
import threading, Queue
class worker(threading.Thread):
def run(self):
while True:
print 'doing stuff'
# get jobs from db
jobs = list(db.Jobs.find())
q = Queue.Queue(5)
for job in jobs:
# instantiate a worker thread here.. don't know how to do this
...
# start new worker thread
new_worker_thread.start()
# then add the worker to the queue
q.put(new_worker_thread)
Any advice would be awesome.
Answer: Simply use:
new_worker_thread = worker()
This instantiates a new worker thread. After this you can start and put it in
the queue.
Some more information on threads can be found here:
<http://www.tutorialspoint.com/python/python_multithreading.htm>
Very useful tutorial!
|
Using a loop to check a date with datetime in python?
Question: I am writing a program that uses a gathers information from a file to output
later on, my problem right now is with testing the information given. I want
to test if the code the user inputted is the same as a date in the file. The
file used contains dates and sales in the form YYYY,MM,DD. I am attempting to
use a for loop to test each line of the file against the user input but I am
getting the error that datetime.date is not iterable. Any
solutions/alternatives? Here is the code,
from datetime import date
def DateTest(Date, Position):
firstTry = True
validSyntax = False
if validSyntax == False:
if firstTry == True:
try:
Date = Date.strip().split(',')
Year = int(Date[0])
Month = int(Date[1])
Day = int(Date[2])
Date = date(Year, Month, Day)
except:
print "That is invalid input."
firstTry = False
else:
validSyntax = True
elif firstTry == False:
Date = raw_input("Please input the desired %s date in the form YYYY,MM,DD: " % Position)
try :
Date = startDate.strip().split(',')
Year = int(Date[0])
Month = int(Date[1])
Day = int(Date[2])
Date = date(Year, Month, Day)
except:
print "That is invalid input."
else:
validSyntax = True
print" ok got it"
if validSyntax == True:
for line in Date:
line = line.strip().split(',')
yearTest = int(line[0])
monthTest = int(line[1])
dayTest = int(line[2])
dateTest = date(yearTest, monthTest, dayTest)
if dateTest == Date:
"print debug"
startDate = raw_input("Please input the desired start date: ")
start = "start"
Response = DateTest(startDate, start)
As you can see I test for valid input and then test for the date being in the
file, which tells me datetime is not iterable.
Answer: Use the strptime it will clean up your code.
>>> s = "1994,05,24"
>>> datetime_obj = datetime.datetime.strptime(s, "%Y,%m,%d")
>>> datetime_obj
datetime.datetime(1994, 5, 24, 0, 0)
Notice it gives you a datetime object, if you only want the date you can call
.date() on it.
>>> date_obj = datetime_obj.date()
If you want to loop through a file, you need to have a file object, or a
filename to then convert to a file object. If your file format is csv the csv
module can be helpful, but if the file is just a list of dates, then you may
not need it.
|
Is it possible to iterate through all nodes with py2neo
Question: Is there a way to iterate through every node in a neo4j database using py2neo?
My first thought was iterating through `GraphDatabaseService`, but that didn't
work. If there isn't a way to do it with py2neo, is there another python
interface that would let me?
**Edit:** I'm accepting @Nicholas's answer for now, but I'll update it if
someone can give me a way that returns a generator.
Answer: I would suggest doing that with asynchronous Cypher, something like:
from py2neo import neo4j, cypher
graph_db = neo4j.GraphDatabaseService()
def handle_row(row):
node = row[0]
# do something with `node` here
cypher.execute(graph_db, "START z=node(*) RETURN z", row_handler=handle_row)
Of course you might want to exclude the reference node or otherwise tweak the
query.
Nige
|
How is Shop class supposed to be access in line 60 of shopify.Session in the shop method
Question: I am trying to use python shopify api with OAuth2 and working through the api,
and am trying to move the the django auth sample over to oauth rather than
legacy (and not use django, I am just targetting webapp2 on appengine for a
much simpler example. ;-)
I am running into a problem where after getting a session
shopify_session.shop() is called in my handler and I am getting a NameError:
"global name 'Shop' is not defined".
Looking at the current code the implementation for this method is (at line 59)
def shop(self):
Shop.current()
but I can't see how the class Shop could possibly accessible. the class Shop
is defined in resources.py and isn't imported anywhere in session.py. Is this
a bug in the api code, or is some magic supposed to going on or some other
sort of setup run to inject that class into the session module.
Answer: Oops, that method has improperly ported from the ruby
[shopify_api](https://github.com/shopify/shopify_api) library. I decided to
just remove it entirely, since it was already broken, therefore no apps must
depend on it working, and even in the ruby library it isn't really using the
session instance. The only way it would make sense would be if it temporarily
activated the session then retrieved the current shop.
The [shopify_django_app](https://github.com/shopify/shopify_django_app)
example app is now updated with Oauth2 support, although the instructions and
zip file for django on App Engine still need to be updated.
|
python unhashable type - posting xml data
Question: First, I'm not a python programmer. I'm an old C dog that's learned new Java
and PHP tricks, but python looks like a pretty cool language.
I'm getting an error that I can't quite follow. The error follows the code
below.
import httplib, urllib
url = "pdb-services-beta.nipr.com"
xml = '<?xml version="1.0"?><!DOCTYPE SCB_Request SYSTEM "http://www.nipr.com/html/SCB_XML_Request.dtd"><SCB_Request Request_Type="Create_Report"><SCB_Login_Data CustomerID="someuser" Passwd="somepass" /><SCB_Create_Report_Request Title=""><Producer_List><NIPR_Num_List_XML><NIPR_Num NIPR_Num="8980608" /><NIPR_Num NIPR_Num="7597855" /><NIPR_Num NIPR_Num="10166016" /></NIPR_Num_List_XML></Producer_List></SCB_Create_Report_Request></SCB_Request>'
params = {}
params['xmldata'] = xml
headers = {}
headers['Content-type'] = 'text/xml'
headers['Accept'] = '*/*'
headers['Content-Length'] = "%d" % len(xml)
connection = httplib.HTTPSConnection(url)
connection.set_debuglevel(1)
connection.request("POST", "/pdb-xml-reports/scb_xmlclient.cgi", params, headers)
response = connection.getresponse()
print response.status, response.reason
data = response.read()
print data
connection.close
Here's the error:
Traceback (most recent call last):
File "C:\Python27\tutorial.py", line 14, in connection.request("POST", "/pdb-xml-reports/scb_xmlclient.cgi", params, headers)
File "C:\Python27\lib\httplib.py", line 958, in request self._send_request(method, url, body, headers)
File "C:\Python27\lib\httplib.py", line 992, in _send_request self.endheaders(body)
File "C:\Python27\lib\httplib.py", line 954, in endheaders self._send_output(message_body)
File "C:\Python27\lib\httplib.py", line 818, in _send_output self.send(message_body)
File "C:\Python27\lib\httplib.py", line 790, in send self.sock.sendall(data)
File "C:\Python27\lib\ssl.py", line 229, in sendall v = self.send(data[count:])
TypeError: unhashable type
My log file says that the xmldata parameter is empty.
Any ideas?
Answer: I guess params has to be a string when passing to .request, this would explain
the error, due to the fact, that a hash is not hashable
Try to encode your params first with
params = urllib.urlencode(params)
You can find another code example too at the bottom of:
<http://docs.python.org/release/3.1.5/library/http.client.html>
|
Python simple string formatting error
Question: This is my script which is supposed to parse a list of domains (each seperated
by returns) in a .txt file, separate them into individual domain names, send a
request to a whois site with the domain name, check the response to see if it
is available, and if it is, write it to a new file. so i get a list of only
available names.
**The problem? It's pretty simple i just dont know the language well enough, I
dont know how to get the domain name in a string format so that the request to
the whois site is like this :**
<http://whois.domaintools.com/google.com>
Apparently the %s thing is not working.
Code:
#!/usr/bin/python
import urllib2, urllib
print "Domain Name Availability Scanner."
print "Enter the Location of the txt file containing your list of domains:"
path = raw_input("-->")
wordfile = open(path, "r")
words = wordfile.read().split("n")
words = map(lambda x: x.rstrip(), words)
wordfile.close()
for word in words:
req = urllib2.Request("http://whois.domaintools.com/%s") % (word)
source = urllib2.urlopen(req).read()
if "This domain name is not registered" in source:
f = open("success.txt", "a")
f.write("%s\n") % (word)
f.close()
break
error in terminal:
python domain.py
Domain Name Availability Scanner.
Enter the Location of the txt file containing your list of domains:
-->a.txt
Traceback (most recent call last):
File "domain.py", line 13, in <module>
req = urllib2.Request("http://whois.domaintools.com/%s") % (word)
TypeError: unsupported operand type(s) for %: 'instance' and 'str'
Answer: **Fix the parentheses:**
req = urllib2.Request("http://whois.domaintools.com/%s" % (word))
As well as:
f.write("%s\n" % word)
:)
|
Django: Is Base64 of md5 hash of email address under 30 characters?
Question: I am investigating since a few hours the best way to use the Email address
instead of username in Django authentication. This topic has been discussed
many times but the given results are inconsistent.
1) The answer [here](http://stackoverflow.com/questions/778382/accepting-
email-address-as-username-in-django) points to a
[snippet](http://www.davidcramer.net/code/224/logging-in-with-email-addresses-
in-django.html) that distinguishes the username and email simply by having an
'@'char in it. The max length of email and username is not equal though and
not considered in the answer.
2) The second answer - from the same
[link](http://stackoverflow.com/questions/778382/accepting-email-address-as-
username-in-django) \- from S.Lott (13 votes) is doing some black magic with
admin.site. It doesn't make sense to me what the code is doing, is this the
accepted way of doing it short and sweet?
3) Then I found [this solution](http://www.xairon.net/2011/05/django-email-
only-authentication/), which seems almost perfect (and makes sense to me):
username = uuid.uuid4().hex[:30]
It picks only the first 30 chars of a unique Python generated ID as the
username. But there is still a chance of collision. Then I came across a post
where someone has claimed
> A base64 encoding of an md5 hash has 25 characters
If thats true, couldn't we take the base64 encoding of an md5 hash of the
**email address** and guarantee 100% unique usernames, which are also under 30
character? If this is true, how could this be achieved?
Many Thanks,
Answer: You can do it like this:
>>> from hashlib import md5
>>> h = md5('[email protected]').digest().encode('base64')[:-1]
>>> _
'Vlj/zO5/Dr/aKyJiOLHrbg=='
>>> len(h)
24
You can ignore the last char because it's just a new line. The chance of
collision is the same as the MD5 hash, you don't lose information when you
encode in base64.
>>> original = md5('[email protected]').digest()
>>> encoded = original.encode('base64')
>>> original == encoded.decode('base64')
True
|
jython Can't list error
Question: I am trying to convert a python class into Java byte code with Jython (on mac
osx lion)
> ./jython -m compileall /Users/owengerig/Downloads/Code\
> Downloads/cryptPYTHON.py
but get this error, which gives no indication of whats wrong
> Listing /Users/owengerig/Downloads/Code Downloads/cryptPYTHON.py ... Can't
> list /Users/owengerig/Downloads/Code Downloads/cryptPYTHON.py
How my python class is setup ([used this post as
example](http://wiki.python.org/jython/ReplaceJythonc)):
from Crypto.Cipher import AES
import base64
import os
class Crypticle(CryptInterface):
"""Authenticated encryption class
* @param string $key base64-encoded encryption key
* @param integer $key_len length of raw key in bits
Encryption algorithm: AES-CBC
Signing algorithm: HMAC-SHA256
"""
AES_BLOCK_SIZE = 16
@JAVA
def __init__(self, key_string, key_size=192):
assert not key_size % 8
self.key = self.extract_key(key_string, key_size)
self.key_size = key_size
@classmethod
def generate_key_string(cls, key_size=192):
key = os.urandom(key_size / 8)
return base64.urlsafe_b64encode(str(key))
@classmethod
def extract_key(cls, key_string, key_size):
key = base64.urlsafe_b64decode(str(key_string))
assert len(key) == key_size / 8, "invalid key"
return key
@JAVA(String, String)
def encrypt(self, data):
"""encrypt data with AES-CBC"""
aes_key = self.key
pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
data = data + pad * chr(pad)
iv_bytes = os.urandom(self.AES_BLOCK_SIZE)
cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
data = iv_bytes + cypher.encrypt(data)
data_str = base64.urlsafe_b64encode(str(data))
return data_str
@JAVA(String, String)
def decrypt(self, data_str):
"""decrypt data with AES-CBC"""
aes_key = self.key
data = base64.urlsafe_b64decode(data_str)
iv_bytes = data[:self.AES_BLOCK_SIZE]
data = data[self.AES_BLOCK_SIZE:]
cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
data = cypher.decrypt(data)
return data[:-ord(data[-1])]
Also tried this code (per comments below) but go the same error:
class Employee(Object):
def __init__(self):
self.first = "Josh"
self.last = "Juneau"
self.id = "myempid"
def getEmployeeFirst(self):
return self.first
def getEmployeeLast(self):
return self.last
def getEmployeeId(self):
return self.id
Answer: -m compileall takes a directory, not a filename. So you need to execute the following:
./jython -m compileall /Users/owengerig/Downloads/Code\ Downloads/
**Long Explanation**
If you open _jythondirectory_ /Lib/compileall.py:
try:
names = os.listdir(dir)
except os.error:
print "Can't list", dir
names = []
os.listdir() throws an error if it isn't passed a directory as its argument.
Since this is the function used to compile the command-line arguments, and the
main() function does not check if the arguments are directories, this will
fail.
for dir in args:
if not compile_dir(dir, maxlevels, ddir,
force, rx, quiet):
success = 0
**/Long Explanation**
|
Is it possible to make an alias for a module in Ruby?
Question: In Python, you can set an alias for a module with 'as':
import mymodule as mm
But I can't seem to find an equivalent for ruby. I know that you can `include`
rather than `require` a module, but this risks namespace collisions. Is there
any equivalent to Python module aliases?
Answer: Modules in Ruby aren't really that special, so you can just assign them to
another constant:
[4] (pry) main: 0> module TestModule
[4] (pry) main: 0* def self.foo
[4] (pry) main: 0* "test"
[4] (pry) main: 0* end
[4] (pry) main: 0* end
=> nil
[5] (pry) main: 0> tm = TestModule
=> TestModule
[6] (pry) main: 0> tm.foo
=> "test"
|
Python classes--Need explanation
Question: I have a general question on the class definition and its use..THe below code
from one of the book works fine but I have a general questions.
Here we have defined a class Point and creating 2 instance Point1 & Point2.
When calculating the distance for point2, how can we pass the point1 object?
Isn't point1 the point object, whereas the other_point is reprented as a
variable.
Im little confused.
Code:
import math
class Point:
def move(self, x, y):
self.x = x
self.y = y
def reset(self):
self.move(0, 0)
def calculate_distance(self, other_point):
print("Inside calculating distance")
return math.sqrt(
(self.x - other_point.x)**2 +
(self.y - other_point.y)**2)
point1 = Point()
point2 = Point()
point1.reset()
point2.move(5,0)
print(point2.calculate_distance(point1))
Answer: When you create a `Point` object, several things happen.
point1 = Point()
point2 = Point()
One of the things that happens is that any methods belonging to the `Point`
class are _bound_. What this means is that one of the arguments in the method
is _fixed_ , so that it always refers to the instance created. Let's look at
the definition of `calculate_distance`.
def calculate_distance(self, other_point):
print("Inside calculating distance")
return math.sqrt(
(self.x - other_point.x)**2 +
(self.y - other_point.y)**2)
You can probably guess which argument is fixed. When `Point()` is called and
an instance is created, the `self` parameter of `calculate_distnace` is fixed
so that it always refers to that instance. So whenever you do this:
point1.calculate_distance(x)
You're doing the equivalent of this:
Point.calculate_distance(point1, x)
And whenever you do this:
point2.calculate_distance(point1)
You're doing the equivalent of this:
Point.calculate_distance(point2, point1)
|
Replace a string located between
Question: Here is my problem: in a variable that is text and contains commas, I try to
delete only the commas located between two strings (in fact `[` and `]`). For
example using the following string:
input = "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
output = "The sun shines, that's fine [not for everyone] and if it rains, it Will Be better."
I know how to use `.replace` for the whole variable, but I can not do it for a
part of it. There are some topics approaching on this site, but I did not
manage to exploit them for my own question, e.g.:
* [Repeatedly extract a line between two delimiters in a text file, Python](http://stackoverflow.com/questions/7098530/repeatedly-extract-a-line-between-two-delimiters-in-a-text-file-python)
* [Python finding substring between certain characters using regex and replace()](http://stackoverflow.com/questions/4622472/python-finding-substring-between-certain-characters-using-regex-and-replace)
* [replace string between two quotes](http://stackoverflow.com/questions/6686711/replace-string-between-two-quotes)
Answer:
import re
Variable = "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
Variable1 = re.sub("\[[^]]*\]", lambda x:x.group(0).replace(',',''), Variable)
First you need to find the parts of the string that need to be rewritten (you
do this with `re.sub`). Then you rewrite that parts.
The function `var1 = re.sub("re", fun, var)` means: find all substrings in te
variable `var` that conform to `re`; process them with the function `fun`;
return the result; the result will be saved to the `var1` variable.
The regular expression "[[^]]*]" means: find substrings that start with `[`
(`\[` in re), contain everything except `]` (`[^]]*` in re) and end with `]`
(`\]` in re).
For every found occurrence run a function that convert this occurrence to
something new. The function is:
lambda x: group(0).replace(',', '')
That means: take the string that found (`group(0)`), replace `','` with `''`
(remove `,` in other words) and return the result.
|
Error on "pip install --upgrade distribute"
Question: Installed python via homebrew as such:
brew install python --universal --framework
Followed the instructions over at
<https://github.com/mxcl/homebrew/wiki/Homebrew-and-Python> to install pip and
upgrade distribute. pip install appeared to go fine, but whenever I try to use
pip to upgrade distribute or install virtualenv as such
pip install --upgrade distribute
or
pip install virtualenv
I get the following error:
> Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in
> from pkg_resources import load_entry_point File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py",
> line 2603, in working_set.require(**requires**) File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py",
> line 666, in require needed = self.resolve(parse_requirements(requirements))
> File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py",
> line 565, in resolve raise DistributionNotFound(req) # XXX put more info
> here pkg_resources.DistributionNotFound: pip==1.0.2
Not proficient enough in python to know what is going on here so if anyone
knows how to correct this it would be appreciated.
My $PATH looks like this:
>
> /Users/wg/.rvm/gems/ruby-1.9.3-p125@rails3_2/bin:/Users/wg/.rvm/gems/ruby-1.9.3-p125@global/bin:/Users/wg/.rvm/rubies/ruby-1.9.3-p125/bin:/Users/wg/.rvm/bin:/usr/local/bin:/usr/local/share/python:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/git/bin
... and when I run `which pip` I get `/usr/local/bin/pip` (not sure if this is
the problem and if so, what to do to get it to use the right version of pip).
EDIT:
Wanted to include that I'm running Lion OS 10.7 with the latest build of XCode
and the Command utilities installed. Also, don't know if this helps, but I
thought I'd include the results of running "which easy_install" as well ...
returns:
> /usr/local/share/python/easy_install
Not sure if that is perhaps related as well.
* * *
Thanks much!
Answer: I practice, I find running
pip install --upgrade setuptools
before
pip install --upgrade distribute
pip install --upgrade pip
solves my problem when running `pip install --upgrade distribute`.
|
Solution: Python3 Tkinter Jump from one window to another with back and next buttons
Question: I've been studying tkinter in python3 and find it very hard to find good
documentation and answers online. To help others struggling with the same
problems I decided to post a solution for a simple problem that there seems to
be no documentation for online.
Problem: Create a wizard-like program, that presents the user with a series of
windows and the user can move between the windows clicking next and back -
buttons.
The solution is:
* Create one root window.
* Create as many frames as you have windows to present to the user. Attach all frames to the root window.
* Populate each frame with all the widgets it needs.
* When all the frames have been populated, hide each frame with the `grid_forget()` method but leave the first frame unhidden so that it becomes the visible one. All the child widgets on the frame will be hidden with the frame.
* When the user clicks on Next or Back buttons on a window, call a subroutine that hides other frames (with `grid_forget()`) and makes the one that is needed visible (with `grid()`).
* When you want the program to end, use the destroy - method for the root window.
So you will be creating a single window and showing different frames on it.
(By the way, the best place to start studying tkinter is:
<http://www.tkdocs.com/tutorial/index.html>)
Here is a sample implementation in Python3. It has 3 simple windows, each with
a text label and two buttons to navigate through different windows.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Creates three "windows" that the user can navigate through using Back and Next - buttons.
import tkinter
import tkinter.ttk
def create_widgets_in_first_frame():
# Create the label for the frame
first_window_label = tkinter.ttk.Label(first_frame, text='Window 1')
first_window_label.grid(column=0, row=0, pady=10, padx=10, sticky=(tkinter.N))
# Create the button for the frame
first_window_quit_button = tkinter.Button(first_frame, text = "Quit", command = quit_program)
first_window_quit_button.grid(column=0, row=1, pady=10, sticky=(tkinter.N))
first_window_next_button = tkinter.Button(first_frame, text = "Next", command = call_second_frame_on_top)
first_window_next_button.grid(column=1, row=1, pady=10, sticky=(tkinter.N))
def create_widgets_in_second_frame():
# Create the label for the frame
second_window_label = tkinter.ttk.Label(second_frame, text='Window 2')
second_window_label.grid(column=0, row=0, pady=10, padx=10, sticky=(tkinter.N))
# Create the button for the frame
second_window_back_button = tkinter.Button(second_frame, text = "Back", command = call_first_frame_on_top)
second_window_back_button.grid(column=0, row=1, pady=10, sticky=(tkinter.N))
second_window_next_button = tkinter.Button(second_frame, text = "Next", command = call_third_frame_on_top)
second_window_next_button.grid(column=1, row=1, pady=10, sticky=(tkinter.N))
def create_widgets_in_third_frame():
# Create the label for the frame
third_window_label = tkinter.ttk.Label(third_frame, text='Window 3')
third_window_label.grid(column=0, row=0, pady=10, padx=10, sticky=(tkinter.N))
# Create the button for the frame
third_window_back_button = tkinter.Button(third_frame, text = "Back", command = call_second_frame_on_top)
third_window_back_button.grid(column=0, row=1, pady=10, sticky=(tkinter.N))
third_window_quit_button = tkinter.Button(third_frame, text = "Quit", command = quit_program)
third_window_quit_button.grid(column=1, row=1, pady=10, sticky=(tkinter.N))
def call_first_frame_on_top():
# This function can be called only from the second window.
# Hide the second window and show the first window.
second_frame.grid_forget()
first_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def call_second_frame_on_top():
# This function can be called from the first and third windows.
# Hide the first and third windows and show the second window.
first_frame.grid_forget()
third_frame.grid_forget()
second_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def call_third_frame_on_top():
# This function can only be called from the second window.
# Hide the second window and show the third window.
second_frame.grid_forget()
third_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
def quit_program():
root_window.destroy()
###############################
# Main program starts here :) #
###############################
# Create the root GUI window.
root_window = tkinter.Tk()
# Define window size
window_width = 200
window_heigth = 100
# Create frames inside the root window to hold other GUI elements. All frames must be created in the main program, otherwise they are not accessible in functions.
first_frame=tkinter.ttk.Frame(root_window, width=window_width, height=window_heigth)
first_frame['borderwidth'] = 2
first_frame['relief'] = 'sunken'
first_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
second_frame=tkinter.ttk.Frame(root_window, width=window_width, height=window_heigth)
second_frame['borderwidth'] = 2
second_frame['relief'] = 'sunken'
second_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
third_frame=tkinter.ttk.Frame(root_window, width=window_width, height=window_heigth)
third_frame['borderwidth'] = 2
third_frame['relief'] = 'sunken'
third_frame.grid(column=0, row=0, padx=20, pady=5, sticky=(tkinter.W, tkinter.N, tkinter.E))
# Create all widgets to all frames
create_widgets_in_third_frame()
create_widgets_in_second_frame()
create_widgets_in_first_frame()
# Hide all frames in reverse order, but leave first frame visible (unhidden).
third_frame.grid_forget()
second_frame.grid_forget()
# Start tkinter event - loop
root_window.mainloop()
Answer: As you've taken the liberty to post an answer as a question. I'd like to post
a comment as an answer and suggest that perhaps you should contribute this to
TkDocs (click their [About tab](http://www.tkdocs.com/about.html) and they
talk about contributing to the site).
I think it'd be better if that site were to improved with more examples than
to turn this site into a cookbook. I think you can also contribute to the
[Active State recipes](http://code.activestate.com/recipes/), and they seem to
be the carriers of the torch for Tcl/Tk, so Tkinter stuff makes a lot of sense
there too.
|
python lxml find <fb:comments /> tag
Question: I'm using lxml to parse an html that has a facebook comments tag that looks
like that:
<fb:comments id="fb_comments" href="http://example.com" num_posts="5" width="600"></fb:comments>
I am trying to select it to get the href value but when i do a
`cssselect('fb:comments')` i get the following error:
The pseudo-class Symbol(u'comments', 3) is unknown
Is there a way to do it?
**Edit:** The code:
from lxml.html import fromstring
html = '...'
parser = fromstring(html)
parser.cssselect('fb:comments') #raises the exception
Answer: The [`cssselect()`](http://lxml.de/cssselect.html) method parses the document
using given [CSS selector](http://www.w3.org/TR/CSS2/selector.html)
expression. In your case the colon character (`:`) is a XML namespace prefix
separator (i.e. `<namespace:tagname/>`) which is confused with CSS pseudo-
class syntax (i.e. `tagname:pseudo-class`).
According to [lxml manual](http://lxml.de/cssselect.html#namespaces) you
should use `namespace-prefix|element` syntax in `cssselect()`in order to to
find a tag (`comments`) with a namespace prefix (`fb`). So:
from lxml.html import fromstring
html = '...'
parser = fromstring(html)
parser.cssselect('fb|comments')
|
PyV8, can I manipulate DOM structure?
Question: Lets assume that we have PyV8:
import PyV8
ctxt = PyV8.JSContext()
and a python DOM structure, for example `xml.dom`
How can I feed a .js-file to PyV8 so that it could change DOM-structure that I
have.
If I had it's content:
$("#id").remove();
I want dom item to be removed.
[PyV8](http://code.google.com/p/pyv8/) has perfect hello-world example. But
I'd like to see something usefull.
To be clear, what I want to do is:
`"Javascript file"` \-->-- **magic** \-->-- `DOM, (already built with html
file) and changed now with passed javascript file`
Answer: A good example for what you're trying to do can be found here:
<https://github.com/buffer/thug>
It's a python http client executing JS via PyV8 for security research
purposes, but can be strapped down easily for simpler needs.
|
Log in Profile in python
Question: Is there any way that we can print the user name of the person who has logged
in the system in the file? the file is an output file of python.
Answer: You could look into `os.environ`.
In [1]: import os
In [2]: os.environ['LOGNAME']
Out[2]: 'lev'
|
How to make XPath return 'None' in Python if no data found?
Question: XPath returns nothing if a child element has no text value. In this case,
rating has no data, so I want it to say so - None or nothing in this child
instead of just ignoring it. Your input is much appreciated.
**XML :**
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
<rating></rating>
</book>
<book>
<title lang="hindi">Learning XML</title>
<price>39.95</price>
<rating></rating>
</book>
</bookstore>
**Python :**
>>> import lxml.html as lh
>>> bk=open('book.xml','r')
>>> bkout=lh.parse(bk)
>>> bk.close()
>>> bkout.xpath('//book/*/text()')
['Harry Potter', '29.99', 'Learning XML', '39.95']
>>> bkout.xpath('//book/* and not(text())/text()')
True
**Desired Output :**
['Harry Potter', '29.99', '', 'Learning XML', '39.95', '']
or
['Harry Potter', '29.99', None, 'Learning XML', '39.95', None]
Answer: Remove the "text()":
In [16]: [x.text for x in bk.xpath("//book/*")]
Out[16]: ['Harry Potter', '29.99', None, 'Learning XML', '39.95', None]
|
Python multiprocess debugging
Question: I'm trying to debug a simple python application but no luck so far.
import multiprocessing
def worker(num):
for a in range(0, 10):
print a
if __name__ == '__main__':
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
p.start()
I want to set a breakpoint inside the for-loop to track the values of 'a' but
non of the tools that I tried are able to do that. So far I tried debuging
with:
* PyCharm and get the following error: ImportError: No module named pydevd - <http://youtrack.jetbrains.com/issue/PY-6649> It looks like they are still working on a fix for this and from what I understand, no ETA on this
* I also tried debuging with Winpdb - <http://winpdb.org> but it simply won't go inside my 'worker' method and just print the values of 'a'
I would really appreciate any help with this!
Answer: I copied everything in `/Applications/PyCharm\ 2.6\
EAP.app/helpers/pydev/*.py` to `site-packages` in my virtualenv and it worked
for my (I'm debugging celery/kombu, breakpoints work as expected).
|
How to create a loop that shuts down when given answer in python?
Question: what I am wanting to do is randomly generate two numbers that equal a given
number. Yet to allow for this to get the desired answer I want it to be
random. That is the problem.
a=(1,2,3,4,5,6,7,8,9,)
from random import choice
b=choice(a)
c=choice(b)
d= c+b
if d == 10:
#then run the rest of the program with the value's c and b in it
#probably something like sys.exit goes here but I am not sure to end \/
else:
# i have tryied a few things here but I am not sure what will loop it around*
* * *
(thanks for the help :D)
I have know created a list called 'right' and know trying to append values a
and b to the list yet that is not working. For I am knowing running the
program _'in for trail in range(100)'_ so I get the answer. Yet the values are
not appending into the new list right. Which is the problem. Then what I am
going to do it read values 0 and 1 in the list right and then use them.(sorry
its not that well done for at school) **This is for fractions not adding to a
given variable. This bit second but is.**
import sys
right=(0)
y=x+x
from trail in range(y)
a=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
from random import choice
A=choice(a)
B=choice(a)
d=A/B
if d==1:
right.append(A)
right.append(B)
else:
x.append(1)
Answer:
from random import choice
a = range(1, 10)
b = c = 0
while b + c != 10:
b = choice(a)
c = choice(a) # You meant choice(a) here, right?
But this accomplishes the same thing:
b = choice(a)
c = 10 - b
For decimal numbers betweeen 0 and 10:
from random import uniform
b = uniform(0, 10)
c = 10 - b
|
Python Tkinter Listbox Unbind the Default Selection
Question: I find this feature of automatic selection to item index 0 in the Listbox a
nuisance. In my script, I have 3 listboxes called lb1,lb2 and lb3. If user
selects any items on lb2 or lb3, I intend to pop up a MessageBox to ask the
user to only select items from lb1. However, due to the automatic selection
items index 0 in lb2 and lb3, whenever I click on item in lb1, the MessageBox
also appears.
Question: How can I disable the initial selection of item index 0 in ListBox?
This is part of my script to call MessageBox if user selects items from lb2 or
lb3:
if lb2.get(ACTIVE) or lb3.get(ACTIVE):
tkMessageBox.showwarning("Warning","Please select from lb1 ")
Please advice! Any other ways to perform the intended action will also do.
Thanks.
Answer: What OS are you using?
If I execute this code (taken from the Tkinter Listbox reference page on
effbot.org) on Windows, there is no default selection made in the listbox.
from Tkinter import *
master=Tk()
listbox=Listbox(master)
listbox.pack()
for item in ['one','two','three','four']:
listbox.insert(END, item)
**EDIT :** OK, now I see what you're asking. You want to check the
`curselection` method first before trying to use `get(ACTIVE)`.
if listbox.curselection():
item = listbox.get(ACTIVE)
Does that help? You can find a [more complete example
here](http://www.tkdocs.com/tutorial/morewidgets.html).
|
What if I put two kinds of encoded strings, say utf-8 and utf-16, in one file?
Question: In Python, for example:
f = open('test','w')
f.write('this is a test\n'.encode('utf-16'))
f.write('another test\n'.encode('utf-8'))
f.close()
That file gets messy when I re-open it:
f = open("test")
print f.readline().decode('utf-16') # it leads to UnicodeDecodeError
print f.readline().decode('utf-8') # it works fine
However if I keep the texts encoded in one style (say utf-16 only), it could
read back ok. So I'm guessing mixing two types of encoding in the same file is
wrong and couldn't be decoded back, even if I do know the encoding rules of
each specific string? Any suggestion is welcome, thank you!
Answer: This is usually a bad idea, but in your case it doesn't work because you
encode newlines as well.
In UTF-16, _every_ character is encoded to two bytes, including the newline
you wrote. Because you read your file line by line, python will give you all
data from the file up to the next newline byte, but in UTF-16 that could mean
that one of the two bytes is still included in the returned data resulting in
an incomplete UTF-16 byte stream.
To understand this, you need to understand UTF-16 encoding in more detail.
When writing 16-bit data as 2 bytes of 8 bits, computers need to decide which
byte to write to the file first. This decision can go two ways, and is called
[endianess](https://en.wikipedia.org/wiki/Endianess); like Gulliver's
Lilliputs, computer systems prefer either Big or Little endian ordering.
An UTF-16 data stream is thus written in one of two orderings, and a [Byte
Order Mark](https://en.wikipedia.org/wiki/Byte_order_mark) or "BOM" is written
first to flag which one was choosen.
Your newline is thus either encoded as `'\n\x00'` or `'\x00\n'`, and on
reading that null byte (`\x00`) is either part of the UTF-16 data you decode,
or the UTF-8 data (where it is ignored). So, if you encode UTF-16 as big
endian, things work (but you have a stray null byte), but if you encode as
little endian, things break.
Basically, encoded data should be treated strictly as binary data and you
should use a different method to delineate different pieces of encoded text,
_or_ you should only use encodings where newlines are strictly encoded as
newlines.
I'd use a length prefix, read that first, then read that number of bytes from
the file for each encoded piece of data.
>>> import struct
>>> f = open('test', 'wb')
>>> entry1 = 'this is a test\n'.encode('utf-16')
>>> struct.pack('!h', len(entry1)))
>>> f.write(entry1)
>>> entry2 = 'another test\n'.encode('utf-8')
>>> f.write(struct.pack('!h', len(entry2)))
>>> f.write(entry2)
>>> f.close()
I've used the [`struct` module](http://docs.python.org/library/struct.html) to
write fixed-length length data. Note that I write the file as binary, too.
Reading:
>>> f = open('test', 'rb')
>>> fieldsize = struct.calcsize('!h')
>>> length = struct.unpack('!h', f.read(fieldsize))[0]
>>> print f.read(length).decode('utf-16')
this is a test
>>> length = struct.unpack('!h', f.read(fieldsize))[0]
>>> print f.read(length).decode('utf-8')
another test
>>>
Again the file is opened in binary mode.
In a real-life application you probably have to include the encoding
information per entry as well.
|
Python OpenCV stereo cam blind one?
Question: My system is Linux HPDebian 3.2.0-2-amd64 #1 SMP x86_64 GNU/Linux Python 2.7,
OpenCV2 I can use only 1 cam. My question is How to get a video feed from 2
cams ? I had read c++ version but I prefer python. It is easier for non-
programmer.
I don't understand why my webcam works only Wleft, but WRight is blank-gray
windows And at the command line
VIDIOC_QBUF: Invalid argument
continue to flood my command line.
OpenCV-Python has a ready-made package of stereo program, but I need to access
the elements of each cam because I want to test my algorithm.
URLs, Book. Any help would be appreciated. Student
My attempt:
'''
Simple Stereo feed
'''
import cv
cv.NamedWindow("wLeft", cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow("wRight", cv.CV_WINDOW_AUTOSIZE)
captureL = cv.CaptureFromCAM(0)
captureR = cv.CaptureFromCAM(1)
def repeat():
frameL = cv.QueryFrame(captureL)
cv.ShowImage("wLeft", frameL)
frameR = cv.QueryFrame(captureR)
cv.ShowImage("wRight", frameR)
while True:
repeat()
if cv.WaitKey(33)==27:
break
cv.DestroyAllWindows()
===============================================
**Update 1**
Answer to your questions
1. In current OpenCV-Python. I can not find any command, but I when I comment out the Leftcam, Rightcam works. And vice versa.
2. Yes, I just found it!. I redirected command and carefully searched.
**libv4l2: error turning on stream: No space left on device**
3. They are identical. OKER193.
4. I can use it just only 1 cam Left or Right only. Can not get a video feed from two of them simulataneously.
5. I have no hubs. I don't know it is a real port or not, but I connect it left and right of my notebook.
http://opencv-users.1802565.n2.nabble.com/Multiple-Camera-Read-Error-
td7001563.html
I tried cv.ReleaseCapture()
def repeat():
frameL = cv.QueryFrame(captureL)
cv.ShowImage("wLeft", frameL)
cv.ReleaseCapture(captureL)
frameR = cv.QueryFrame(captureR)
cv.ShowImage("wRight", frameR)
cv.ReleaseCapture(captureR)
I got the errors:
...
VIDIOC_QUERYMENU: Invalid argument //Many lines
...
Traceback (most recent call last):
File "55.py", line 19, in <module>
repeat()
File "55.py", line 13, in repeat
cv.ReleaseCapture(captureL)
AttributeError: 'module' object has no attribute 'ReleaseCapture'
I really wonder
<http://opencv.willowgarage.com/documentation/python/highgui_reading_and_writing_images_and_video.html?highlight=releasecapture>
CaptureFromCAM last line say To release the structure, use ReleaseCapture.
This function may be dropped out.
Wandering around and found this
<http://superuser.com/questions/431759/using-multiple-usb-webcams-in-linux>
Then I check my resolution per cam is 640x480 as a normal. And my webcam is
1.1/2.0 USB interface.
root@HPDebian:~# v4l2-ctl -d /dev/video0 --list-formats
ioctl: VIDIOC_ENUM_FMT
Index : 0
Type : Video Capture
Pixel Format: 'YUYV'
Name : YUV 4:2:2 (YUYV)
Then check another cam
root@HPDebian:~# v4l2-ctl -d /dev/video1 --list-formats
ioctl: VIDIOC_ENUM_FMT
Index : 0
Type : Video Capture
Pixel Format: 'YUYV'
Name : YUV 4:2:2 (YUYV)
At this point I am not sure about my USB notebook. It may be a hub inside. I
will try reduce the resolution and post my result again.
========================================================================
**Update 2**
Try time.sleep(1) from Martin.
VIDIOC_QUERYMENU: Invalid argument //Many lines
libv4l2: error setting pixformat: Device or resource busy
HIGHGUI ERROR: libv4l unable to ioctl S_FMT
libv4l2: error setting pixformat: Device or resource busy
libv4l1: error setting pixformat: Device or resource busy
HIGHGUI ERROR: libv4l unable to ioctl VIDIOCSPICT
libv4l2: error turning on stream: No space left on device
VIDIOC_STREAMON: No space left on device
VIDIOC_QBUF: Invalid argument //Many lines until Ctrl C
I will try this again in M$ xp.
===============================================
**Update 3**
Still using Linux. M$ xp is busy. This time I del the c1 and c2. Since I don't
know how to release camera. I believe that API of driver I use is allow only 1
device access kernel per time. So I try this one.
def repeat1():
c1 = cv.CreateCameraCapture(0)
i1 = cv.QueryFrame(c1)
cv.ShowImage("WebCAM1", i1)
del(c1)
def repeat2():
c2 = cv.CreateCameraCapture(1)
i2 = cv.QueryFrame(c2)
cv.ShowImage("WebCAM2", i2)
del(c2)
Program run very sluggish and WebCAM1 is distorted, WebCAM2 is not.
Answer: Some things to check:
1. Is OpenCV picking up all your cameras? Try [checking how many cameras are attached](http://stackoverflow.com/questions/7322939/how-to-count-cameras-in-opencv-2-3).
2. Do you get any error other error messages? i.e. is there a stack track with the one you've mentioned?
3. Are there any hardware differences between the two cameras?
4. What happens if you comment out all the stuff about lcam? i.e. is it just something to do with the second camera or is it something to do with running two cameras at once.
5. Try plugging them into seperate hubs as per [this suggestion](http://forum.openframeworks.cc/index.php?PHPSESSID=m5l5gsjssc5pv0jimj4nbsvst2&/topic,8179.0.html)
|
How to compare one element of one array numerically to another element in another array in python
Question: I am new to python and made two arrays for two tab delimited input files.I was
searching for a way to compare the column(element) of one array numerically to
element of another array. Is there any way to do that.My code till now is as
below
#!/usr/bin/python
import sys
from array import *
#print len(sys.argv)
if len(sys.argv) != 4:
print 'Usage: python scores.py <infile1> <infile2> <outfile>'
sys.exit(1)
f1 = open ("12877overlappedallvariants.gvf", "r")
f2 = open ("unmatched.12877overlappedallvariants.gvf", "r")
f3 = open ("out.txt", "w")
for line in f1.readlines():
cols = line.split('\t')
#print cols[5:6]
for line in f2.readlines():
cols1 = line.split('\t')
#print cols1[5:6]
I tried this below section of code but does not work
slice1 = cols[5:6]
slice2 = cols1[5:6]
new_list = []
for element in slice1:
if element in slice2:
new_list.append(element)
print new_list
I am trying to see if the element 5 of array1 is equal to, greater than or
less than element 5 of array2. Any help is appreciated. Thanks.
Answer: It's worth noting that these are lists, not arrays. There is a difference.
You are overwriting `cols` every time you loop - meaning you will only get the
last row of data - a list comprehension is in order here to get all the data
you want, or better yet, simply don't store the data at all - do the operation
you want on it.
Your main problem with the comparison is that you are taking list slices,
rather than just taking the element you need. This is overcomplicating what
you are trying to do.
So, as I mentioned in the comments, there are a lot of improvements you can
make to your initial code - mainly the `with` statement and the `csv` module.
So first of all, use the `with` statement to open your files. We use
`csv.reader()` as well, using the `"excel-tab"` dialect as it's a tab-
delimited file, and `csv.QUOTE_NONNUMERIC` to tell it the values are numbers,
so we don't have to convert them from strings later. Note that if only certain
values are numbers, you will either need to quote all non-numeric values to
use this method, or convert those values explicitly and not use it.
with open("file1.tsv") as file1, open("file2.tsv") as file2:
rows = csv.reader(file2, dialect="excel-tab", quoting=csv.QUOTE_NONNUMERIC)
rows1 = csv.reader(file2, dialect="excel-tab", quoting=csv.QUOTE_NONNUMERIC)
To perform your check, simply do something like this (continued on from within
the `with` block above):
for cols, cols1 in zip(rows, rows1): #Use itertools.izip() in 2.x for efficiency.
first = cols[4]
second = cols1[4]
if first < second:
...
elif first == second:
...
else: #first > second
...
Note the use of zip to loop over both files at once. We need to loop over the
files as they return a row at a time, each row being a list of data for each
column. You can then do as you please with the data. I have given an example
of comparing the fifth value (note the index `4` \- python is `0` indexed -
that is, the first value is `0`, so the fifth is `4`).
By doing this all as we loop through the files, we ensure we don't have to
create lists and store the data temporarily - which is useful if we end up
working on large files.
If you needed to use that data a lot later, and wanted it as a list, you could
simply make the two `rows` objects lists, by wrapping a `list()` call around
the `csv.reader()`s.
|
How to parse this web page (and convert into a dictionary) in Python
Question: I want to fetch some data from a certain web page (online book store).
The web pages look like this: <http://www.rob389.com/dp/tr/11/9789754681383>
I want to parse the `<script>` section that contains the following string:
tOBJ.DATA[0].MMM00_ITEM_CODE="9789754681383"
Where _9789754681383_ is the ISBN number.
I first need to find and extract the correct `<script>` section.
Then, I want to iterate through the content of the **tOBJ.DATA[0]** object and
convert it into a dictionary which would look like:
my_dict["MMM00_ITEM_CODE"] = "9789754681383"
my_dict["MMM00_TITLE"] = "Uykusuz Bir Gece"
And so on...
I guess it's possible to do it with python with few number of lines, but I
cannot figure out.
Any suggestions?
Thanks in advance.
PS: Any other parsing suggestions are welcome.
Answer: You can do it with
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) and a little
bit of code:
from bs4 import BeautifulSoup
import urllib2
from urlparse import urlsplit
def isbnExtractor(url):
urlContent = url.strip('/').split('/')
print urlContent[6]
And this should do the trick. Like this:
PS python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from parse import isbnExtractor
>>> url = "http://www.rob389.com/dp/tr/11/9789754681383"
>>> isbnExtractor(url)
9789754681383
|
Where does GAE store permalinks?
Question: So I have the following code GAE code in python and it is a little long but
basically it allows a user to post to a blog and then saves each blog post to
a permalink which the user is redirected to and the user can relink to
forever. The permalink url is just blog/(the blog post ID). So the permalink
is being created in the NewPost handler by the redirect method (correct me if
I am wrong) and and then where is the list of these permalinks being stored?
Is it accessible somehow? Because I cannot see it visually this part is
tripping me up a little.
I learned all this code from Udacity.com but they didn't really explain this
point and I can get it to work but don't understand how it is working.
import os
import re
from string import letters
import webapp2
import jinja2
from google.appengine.ext import db
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
class BlogHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
return render_str(template, **params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
def render_post(response, post):
response.out.write('<b>' + post.subject + '</b><br>')
response.out.write(post.content)
#front page
class MainPage(BlogHandler):
def get(self):
self.write('Hello, Udacity!')
def blog_key(name = 'default'):
return db.Key.from_path('blogs', name)
#creates the database
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
def render(self):
self._render_text = self.content.replace('\n', '<br>')
return render_str("post.html", p = self)
#front of blog with list of last 10 posts
class BlogFront(BlogHandler):
def get(self):
posts = db.GqlQuery("select * from Post order by created desc limit 10")
self.render('front.html', posts = posts)
#displays the permalink page
class PostPage(BlogHandler):
def get(self, post_id):
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
if not post:
self.error(404)
return
self.render("permalink.html", post = post)
#create a new post
class NewPost(BlogHandler):
def get(self):
self.render("newpost.html")
def post(self):
subject = self.request.get('subject')
content = self.request.get('content')
if subject and content:
p = Post(parent = blog_key(), subject = subject, content = content)
p.put()
self.redirect('/blog/%s' % str(p.key().id()))
else:
error = "subject and content, please!"
self.render("newpost.html", subject=subject, content=content, error=error)
app = webapp2.WSGIApplication([('/', MainPage),
('/unit2/welcome', Welcome),
('/blog/?', BlogFront),
('/blog/([0-9]+)', PostPage),
('/blog/newpost', NewPost),
],
debug=True)
UPDATE:
Would it be possible to change the code in the following way to make it a
little more search engine friendy:
class NewPost(BlogHandler):
def get(self):
self.render("newpost.html")
def post(self):
subject = self.request.get('subject')
content = self.request.get('content')
if subject and content:
p = Post(parent = blog_key(), subject = subject, content = content)
p.put()
#the change is in the following line:
self.redirect('/blog/%s/%s' % (str(p.key().id(), str(p.subject)))
else:
error = "subject and content, please!"
self.render("newpost.html", subject=subject, content=content, error=error)
FINAL UPDATE:
I solved the problem of making it more search engine friendly with the
following bit of code:
def post(self):
subject = self.request.get('subject')
content = self.request.get('content')
if subject and content:
p = Post(parent = blog_key(), subject = subject, content = content)
p.put()
subject = p.subject
subject = subject.replace(' ', '25fdsa67ggggsd5')
subject = ''.join(e for e in subject if e.isalnum())
subject = subject.replace('25fdsa67ggggsd5', '-')
subject = subject.lower()
self.redirect('/blog/%s/%s' % (str(p.key().id(), str(subject)))
else:
error = "subject and content, please!"
self.render("newpost.html", subject=subject, content=content, error=error)
Answer: The ID of the blog post is all that is needed to retrieve it front the
datastore, so there is no need for a mapping of any kind. A request comes in
with the permalink URL, the ID is extracted from the URL, the post is
retrieved from the datastore using the ID, the blog post is rendered.
It is a simple and effective strategy, but one area where it falls flat is
search engine optimization. Most search engines would prefer a URL that has
words in it rather than just a string of numbers and characters.
This is commonly called slugging, and it would require you to provide a
mapping between the ID and a string. Several years ago, I wrote a mixin class
that provided easy slugging for AppEngine/Python programs: [sluggable-
mixin](http://code.google.com/p/sluggable-mixin/). It should still work.
|
format conversion of an image in python
Question: I have to write an application for image processing in python. does anyone
know how to convert the file type of an image from JPEG to TIFF?
Answer: Check out the [Python Image Library
(PIL)](http://www.pythonware.com/products/pil/). See this
[tutorial](http://effbot.org/imagingbook/introduction.htm), the PIL is quite
easy to use.
[Supported image
formats](http://infohost.nmt.edu/tcc/help/pubs/pil/formats.html).
To do the conversion you open the image and then save it with the new
extension (which PIL uses to determine what format to use for saving).
import Image
im = Image.open('test.jpg')
im.save('test.tiff') # or 'test.tif'
Note that the official distribution does not support Python 3.x (yet?),
however, at least under Windows there's an [unofficial
version](http://www.lfd.uci.edu/~gohlke/pythonlibs/) available that works with
v 3.x.
|
Application Layout with Groups of single items in Python
Question: I am coming from the PHP world, worked a lot with Joomla. Now I am building a
Python web application and I my first step is to create a user management when
I faced a very basic question: How do you manage all users in one class, when
your model represents only a single database row.
An example will make this more clear. Here's what Joomla did:
JUser::getInstance($userid)
What this did was there is the class `JUser` and it has a static method
`getInstance()` that operated on a static variable that was valid among all
instances. In this way, `JUser` managed all Users while only representing
_one_ user as an instance of the class.
Now on Python I use SQLAlchemy and have a class like this:
class User(Base):
... and so on. Before I now start doing crappy stuff coming over from a crappy
PHP world, I wanted to know: What is the correct and clean approach here?
Build a new `Users` class that holds all users? Or is this static-method
approach a good concept?
I have been googling for some time but I can't seem to find something on this
topic: Building larger applications in Python with the MV(C) model. Anyone
have any good links on this I could read?
In a more specifc way: How do I solve this problem?
Answer: You should create one model class, just like Joomla did:
class User(Base):
...
And then you can use generic functionality of SQLAlchemy, and query for user
you need,
using primary key:
user = session.query(User).get(user_id)
or using unique username/email:
user = session.query(User).filter(User.username==my_username).first()
Speaking of user which is logged in for current HTTP request, web frameworks
usually give you an instance automatically, passing it to HTTP request handler
you're implementing. For example, Django framework gives you user instance
from it's own ORM out of the box, as it has all authentication and session
functionality in it. I also use Flask microframework with Flask-login module
and SQLAlchemy, and there you need to implement a callback, which loads user
instance by user Id, like I said before:
@login_manager.user_loader
def load_user(userid):
# just query for user
return User.query.get(userid) # User.query is Flask-SQLAlchemy extension, it's same to session.query(User).get(userid)
Then you can get your user instance from a thread-local variable:
from flask.ext.login import login_required, current_user
@app.route('/hello/')
@login_required
def my_request_handler():
return "<html><body>Current user is %s</body></html>" % current_user.username
Of course you can implement a static method, if you need a shortcut for
getting user instance by Id:
class User(Base):
...
@classmethod
def by_id(cls, id):
return session.query(cls).get(id)
(where SQLAlchemy's session is somehow defined globally)
For Python/web apps architecture, you can look at
[Django](https://djangoproject.com) — it's very popular and easy to use all-
in-one framework, and it has MVC-like architecture in it. Just [read the
tutorial](https://docs.djangoproject.com/en/1.4/intro/tutorial01/).
(But note that Django's own ORM's functionality is very limited in comparison
to SQLAlchemy, if you'll wish to use Django).
|
Convert non-UTC time string with timezone abbreviation into UTC time in python, while accounting for daylight savings
Question: I am having a hard time converting a string representation of non-UTC times to
UTC due to the timezone abbreviation.
**(update: it seems that the[timezone abbreviations may not be
unique](http://stackoverflow.com/questions/5946499/how-to-get-the-common-name-
for-a-pytz-timezone-eg-est-edt-for-america-new-york?rq=1). if so, perhaps i
should also be trying to take this into account.**)
I've been trying to look for a way around this using datetutil and pytz, but
haven't had any luck.
Suggestions or workaround would be appreciated.
string = "Jun 20, 4:00PM EDT"
**I'd like to convert that into UTC time, accounting for daylight savings when
appropriate.**
**UPDATE:** Found some references that may help more experienced users answer
the Q.
Essentially, I would imagine part of the solution doing the reverse of
[this](http://stackoverflow.com/questions/5946499/how-to-get-the-common-name-
for-a-pytz-timezone-eg-est-edt-for-america-new-york?rq=1).
**FINAL UPDATE (IMPORTANT)**
Taken from the [dateutil docs examples](http://labix.org/python-
dateutil#head-587bd3efc48f897f55c179abc520a34330ee0a62).
**Some simple examples based on the date command, using the TZOFFSET
dictionary to provide the BRST timezone offset.**
> > > parse("Thu Sep 25 10:36:28 BRST 2003", tzinfos=TZOFFSETS)
> datetime.datetime(2003, 9, 25, 10, 36, 28, tzinfo=tzoffset('BRST', -10800))
>>>
>>> parse("2003 10:36:28 BRST 25 Sep Thu", tzinfos=TZOFFSETS)
datetime.datetime(2003, 9, 25, 10, 36, 28, tzinfo=tzoffset('BRST', -10800))
**Combine this with a library[such as found
here.](http://stackoverflow.com/questions/1703546/parsing-date-time-string-
with-timezone-abbreviated-name-in-python/4766400#4766400) and you will have a
solution to this problem.**
Answer: Using [Nas Banov's excellent
dictionary](http://stackoverflow.com/a/4766400/366335) mapping timezone
abbreviations to UTC offset:
import dateutil
import pytz
# timezone dictionary built here: http://stackoverflow.com/a/4766400/366335
# tzd = {...}
string = 'Jun 20, 4:00PM EDT'
date = datetuil.parser.parse(string, tzinfos=tzd).astimezone(pytz.utc)
|
How to get layout correct for matplotlib FigureCanvas in wx.Notebook panel
Question: I've been struggling with this for a few days now. If I don't use a
wx.Notebook, I can get the FigureCanvas to size correctly within a sizer, but
once I place the FigureCanvas inside of a wx.Notebook panel, the plot seems to
ignore the panel sizer. It also has some sort of refresh issue, if you pull it
off of the screen and back on, the plot is gone. Perhaps there is a problem
with the order of commands, but I can't seem to find it. This post: [How to
update a plot with python and
Matplotlib](http://stackoverflow.com/questions/5160558/how-to-update-a-plot-
with-python-and-matplotlib) helped me get this far, but I can't seem to work
out why the plot acts differently once I use it in a wx.Notebook.
Here's what it looks like when it first displays:
<http://static.inky.ws/image/2205/image.jpg>
Here it is after I've pulled off the screen halfway:
<http://static.inky.ws/image/2206/image.jpg>
#!/usr/bin/env python
import wx
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self,
parent,
id=wx.ID_ANY,
pos=wx.DefaultPosition,
size=wx.Size( -1,-1 ),
style=wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL)
fgSizer8 = wx.FlexGridSizer(0, 1, 0, 0)
self.m_notebook2 = wx.Notebook(self,
wx.ID_ANY,
wx.DefaultPosition,
wx.DefaultSize,
0)
self.m_panel8 = wx.Panel(self.m_notebook2,
wx.ID_ANY,
wx.DefaultPosition,
wx.DefaultSize,
wx.TAB_TRAVERSAL)
bSizer20 = wx.BoxSizer(wx.VERTICAL)
self.fig = Figure()
self.axes = self.fig.add_subplot(111)
self.pts = self.axes.plot([1, 2, 3], [4, 5, 7], 'ro-', picker=5)
self.canvas = FigureCanvas(self, -1, self.fig)
bSizer20.Add(self.canvas, 1, wx.ALL|wx.EXPAND, 5)
self.m_panel8.SetSizer(bSizer20)
self.m_panel8.Layout()
bSizer20.Fit(self.m_panel8)
self.m_notebook2.AddPage(self.m_panel8, u"a page", False)
fgSizer8.Add(self.m_notebook2, 1, wx.EXPAND |wx.ALL, 5)
self.SetSizer(fgSizer8)
self.Layout()
fgSizer8.Fit(self)
self.Centre(wx.BOTH)
if __name__ == "__main__":
app = wx.App(0)
frame = MyFrame(None)
frame.Show()
app.MainLoop()
Answer: change
self.canvas = FigureCanvas(self, -1, self.fig)
to
self.canvas = FigureCanvas(self.m_panel8, -1, self.fig)

|
nginx + uwsgi + flask - disabling custom error pages
Question: Is it possible to disable nginx's custom error pages - if I may call them that
- to display my framework's exception pages?
I can't really see my werkzeug debugger tool rendered in html...
**UPDATE**
OK, I got to make a very very simple flask application to work and I'll post
the bits:
**/home/my_user/.virtualenvs/nginx-test/etc/nginx.conf**
worker_processes 1;
events { worker_connections 1024; }
http {
server {
listen 5000;
server_name localhost;
access_log /home/my_user/.virtualenvs/nginx-test/lib/nginx/access.log;
error_log /home/my_user/.virtualenvs/nginx-test/lib/nginx/error.log;
location / {
include uwsgi_params;
uwsgi_pass unix:/tmp/uwsgi.sock;
}
}
}
**/home/my_user/dev/nginx_test/___init_ __.py**
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
raise Exception()
if __name__ == '__main__':
app.run('0.0.0.0', debug=True)
PYTHONPATH environment variable:
$ echo $PYTHONPATH
/home/my_user/dev/
How I run uwsgi:
$ uwsgi -s /tmp/uwsgi.sock --module nginx_test --callable app
How I run nginx:
$ nginx -c ~/.virtualenvs/nginx-test/etc/nginx.conf -p ~/.virtualenvs/nginx-test/lib/nginx/
If I hit the root page:

If I run nginx manually like:
python /home/my_user/dev/nginx_test/___init___.py
I will see instead, and what I want to see:

Of course I made sure it would work when I didn't raise the exception, but
returned 'Hello World' for example on my index() function.
This is referred to custom error pages in .NET. I want to disable this and let
nginx/uwsgi pass the html generated by the debugger directly to the browser
instead of the internal server error thing.
**UPDATE 2**
Now if I change my flask app to enable debugging mode by:
**/home/my_user/dev/nginx_test/___init_ __.py**
from flask import Flask
app = Flask(__name__)
app.config.update(DEBUG=True)
@app.route('/')
def index():
raise Exception()
if __name__ == '__main__':
app.run('0.0.0.0', debug=True)
Then I get 502 error.
But if I instead of raise Exception:
**/home/my_user/dev/nginx_test/___init_ __.py**
from flask import Flask
app = Flask(__name__)
app.config.update(DEBUG=True)
@app.route('/')
def index():
return 'Hello World'
if __name__ == '__main__':
app.run('0.0.0.0', debug=True)
I get 'Hello World' on my browser when I hit the page (http://localhost:5000).
Answer: This "Internal Server Error" page is not from nginx but from Flask. It does so
**when debug mode is off**.
uwsgi is importing your code as a module, not running at as a script.
`__name__ == '__main__'` is False and the if statement is not executed. Try
setting debug mode outside of the if:
app = Flask(__name__)
app.debug = True
However, it is strongly recommended to **never** leave the debug mode on a
server on the public internet, since the user can make the server run any
code. This is a serious security issue.
|
python parse file
Question: I have a file with username and emails, in this format :
pete,[email protected]
I want to only keep the email, so i thought about using a regex like this :
import re,sys
Mailfile = sys.argv[1]
file = open(Mailfile, "r")
for MAIL in file.readlines():
tmp = re.split("\n+", MAIL)
m = re.match( ',(.+)', MAIL)
m.group(0)
But then I don't know how to store the result in a file. I always get the last
email address in the new file.
What would be the best way to store the results in a file ? Thanks!
Answer:
import sys
infile, outfile = sys.argv[1], sys.argv[2]
with open(infile) as inf, open(outfile,"w") as outf:
line_words = (line.split(',') for line in inf)
outf.writelines(words[1].strip() + '\n' for words in line_words if len(words)>1)
|
How can I update the textctrl content in GUI?
Question: I am trying to write my first wxpython GUI program,in my program,I want to get
anothor software window's title,if the title change,clear the old title and
show the new title in GUI,I test in cmd,it can get the title in a loop,but I
don't konw how to set a event in GUI to update the title.
my code:
def getinfos():
tempWindowName=win32gui.GetWindowText (find_window())
while True:
titles=[]
if (tempWindowName==win32gui.GetWindowText (find_window())):
pass
else:
tempWindowName=win32gui.GetWindowText (find_window())
titles.append(tempWindowName)
return title[0]
time.sleep(1000)
and the GUI code:
import controller2
import time
########################################################################
class InfoPanel(wx.Panel):
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
try:
self.titleResults = controller2.getinfos()
except:
self.titleResults = 'no data'
mainSizer = wx.BoxSizer(wx.VERTICAL)
self.titlecontent = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_RICH|wx.TE_LEFT|wx.TE_WORDWRAP|wx.NO_BORDER)
self.titlecontent.SetBackgroundColour('white')
self.settitle()
mainSizer.Add(self.yejicontent, 2.5, wx.ALL|wx.EXPAND, 5)
self.SetSizer(mainSizer)
#----------------------------------------------------------------------
def settitle(self):
self.titlecontent.SetValue("%s"%self.titleResults)
########################################################################
class InfoFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="title",size=(500, 880))
panel = InfoPanel(self)
style= self.GetWindowStyle()
self.SetWindowStyle(style|wx.STAY_ON_TOP)
class MyApp(wx.App):
def OnInit(self):
self.infoFrame=InfoFrame()
self.SetTopWindow(self.infoFrame)
self.infoFrame.Show(True)
return True
#----------------------------------------------------------------------
if __name__ == "__main__":
app = MyApp(False)
app.MainLoop()
Thanks for your time and appreciate for any advise.
Answer: You can send a [custom wx event](http://wiki.wxpython.org/CustomEventClasses)
or setup [pubsub](http://wiki.wxpython.org/WxLibPubSub).
|
python read last three lines from kernel log
Question: I want to read the last three lines from the kernel log `/var/log/messages` in
a loop.
for i in xrange(0,100):
# do_stuff()
file = open('/var/log/messages')
lines = file.readlines()[-3:]
# analyse_stuff()
file.close()
But I have a problem with this code:
[...]
1013477960613797 1013477960959759 1013477961174602
1013477960613797 1013477960959759 1013477961174602
1013477960613797 1013477960959759 1013477961174602
1013477960613797 1013477960959759 1013477961174602
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477973551967 1013477973773506 1013477977678559
1013477986756370 1013477990527612 1013477990834895
1013477986756370 1013477990527612 1013477990834895
1013477986756370 1013477990527612 1013477990834895
1013477986756370 1013477990527612 1013477990834895
1013477986756370 1013477990527612 1013477990834895
1013477986756370 1013477990527612 1013477990834895
1013477986756370 1013477990527612 1013477990834895
1013477986756370 1013477990527612 1013477990834895
[...]
As you can see, values are repeated many times. `do_stuff()` executes a
binary, which issues three log messages. `analyse_stuff()` will analyse the
three lines and does _magic_ I always close the file and reopen it, because I
thought this would resolve the problem, but it doesn't. Any idea what happens?
Answer: I would normally use tail, but if you **really** only want the last 'n' lines,
and don't care too much about following (similar to 'tail -f'), then your
simplest option is something like:
from collections import deque
last3 = deque(open('/path/to/your/file'), 3)
print last3
`deque` will consume line by line, discarding the oldest entries to keep a
constraint of 3 lines. Look at
<http://docs.python.org/library/collections.html#collections.deque> for more
information
|
How to patch Python class using Mock library
Question: I'm having trouble patching a class for my testing. I'm trying to patch
something that belongs to Scrapy - a
[HtmlXpathSelector](http://scrapy.readthedocs.org/en/latest/topics/selectors.html?highlight=HtmlXPath#scrapy.selector.HtmlXPathSelector)
class.
Here is some code:
from scrapy.selector import HtmlXPathSelector
from mock import MagicMock, patch
with patch('scrapy.selector.HtmlXPathSelector') as MockHtml:
instance = MockHtml.return_value
instance.method.return_value = 'foo'
example = HtmlXPathSelector()
print type(example)
assert example is instance
assert example.method == 'foo'
The result is:
<class 'scrapy.selector.lxmlsel.HtmlXPathSelector'>
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
AssertionError
>>>
This example is nigh on the same as the one in the Mock library tutorial. Any
idea why it's not working?
Answer: You should not patch a class already imported in the current test code.
Instead you need to patch the class in the corresponding module (you want to
test). So if `HtmlXPathSelector` is imported in `mymodule`, you will patch as:
with patch('mymodule.HtmlXPathSelector') as MockClass:
...
See [where to patch](http://mock.readthedocs.org/en/latest/patch.html#where-
to-patch) for further details.
**Edit** If you really need this, you can patch a class in the current module
with:
with patch('__main__.Class') as MockClass:
|
Django Help: AttributeError: 'module' object has no attribute 'Charfield'
Question: I have seen several similar posts of other attributes found but not this. New
to Python and Django- I've done the first part of the several tutorials
including Django's "Polls" tutorial and when it gets to the point where I
syncdb for my app I invariably get 'AttributeError: 'module' object has no
attribute CharField.
In models I have copied exactly as the tutorial says:
from django.db import models
class Poll(models.Model):
question = models.Charfield(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
# Create your models here.
'polls' is also added to installed apps and I'm using sqlite3, windows 7,
python 2.7.
Any help very appreciated! (I'm trying very hard to learn!)
Answer: That is `CharField`, with uppercase 'f', and not `Charfield` as in your code.
|
Python: How to differ these two functions with each other
Question:
def a():
""" Need to write something here."""
def test1():
return a()
def test2(x):
return x
I would like to do this in python interpreter:
test1()
test2(a())
So what I need to do is that I write a() to make these two functions (test1(),
test2(x)) return different result.
For example, I want test1 to return number 1 and test2 return other things
except number 1.
Answer:
import inspect
def a():
s = inspect.stack()
if s[1][3] == '<module>':
return "From test2"
else:
return "Not from test2"
|
Objects With No Behavior
Question: I'm thinking about a situation where I have an object "Transaction", that has
quite a few properties to it like account, amount, date, currency, type, etc.
I never plan to mutate these data points, and calculation logic will live in
other classes. My question is, is it poor Python design to instantiate
thousands of objects just to hold data? I find the data far easier to work
with embedded in a class rather than trying to cram it into some combination
of data structures.
Answer: No, this is perfectly fine. In fact, Python has support for it in the standard
`collections` module:
from collections import namedtuple
Transaction = namedtuple("Transaction", ["account", "amount"])
instead of `class Transaction(object):` etc. Note that `namedtuple` is a kind
of "class factory" and you need to pass it the name of the class to be
constructed, as a string. That need not be the name you bind the result to,
but doing so is still a good idea. Named tuple types are analogous to records
in Pascal or structs in C: data holders with named members but no significant
behavior of their own.
Usage:
>>> t = Transaction(account="my private account", amount=+1000)
>>> t
Transaction(account='my private account', amount=1000)
>>> t.amount
1000
>>> t.amount += 1
Traceback (most recent call last):
File "<ipython-input-6-ae60188f2446>", line 1, in <module>
t.amount += 1
AttributeError: can't set attribute
|
Can one partially apply the second argument of a function that takes no keyword arguments?
Question: Take for example the python built in `pow()` function.
xs = [1,2,3,4,5,6,7,8]
from functools import partial
list(map(partial(pow,2),xs))
>>> [2, 4, 8, 16, 32, 128, 256]
but how would I raise the xs to the power of 2?
to get `[1, 4, 9, 16, 25, 49, 64]`
list(map(partial(pow,y=2),xs))
TypeError: pow() takes no keyword arguments
I know list comprehensions would be easier.
Answer: # No
According to [the
documentation](http://docs.python.org/library/functools.html#functools.partial.args),
[`partial`](http://docs.python.org/library/functools.html#functools.partial)
_cannot_ do this (emphasis my own):
> **partial.args**
>
>> The _leftmost_ positional arguments that will be prepended to the
positional arguments
* * *
You could always just "fix" `pow` to have keyword args:
_pow = pow
pow = lambda x, y: _pow(x, y)
|
ImportError: django.utils not found in Google app engine
Question: I get this error when I use simplejson from django.utils in google app engine
project:
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 187, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/base/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 225, in _LoadHandler
handler = __import__(path[0])
File "/base/data/home/apps/s~testapp/1.359839747994604729/notify.py", line 8, in <module>
from handlers.xmpp_handler import XMPPHandler
File "/base/data/home/apps/s~testapp/1.359839747994604729/handlers/xmpp_handler.py", line 12, in <module>
import commands
File "/base/data/home/apps/s~testapp/1.359839747994604729/handlers/commands.py", line 4, in <module>
from django.utils import simplejson
ImportError: No module named django.utils
**Snippet:**
import datetime
from google.appengine.api import users
from google.appengine.ext import db
from django.utils import simplejson
class jsonEncoder(simplejson.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, db.Model):
return dict((p, getattr(obj, p))
for p in obj.properties())
elif isinstance(obj, users.User):
return obj.email()
else:
return simplejson.JSONEncoder.default(self, obj)
Answer: You need to specify that you want to use django in your `app.yaml`:
libraries:
- name: django
version: "1.2"
See the [GAE
docs](https://developers.google.com/appengine/docs/python/tools/libraries27)
for the supported django versions.
On Python 2.7 runtime, you should be using python's [native json
library](https://developers.google.com/appengine/docs/python/python27/newin27#JSON_Version)
instead of simplejson though.
|
Embedding HTML in an rst2pdf list-table
Question: I'm using [`rst2pdf`](https://code.google.com/p/rst2pdf/) 0.92 on linux, and I
am trying to embed html inside a `list-table` directive, as shown in [Dimitri
Christodoulou's blog](http://dimitri-christodoulou.blogspot.com/2012/01/how-
to-embed-html-in-restructuredtext.html). Robert Alsina mentioned that he had
integrated this feature into [`rst2pdf`](https://code.google.com/p/rst2pdf/)
0.90.
I'm trying to build an invoice with multiple text lines per cell, the simplest
way to control where the line-breaks are seems to be using a `<br>` tag. This
was my `test.rst` file:
Invoice for Services Rendered
=============================
.. list-table::
:widths: 50 50
:header-rows: 0
* - .. raw:: html
<p>My Name Here<br>My address here<br>City, State, Zip<br>Ph: 214-555-1212<br></p>
- **INVOICE**
* - This is a test
- .. raw:: html
<p>Invoice #20120622001<br>Date: 25 June 2012<br></p>
This compiles into a pdf with no problems using `rst2pdf -o test.pdf
test.rst`; however, I see no text where the embedded HTML should be:

I am using:
* Python 2.6.6 in a virtual-env
* docutils 0.9.1
* rst2pdf 0.92
* xhtml2pdf 0.0.4
* Debian Squeeze (Debian Linux 6.0)
How can I get rst2pdf to embed the HTML shown above in a `list-table`
directive?
**EDIT**
This has been filed as [rst2pdf issue
455](https://code.google.com/p/rst2pdf/issues/detail?id=455)
Answer: Fixed it! Sorry it took so long. Latest pisa/xhtml2pdf has completely
different imports :-P
|
Getting either “DLL load failed” or python-exception in demandimport, when using mercurial on trac, this time on Windows 2008 R2, 64 bit
Question: [This question](http://stackoverflow.com/questions/5158523/dll-load-failed-
when-using-mercurial-on-trac), asked in 2011, and on a different operating
system (XP instead of WSRV2008R2) is someone having a very similar sounding
problem, but the accepted solution is to go back to a now-ancient mercurial
version 1.8. I don't think that is a good answer in 2012.
I'd like to know if there is a way to get Apache 2.2 and Trac 0.12, and
Mercurial 2.2.2 working on windows, and all running under Apache. The problems
I'm having seem to be Python programming-related, and related to Python's use,
and Mercurial's use, of various zipped and unzipped module formats.
1. It seems that to get this all working, may require you to build mercurial from sources, on windows, or to use Mercurial's "pure python" version. I'd like to know what about Python, or what about Mercurial, leads to these problems which might need me to run "pure python". Perhaps one accepted answer is that Mercurial is a quirky beast, and under mod_wsgi, one should use the pure python version of mercurial only. The underlying Python and mercurial implementation reasons why, would be great to know, as well.
2. It seems that Mercurial's shady looking demand-loading feature is implicated, which is a source-code level feature in the mercurial sources, which is confusing me, and I'm hoping someone can explain it.
3. The use in mercurial installed versions of a "library.zip" seems also to be creating an at-runtime situation where mercurial will import when I run python.exe from the command line (command prompt in Windows, with environment and path set as it would be set, if I was inside apache), but where Mercurial's primary python units will not import, from inside apache, with mod_wsgi.
Here is the test script which I use which works fine, from a command prompt,
and shows that this python 2.6 instance has a workable set of Mercurial stuff
in `site-packages`:
from mercurial import ui, hg
path = 'D:/MyHgRepo'
repo = hg.repository(ui.ui(), path)
print path,"Repository info:"
print repr(repo), "object len: ",len(repo)
However, when running from within `Trac` which is hosted inside `Apache`,
attempts to load the mercurial module fails, first with a strange
`demandimport` failure, and when that is fixed, silently with no reason given
in Trac (I'll have to debug in trac sourcecode to solve this last bit,
perhaps). `Demandimport.py` is a module inside the site-packages/Mercurial
folder. This exception traceback comes from the trac.log:
In both cases, it says `Look in the Trac log for more information.` \-- the
error message here seems to be the problem:
Traceback (most recent call last):
File "build\bdist.win32\egg\trac\loader.py", line 68, in _load_eggs
entry.load(require=True)
File "build/bdist.linux-i686/egg/pkg_resources.py", line 1954, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "C:\Program Files\BitNami Trac Stack\python\lib\site-packages\mercurial\demandimport.py", line 114, in _demandimport
mod = _origimport(name, globals, locals)
File "build\bdist.win32\egg\trac\mimeview\rst.py", line 155, in <module>
File "C:\Program Files\BitNami Trac Stack\python\lib\site-packages\mercurial\demandimport.py", line 87, in __getattribute__
return getattr(self._module, attr)
AttributeError: 'module' object has no attribute 'directives'
The above exception can be fixed, oddly enough by "commenting out" that whole
demand import unit. Here's my null "pass" implementation:
# demandimport.py - disabled by warren.
'''
demandimport - disabled in code by warren.
'''
def enable():
"does nothing"
pass
def disable():
"does nothing"
pass
The above hack clears up the above visible exception, leaving trac.log free of
errors, and yet, still there is no Hg plugin visible inside Trac.
From googling-wildly around the internet, I have found that:
1. Mercurial installers for Windows that install into the \Python2.6 system folder, ship a "Library.zip" that contains not only .pyc but also .pyd files. This appears to work for some people, and fail for some people, when using `mod_wsgi` under apache, instead of while using Python interactively, or via standalone http `hg serve` operation. I have seen the author of the Trac Mercurial Plugin suggest unpacking library.zip. This is my first question; What is going on with Library.zip and is it my problem.
2. Lots of people have a hard time getting Python 2.6 or 2.7, mod_wsgi, Trac, and Mercurial to all run from inside Apache, on Windows. The underlying problems they have appear to be far beyond a software-user and installer's ability to solve, and require some arcane, or at least rudimentary python programming knowledge to solve.
That is why I'm asking this question here, on a programming answers site. I
want to understand Python, and its library and module and site-packages
architecture, as used by the popular open source packages Mercurial, Trac, and
others, so that I can understand, diagnose and debug the broken Python
codebase of Mercurial 2.2, which does not function on my system, when used in
the mod_wsgi/apache2.2 environment.
I'm using Python 2.6, and Trac 0.12, all of which were installed by the
Bitnami Trac Stack installer. I'm using Mercurial 2.2 installed via the
mercurial-2.2-for-x86-for-Python2.6 installer from the mercurial website.
Answer: This happens because the version of Mercurial installed with binaries
including some CPython extensions, that could not be imported into the version
of Python that is being used inside the web server WSGI or CGI or other
Python-in-apache technique.
Solution:
A. Find and install the correct version of mercurial binaries (including the
library.zip and CPython binary extensions used by Mercurial)
B. Go for a pure 100%-python (no CPython binary extensions) version of
Mercurial, such as hackable mercurial:
<http://mercurial.selenic.com/wiki/HackableMercurial>
|
'int' object has no attribute '__getitem__'
Question:
import math
import os
class collection:
col = [[0 for col in range(5)] for row in range(6)]
dist = [[0 for col in range(6)] for row in range(6)]
filename = ""
result = ""
def __init__(self,arg1):
self.filename = arg1
def coll(self):
for i in range(6):
try:
if(i==0):
f = open(self.filename,'r')
elif(i==1):
f = open("chap1.txt",'r')
elif(i==2):
f = open("chap2.txt",'r')
elif(i==3):
f = open("chap3.txt",'r')
elif(i==4):
f = open("chap4.txt",'r')
elif(i==5):
f = open("chap5.txt",'r')
for j in range(5):
self.result = f.readline()
self.col[i][j] = self.result
finally:
print "file handling error"
def distance(self):
for i in range[6]:
for j in range[6]:
dis = 0
for k in range[5]:
dis += math.fabs((self.col[i][k]-self.col[j][k])*(j-i))
self.dist[i][j] = dis
self.dist[i][i] = sys.maxdouble
return self.dist
class profile:
dist = [[0 for col in range(6)]for row in range(6)]
filename = ""
pque = [[0 for col in range(6)]for row in range(6)]
d = [[0 for col in range(6)]for row in range(6)]
par = [[0 for col in range(6)]for row in range(6)]
st = 0
def __init__(self,arg1):
self.filename = arg1
def begin(self):
ob = collection(self.filename)
ob.coll()
dist = ob.distance()
def sssp(self):
for i in range(6):
pque[i] = sys.maxdouble
d[i] = sys.maxdouble
d[0] = 0
pque[0] = 0
while isempty()==0:
u = extract_min()
for i in range(6):
if d[i]>d[u]+dist[u][i]:
d[i] = d[u]+dist[u][i]
pque_deckey(i,d[i])
par[i]=u
if u!=0:
print u
print "\n"
for i in range(6):
print par[i]
def extract_min():
ret = 0
shift = 0
minimum = pque[0]
for i in range(6):
if pque[i]<minimum:
minimum = pque[i]
ret = i
pque[ret] = sys.maxdouble
return ret
def isempty(self):
count = 0
for i in range(6):
if pque[i] == sys.maxdouble:
count=count+1
if count==6:
return 1
else :
return 0
def pque_deckey(self,im,di):
pque[im]=di
class main:
filename = raw_input("enter name of student:\n")
filename = filename + ".txt"
if(os.path.exists(filename)==1):
f = file(filename,"r")
else:
f = file(filename,"w+")
att1 = raw_input("att1 score:\n")
att2 = raw_input("att2 score:\n")
att3 = raw_input("att3 score:\n")
att4 = raw_input("att4 score:\n")
att5 = raw_input("att5 score:\n")
f.write(att1)
f.write("\n")
f.write(att2)
f.write("\n")
f.write(att3)
f.write("\n")
f.write(att4)
f.write("\n")
f.write(att5)
f.write("\n")
stud = profile(filename)
stud.begin()
stud.sssp()
it shows a runtime error :
File "C:\Python27\winculum.py", line 33, in coll
self.col[i][j] = self.result
TypeError: 'int' object has no attribute '__getitem__'
I am just a beginner at python, and I am unable to rectify this even after
searching on the net.
Answer: The error:
'int' object has no attribute '__getitem__'
means that you're attempting to apply the index operator `[]` on an int, not a
list. So is `col` not a list, even when it should be? Let's start from that.
Look here:
col = [[0 for col in range(5)] for row in range(6)]
Use a different variable name inside, looks like the list comprehension
overwrites the `col` variable during iteration. (Not during _the_ iteration
when you set `col`, but during the following ones.)
|
Error message for virtualenvwrapper on OS X Lion
Question: I've used homebrew to install python on a new Mac Lion installation, and have
been trying to install virtualenv and virtualenvwrapper with pip, but when I
start a new terminal session, I get this traceback:
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named virtualenvwrapper.hook_loader
virtualenvwrapper.sh: There was a problem running the initialization hooks.
If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenv has been installed for
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is
set properly.
The python and pip used are from homebrew, but it seems to want me to use
Apple's default python. I get the following
~$ which python | xargs ls -l
lrwxr-xr-x 1 beard admin 33 Jun 24 16:11 /usr/local/bin/python -> ../Cellar/python/2.7.3/bin/python
~$ echo $VIRTUALENVWRAPPER_PYTHON
/usr/local/bin/python
~$ which pip | xargs ls -l
-rwxr-xr-x 1 beard admin 301 Jun 24 16:18 /usr/local/share/python/pip
~$ which virtualenvwrapper.sh | xargs ls -l
-rwxr-xr-x 1 beard admin 32227 Jun 24 16:19 /usr/local/share/python/virtualenvwrapper.sh
However, it seems to think that I've installed pip (and virtualenv) with the
system python in `/usr/bin/python`
**Edit:** In my bashrc--
export WORKON_HOME="$HOME/py-env"
export VIRTUALENVWRAPPER_LOG_DIR="$HOME/py-env"
export VIRTUALENVWRAPPER_HOOK_DIR="$HOME/py-env"
source /usr/local/share/python/virtualenvwrapper.sh
export VIRTUALENVWRAPPER_PYTHON="/usr/local/bin/python"
Answer: Since you have your own version of python, have you tried overriding
VIRTUALENVWRAPPER_PYTHON? (It looks like you want `export
VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python`) [The virtualenvwrapper
docs](http://www.doughellmann.com/docs/virtualenvwrapper/install.html#python-
interpreter-virtualenv-and-path) suggest setting that envvar to the desired
python before sourcing virtualenvwrapper.sh. Their example has:
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
source /usr/local/bin/virtualenvwrapper.sh
|
Getting RabbitMQ and Graphite to connect
Question: I'm trying to connect RabbitMQ to Graphite(0.9.9) using
<https://github.com/somic/graphite-rabbitmq> However, I'm not entirely sure
which directory in Graphite the graphite-rabbitmq files should be placed.
When I run `carbon-agent-rabbitm1.py` I get
Failed to import the graphite package. Please verify that this package
was properly installed and that your PYTHONPATH environment variable
includes the directory in which it is installed.
For example, you may need to run the following command:
export PYTHONPATH="/home/myusername/lib/python/:$PYTHONPATH"
Help would be very much appreciated
Answer: The convention with python modules, you can just put the downloaded files in
an arbitrary temp directory, cd into that directory, and run:
python setup.py install
The standard `distutils` package will do the work of making sure everything
gets to the right place.
You may also want to download [pip](http://pypi.python.org/pypi/pip/) which
will manage the process of downloading and installing these packages for you,
in which case you can then just type:
pip install graphite-web
But aside from all that, you really can put the files anywhere, so long as you
add the directory to an environment variable called PYTHONPATH, just like the
error message you quoted says.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.