text
stringlengths 226
34.5k
|
---|
How to change primary text in gtk messagedialog in python?
Question: I'm creating program in python with gtk as gui using glade. In that program, I
have several message dialog. It's simple if I just make many message dialog
for every case I have. But, is it possible to just make one message dialog and
use it for different case with different text? It's simple actually. I just
need to change primary text and show it. But, I don't find a way to change
primary text [here](http://python-
gtk-3-tutorial.readthedocs.org/en/latest/dialogs.html) and
[here](http://www.pygtk.org/docs/pygtk/class-gtkmessagedialog.html).
Below is a sample code:
from gi.repository import Gtk
def clicked1(widget):
response = dialog1.run()
if response == Gtk.ResponseType.OK:
print 'ok'
else:
print 'cancel'
dialog1.destroy()
def clicked2(widget):
response = dialog2.run()
if response == Gtk.ResponseType.OK:
print 'ok'
else:
print 'cancel'
dialog2.destroy()
def clicked3(widget):
response = dialog3.run()
if response == Gtk.ResponseType.OK:
print 'ok'
else:
print 'cancel'
dialog3.destroy()
builder = Gtk.Builder()
builder.add_from_file('gui.glade')
dialog1 = builder.get_object('dialog1')
dialog2 = builder.get_object('dialog2')
dialog3 = builder.get_object('dialog3')
builder.get_object('button1').connect('clicked', clicked1)
builder.get_object('button2').connect('clicked', clicked2)
builder.get_object('button3').connect('clicked', clicked3)
builder.get_object('window1').show_all()
Gtk.main()
I want to change it to be something like this
from gi.repository import Gtk
def clicked1(widget):
**dialog.set_text(1)**
response = dialog.run()
if response == Gtk.ResponseType.OK:
print 'ok'
else:
print 'cancel'
dialog.destroy()
def clicked2(widget):
**dialog.set_text(2)**
response = dialog.run()
if response == Gtk.ResponseType.OK:
print 'ok'
else:
print 'cancel'
dialog.destroy()
def clicked3(widget):
**dialog.set_text(3)**
response = dialog.run()
if response == Gtk.ResponseType.OK:
print 'ok'
else:
print 'cancel'
dialog.destroy()
builder = Gtk.Builder()
builder.add_from_file('gui.glade')
**dialog = builder.get_object('dialog')**
builder.get_object('button1').connect('clicked', clicked1)
builder.get_object('button2').connect('clicked', clicked2)
builder.get_object('button3').connect('clicked', clicked3)
builder.get_object('window1').show_all()
Gtk.main()
Answer: Alternatively, we can just write some wrapping functions of
gtk_message_dialog, and here is a simple example:
def info(text, text2=None):
dialog = Gtk.MessageDialog(None,
Gtk.DialogFlags.MODAL,
Gtk.MessageType.INFO,
Gtk.ButtonsType.OK,
text)
if text2 != None:
dialog.format_secondary_text(text2)
response = dialog.run()
dialog.destroy()
The problems is that if no parent window is spesified in the message dialog,
it will show in the center of screen, rather than center of program. To solve
this problem, we can put info() function in the class and set its parent
window parameter.
Other types of message like warning, question and error can do the same way.
And a small demo:
#!/usr/bin/env python3
from gi.repository import Gtk
def info(text, text2=None):
dialog = Gtk.MessageDialog(None,
Gtk.DialogFlags.MODAL,
Gtk.MessageType.INFO,
Gtk.ButtonsType.OK,
text)
if text2 != None:
dialog.format_secondary_text(text2)
response = dialog.run()
dialog.destroy()
def error(text, text2=None):
'''
TODO
'''
pass
def main():
win = Gtk.Window()
win.connect('delete-event', Gtk.main_quit)
win.show_all()
info('hello')
info('hello, primary text', 'hello secondary text')
Gtk.main()
if __name__ == '__main__':
main()
Widget structure of a message dialog is like this: 
|
What is wrong with my code? I am new at Python 3.3
Question:
def start():
import os
os.system("cls")
print "*A Wise man once said “Be the change that you wish to see in the world.” This is the idea you have decided to live by and strive for in your quest for making a better world. You are Noah Vis, CEO of the tech giant GAIA and currently the richest man in the world, surpassing the likes of Bill Gates and Waren Buffet by a great margin. Born into a life of modest privilege in the state of Washington, you rapidly asserted your engineering and scientific abilities to build a global technological empire. Your first breakthrough was the F.E.H.C (Fusion Energy Hydrogen Collider). Producing sustainable energy by mashing the two hydrogen isotopes, deuterium and tritium, together at such high energies that they combiine into one atom. After the fusion, you produce a helium and a free neutron. The critical part being that helium+neutron has less mass than deuterium+tritium, and the mass is converted into purge energy. That energy is then captured as heat and used to run a traditional steam-driven turbine. This invention, emerging just as the world's oil supplies reach a critical low, becomes essential. As the middle east decended into conflict, the rest of the world rebuilded using your patents and products. For the most part, people are grateful. Still focused on making the world better, your focus turns. Do you...*"
print "*[L]ook to the poverty of Africa as the greatest remaining blight on Earth, and resolve to try to bring it to an end, or [T]HIS HAS YET TO BE WRITTEN*"
o1 = (input('>>'))
if o1 =="L":
print "*THIS IS NOT WRITTEN YET*"
if o1 =="T"
print "*THIS IS NOT WRITTEN YET*"
os.system("pause >Nul")
def menu ():
print "Menu\n"
print "(1)Start"
print "(2)Exit\n\n"
choice = (input('>>'))
if choice=="1":
start()
if choice=="2":
quit()
menu()
**This just results in a syntax-error and i can't figure out why. Your help is
much appreciated :-)**
Answer: [Since Python 3](http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-
function), `print` is no longer a statement, but a function. Thus, to use it,
you would do `print()` instead of `print`.
Python 2.7:
print "Hello world!"
Python 3:
print("Hello world!")
You can read more about the `print()` function [at the
docs](http://docs.python.org/2/library/functions.html#print), which also
mentions some parameters you can include, and also how you can use it in
python 2.x (`from __future__ import print_function`)
* * *
Also, you're missing a colon after `if o1 =="T"`. May just be a simple typo
:).
|
Python Blowfish Encryption
Question: I am struggling due to my incomplete knowledge of Java to convert this
encryption code to Python code. The two should have the exact same results.
Help would be greatly appreciated.
_Java Function_
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String s = "testings";
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
Key key = new SecretKeySpec("6#26FRL$ZWD".getBytes(), "Blowfish");
cipher.init(1, key);
byte[] enc_bytes = cipher.doFinal(s.getBytes());
System.out.println(enc_bytes);
}
}
_Python Equivalent_
def PKCS5Padding(string):
byteNum = len(string)
packingLength = 8 - byteNum % 8
if packingLength == 8:
return string
else:
appendage = chr(packingLength) * packingLength
return string + appendage
def PandoraEncrypt(string):
from Crypto.Cipher import Blowfish
key = b'6#26FRL$ZWD'
c1 = Blowfish.new(key, Blowfish.MODE_ECB)
packedString = PKCS5Padding(string)
return c1.encrypt(packedString)
**Results**
Java Function: "??¾ô"
Python Function: "Ë4A-¾`*ã"
Answer: I get the same output for both python and Java using your example.
Java:
import java.math.BigInteger;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class Blowfish1 {
public static void main(String[] args) throws Exception {
String s = "testings";
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
Key key = new SecretKeySpec("6#26FRL$ZWD".getBytes(), "Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] enc_bytes = cipher.doFinal(s.getBytes());
System.out.printf("%x%n", new BigInteger(1, enc_bytes));
}
}
Python:
from Crypto.Cipher import Blowfish
import binascii
# See @falsetru answer for the following method
#
def PKCS5Padding(string):
byteNum = len(string)
packingLength = 8 - byteNum % 8
appendage = chr(packingLength) * packingLength
return string + appendage
def PandoraEncrypt(string):
key = b'6#26FRL$ZWD'
c1 = Blowfish.new(key, Blowfish.MODE_ECB)
packedString = PKCS5Padding(string)
return c1.encrypt(packedString)
if __name__ == '__main__':
s = 'testings'
c = PandoraEncrypt(s)
print(binascii.hexlify(c))
In both cases the output is `223950ff19fbea872fce0ee543692ba7`
|
Python Celery could start with a threading inprocess ?
Question: I want make a testcase with my celery codes. But usually celery need start
with a new process like `$ celery -A CELERY_MODULE worker`, It's means I can't
run my testcase code directly ?
I'm configurate the Celery with memory store to void the extra I/O in the
testcase. That's config can't sample share the task queue in different
process.
Answer: Here is my naive implements. The celery entry from
`celery.bin.celeryd.WorkCommand`, it's parse the args and execute works.
Use the `solo` to void the MultiProcess use in the case. Of course you need
install that's lib first.
You could use this before your celery testcase start.
#!/usr/bin/env python
#vim: encoding=utf-8
import time
import unittest
from threading import Thread
from celery import Celery, states
from celery.bin.celeryd import WorkerCommand
class CELERY_CONFIG(object):
BROKER_URL = "memory://"
CELERY_CACHE_BACKEND = "memory"
CELERY_RESULT_BACKEND = "cache"
CELERYD_POOL = "solo"
class CeleryTestCase(unittest.TestCase):
def test_inprocess(self):
app = Celery(__name__)
app.config_from_object(CELERY_CONFIG)
@app.task
def dumpy_task(dct):
return 321
worker = WorkerCommand(app)
#worker.execute_from_commandline(["-P solo"])
t = Thread(target=worker.execute_from_commandline, args=(["-c 1"],))
t.daemon = True
t.start()
ar = dumpy_task.apply_async(({"a": 123},))
while ar.status != states.SUCCESS:
time.sleep(.01)
self.assertEqual(states.SUCCESS, ar.status)
self.assertEqual(ar.result, 321)
t.join(0)
|
Print code from web page with python and urllib
Question: I'm trying to use python and urllib to look at the code of a certain web page.
I've tried and succeeded this at other webpages using the code:
from urllib import *
url =
code = urlopen(url).read()
print code
But it returns nothing at all. My guess is it's because the page has a lot of
javascripts? What to do?
Answer: ### Dynamic client side generated pages (JavaScript)
You can not use urllib alone to see code that been rendered dynamically client
side (JavaScript). The reason is that urllib only fetches the response from
the server which is headers and the body (the actual code). Because of that I
will not execute the client side code.
You can however use something like
[selenium](https://pypi.python.org/pypi/selenium) to remote control a web
browser (Chrome or Firefox). That will make it possible for you to scrap the
page even though it renders with javascript.
Here is a sample of scraping with selenium: [Using python with selenium to
scrape dynamic web pages](http://stackoverflow.com/questions/8650999/using-
python-with-selenium-to-scrape-dynamic-web-pages)
### But that is not your problem here
The problem with this site however seems to be that they don't want to be
scraped. They block clients with certain http user-agent headers.
You can however get the code anyway if you fake the http headers. Use urllib2
instead of urllib like this:
import urllib2
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox') # Add fake client
response = urllib2.urlopen(req)
print response.read()
But, they clearly don't want you to scrape their site, so you should consider
if this is a good idea.
|
Extract unique rows from a matrix in numpy with the frequency of each row that was created
Question: A follow up question on:
[How can i use the unique(a, 'rows') from MATLab at
python?](http://stackoverflow.com/questions/6776821/how-can-i-use-the-uniquea-
rows-from-matlab-at-python)
The answer there explains how to get the unique rows. Yet matlab also returns
the frequency of each row that was created. Any elegant way to make it with
python?
Thanks!
Answer: You can count the number of each unique row using fancy indexing and
evaluating a condition like:
from numpy import unique, array, all
def myunique(input):
u = array([array(x) for x in set(tuple(x) for x in input)])
return u, array([len(input[all(input==x, axis=1)]) for x in u],dtype=int)
example:
a = array([list('1234'),
list('1234'),
list('1222'),
list('1222'),
list('1234')],dtype=str)
print myunique(a)
#(array([['1', '2', '2', '2'],
# ['1', '2', '3', '4']],
# dtype='|S1'), array([2, 3]))
|
Pythonic enumeration of while loop
Question: Python has an elegant way of automatically generating a counter variable in
`for` loops: the `enumerate` function. This saves the need of initializing and
incrementing a counter variable. Counter variables are also ugly because they
are often useless once the loop is finished, yet their scope is not the scope
of the loop, so they occupy the namespace without need (although I am not sure
whether `enumerate` actually solves this).
My question is, whether there is a similar pythonic solution for `while`
loops. `enumerate` won't work for `while` loops since `enumerate` returns an
iterator. Ideally, the solution should be "pythonic" and not require function
definitions.
For example:
x=0
c=0
while x<10:
x=int(raw_input())
print x,c
c+=1
In this case we would want to avoid initializing and incrementing `c`.
**Clarification:**
This can be done with an endless `for` loop with manual termination as some
have suggested, but I am looking for a solution that makes the code clearer,
and I don't think that solution makes the code clearer in this case.
Answer: Again with the
[`itertools`](http://docs.python.org/2/library/itertools.html)...
import itertools
for c, x in enumerate(
itertools.takewhile(lambda v: v < 10,
(int(raw_input()) for z in itertools.count())
)
):
print c, x
|
Merging two .csv files python-pandas
Question: I have two .csv files with the same initial column-header:
NAME RA DEC Mean_I1 Mean_I2 alpha_K24 class alpha_K8 class.1 Av avgAv
Mon-000101 100.27242 9.608597 11.082 10.034 0.39 I 0.39 I 31.1 31.1
Mon-000171 100.29230 9.522860 14.834 14.385 0.45 I 0.45 I 33.7 33.7
and
NAME Sdev_I1 Sdev_I2
Mon-000002, 0.023, 0.028000001,
Mon-000003, 0.016000001, 0.016000001,
I want to merge the two together so that the 'NAME' columns match up,
basically just add the two Sdev_I1/Sdev_I2 to the end of the first sample.
I've tried...
import pandas as pd
df1 = pd.read_csv('h7.csv',sep=r'\s+')
df2 = pd.read_csv('NEW.csv',sep=r'\s+')
df = pd.merge(df1,df2)
df.to_csv('Newh7.csv',index=False)
but it's printing the 'NAME' twice and everything seems to be out of order and
with a lot of added zeroes as well. I thought I had solved this one awhile
back, but I've totally lost it. Help would be appreciated. Thanks.
Here's the output file:
NAME,RA,DEC,Mean_I1,Mean_I2,alpha_K24,class,alpha_K8,class.1,Av,avgAv,Sdev_I1,Sdev_I2
Answer: Seems you didn't strip the comma symbol in the second csv, you might try to
use converters to convert them:
In [81]: converters = {
'NAME': lambda x:x[:-1],
'Sdev_I1': lambda x: float(x[:-1]),
'Sdev_I2': lambda x: float(x[:-1])
}
In [82]: pd.read_csv('NEW.csv',sep=r'\s+', converters=converters)
Out[82]:
NAME Sdev_I1 Sdev_I2
0 Mon-000002 0.023 0.028
1 Mon-000003 0.016 0.016
|
ruby equivalent of destructor
Question: I'm using [`RubyPython`](http://rubypython.rubyforge.org) to import a Python
module. I am doing `RubyPython.start` in the constructor (`initialize`), and I
suppose I should symmetrically do `RubyPython.stop` in the destructor, but
unfortunately it seems that there is no destructor in Ruby:
class QDSHiveHelper
def initialize
RubyPython.start
qds = RubyPython.import('blah')
...
end
def do_something
qds.some_function
...
end
def finalize
RubyPython.stop
end
end
Could someone please explain how to accomplish this?
`ObjectSpace.define_finalize` seems to be discouraged and has some gotchas
(can't use closure etc). I could also just leave `RubyPython` dangling and not
call `stop` on it, but I don't know what could be the consequences. What's the
best way out?
Answer: There is a hook called [ObjectSpace.define_finalizer](http://ruby-
doc.org/core-2.0/ObjectSpace.html#method-c-define_finalizer) that is called
when an object is destroyed.
|
decorator to replace repetitive object orientated code?
Question: I'm developing a GUI with Qt/PySide with lots of separate classes handling
various widgets. Each widget manages signals between buttons and other user
inputs. I found myself having to reuse code to block widget signals at the
start of method functions and then freeing up the signal at the end. I decided
to try and write a general decorator to do this for me.
I've searched through SO and tried to implement this the best I could with
very little experience using decorators and so I'm not satisfied by my
solution.
**My question is, what is the best way to write a general decorator that can
access and run methods within that class which follow a clear format? Is my
method in anyway a good way?**
For clarity, here's what my code looks like with the repetitive code (I've
removed some for brevity):
class WidgetController(...):
def __init__(...):
self.widget.myWidget.currentIndexChanged.connect(reactToChange)
def reactToChange(...):
self.widget.myWidget.blockSignals(True) # Repetetive line...
...
self.widget.myWidget.blockSignals(False)
def anotherFunction(...):
self.widget.anotherWidget.blockSignals(True)
...
self.widget.anotherWidget.blockSignals(False)
I would like something like the following:
class WidgetController(...):
@blockSignals(myWidget)
def reactToChange(...):
...
@blockSignals(anotherWidget, alsoBlockThisWidget)
def anotherFunction(...):
...
I have developed a decorator (with help from
[here](http://www.artima.com/weblogs/viewpost.jsp?thread=240845),
[here](http://stackoverflow.com/questions/4484872/in-python-why-doesnt-exec-
work-in-a-function-with-a-subfunction) and
[here](http://stackoverflow.com/questions/7590682/access-self-from-decorator))
but I hesitate to show it as it feels horribly clunky. It uses `self` where I
don't understand it as well as `exec` in nested functions and needs widget
names to be passed as strings, but it does seem to work. Here it is:
class BlockSignals(object):
def __init__(self, *toBeBlocked):
self.toBeBlocked = toBeBlocked
def __call__(self, f):
toBeBlocked = self.toBeBlocked
def wrapped_f(self, *args):
for b in toBeBlocked:
exec 'self.widget.' + b + '.blockSignals(False)' in locals()
f(self, *args)
for b in toBeBlocked:
exec 'self.widget.' + b + '.blockSignals(False)' in locals()
return wrapped_f
Usage:
class WidgetController(...):
@BlockSignals("myWidget")
def reactToChange(...):
...
@BlockSignals("anotherWidget", "alsoBlockThisWidget")
def anotherFunction(...):
As you can see, it's not pretty. I'd love to be able to get rid of the string
parsing, get rid of the `exec`s, sort out the confusing `self`s and be able to
implement it by passing it the actual widget object
`@BlockSignals(self.widget.myWidget)`. Unfortunately I've reached the limit of
my ability, is anyone able to help?
Answer: You are looking for
[getattr](http://docs.python.org/2/library/functions.html#getattr):
import functools
def blockSignals(*widgetnames):
def decorator(func):
@functool.wraps(func)
def method(self, *args, **kwargs):
widgets = [getattr(self.widget, name) for name in widgetnames]
for widget in widgets:
widget.blockSignals(True)
result = func(self, *args, **kwargs)
for widget in widgets:
widget.blockSignals(False)
return result
return method
return decorator
class WidgetController(...):
def __init__(...):
self.widget.myWidget.currentIndexChanged.connect(reactToChange)
@blockSignals('myWidget')
def reactToChange(...):
...
@blockSignals('anotherWidget', 'alsoBlockThisWidget')
def anotherFunction(...):
...
You have to pass the _name_ of the widget, not the widget itself, because the
methods are defined at the time the _class_ is defined, not when the
_instance_ is instantiated. The instance `self` and the actual widgets in
`self.widget` do not exist at class-definition time.
The
[functools.wraps](http://docs.python.org/2/library/functools.html#functools.wraps)
decorator copies the name of the original function and its docstring to the
decorated function.
|
How to convert Unicode dict to dict
Question: I am trying to convert :
datalist = [u"{gallery: 'gal1', smallimage: 'http://www.styleever.com/media/catalog/product/cache/1/small_image/445x370/17f82f742ffe127f42dca9de82fb58b1/2/_/2_12.jpg',largeimage: 'http://www.styleever.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/2/_/2_12.jpg'}",
u"{gallery: 'gal1', smallimage: 'http://www.styleever.com/media/catalog/product/cache/1/small_image/445x370/17f82f742ffe127f42dca9de82fb58b1/3/_/3_13.jpg',largeimage: 'http://www.styleever.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/3/_/3_13.jpg'}",
u"{gallery: 'gal1', smallimage: 'http://www.styleever.com/media/catalog/product/cache/1/small_image/445x370/17f82f742ffe127f42dca9de82fb58b1/5/_/5_3_1.jpg',largeimage: 'http://www.styleever.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/5/_/5_3_1.jpg'}",
u"{gallery: 'gal1', smallimage: 'http://www.styleever.com/media/catalog/product/cache/1/small_image/445x370/17f82f742ffe127f42dca9de82fb58b1/1/_/1_22.jpg',largeimage: 'http://www.styleever.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/1/_/1_22.jpg'}",
u"{gallery: 'gal1', smallimage: 'http://www.styleever.com/media/catalog/product/cache/1/small_image/445x370/17f82f742ffe127f42dca9de82fb58b1/4/_/4_7_1.jpg',largeimage: 'http://www.styleever.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/4/_/4_7_1.jpg'}"]
To list containing python dict. If i try to extract value using keyword i got
this error:
for i in datalist:
print i['smallimage']
....:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-686ea4feba66> in <module>()
1 for i in datalist:
----> 2 print i['smallimage']
3
TypeError: string indices must be integers
How do i convert list containing Unicode Dict to Dict..
Answer: You could use the [demjson](http://deron.meranda.us/python/demjson/) module
which has a non-strict mode that handles the data you have:
import demjson
for data in datalist:
dct = demjson.decode(data)
print dct['gallery'] # etc...
|
Python operators pymysql
Question: I'm having some bad time with pymysql and python operators. I don't know much
about python operator though.
I want to insert into the database some values. The code:
import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/Applications/MAMP/tmp/mysql/mysql.sock', user='root', passwd='root', db='db2', charset='utf8')
cur = conn.cursor()
v = (123 , 'foobarfoobar', 'foo', 1241, 3, 132 )
cur.execute("INSERT INTO celebs(num_id, Text, Handle, Followers, RT, Timestamp) VALUES (?,?,?,?,?,?)", v)
For the record mySQL structure is `INT (PRI), INT, TEXT, VARCHAR, INT, INT,
VARCHAR`.
I run this and I get `TypeError: not all arguments converted during string
formatting`
Any details how to solve it and possibly some explanation how operator work in
python. In php is easier I think: `$a = 22; echo "$a days";`
Update:
I'm using directly the Insert into and it still doesn't insert the data:
cur.execute("INSERT INTO celebs (num_id, Text, Handle, Followers, RT, Timestamp) VALUES (123 , 'foobarfoobar', 'foo', 1241, 3, 132 );" )
Answer: According to the [source
code](https://github.com/petehunt/PyMySQL/blob/master/pymysql/__init__.py#L49),
the [`paramstyle`](http://www.python.org/dev/peps/pep-0249/#paramstyle) is
`format`, so you'll need to change...
cur.execute("INSERT INTO ... VALUES (?,?,?,?,?,?)", v)
...to...
cur.execute("INSERT INTO ... VALUES (%s,%s,%s,%s,%s,%s)", v)
If you're using a transactional storage engine such as InnoDB, you'll have to
explicitly commit the transaction by calling `conn.commit()` after doing the
`INSERT` query.
|
python: improve performance and/or method to avoid memory error creating, saving and deleting variable variables
Question: I have been fighting against a function giving me a memory error and thanks to
your support ([Python: how to split and return a list from a function to avoid
memory error](http://stackoverflow.com/questions/17097483/python-how-to-split-
and-return-a-list-from-a-function-to-avoid-memory-error)) I managed to sort
the issue; however, since I am not a pro-programmer I would like to ask for
your opinion on my method and how to improve its performance (if possible).
The function is a generator function returning all cycles from an n-nodes
digraph. However, for a 12 nodes digraph, there are about 115 million cycles
(each defined as a list of nodes, e.g. [0,1,2,0] is a cycle). I need all
cycles available for further processing even after I have extracted some of
their properties when they were first generated, so they need to be stored
somewhere. So, the idea is to cut the result array every 10 million cycles to
avoid memory error (when an array is too big, python runs out of RAM) and
create a new array to store the following results. In the 12 node digraph, I
would then have 12 result arrays, 11 full ones (containing 10 million cycles
each) and the last containing 5 million cycles.
However, splitting the result array is not enough since the variables stay in
RAM. So, I still need to write each one to the disk and delete it afterwards
to clear the RAM.
As stated in [How do I do variable variables in
Python?](http://stackoverflow.com/questions/1373164/how-do-i-do-variable-
variables-in-python), using 'exec' to create variable variable names is not
very "clean" and dictionary solutions are better. However, in my case, if I
store the results in a single dictionary, it will run out of memory due to the
size of the arrays. Hence, I went for the 'exec' way. I would be grateful if
you could comment on that decision.
Also, to store the arrays I use numpy.savez_compressed which gives me a 43 Mb
file for each 10million cycles array. If it is not compressed it creates a 500
Mb file. However, using the compressed version slows the writing process. Any
idea how to speed the writing and/or compressing process?
A simplified version of the code I wrote is as follows:
nbr_result_arrays=0
result_array_0=[]
result_lenght=10000000
tmp=result_array_0 # I use tmp to avoid using exec within the for loop (exec slows down code execution)
for cycle in generator:
tmp.append(cycle)
if len(tmp) == result_lenght:
exec 'np.savez_compressed(\'results_' +str(nbr_result_arrays)+ '\', tmp)'
exec 'del result_array_'+str(nbr_result_arrays)
nbr_result_arrays+=1
exec 'result_array_'+str(nbr_result_arrays)+'=[]'
exec 'tmp=result_array_'+str(nbr_result_arrays)
Thanks for reading,
Aleix
Answer: How about using
[itertools.islice](http://docs.python.org/2/library/itertools.html#itertools.islice)?
import itertools
import numpy as np
for i in itertools.count():
tmp = list(itertools.islice(generator, 10000000))
if not tmp:
break
np.savez_compressed('results_{}'.format(i), tmp)
del tmp
|
how to create a dictionary from a file?
Question: I'm trying to write a Python code that will allow me to take in text, and read
it line by line. In each line, the words just go into the dictionary as a key
and the numbers should be the assigned values, as a list. the file
'topics.txt' will be composed of hundreds of lines that have the same format
as this:
1~cocoa
2~
3~
4~
5~grain~wheat~corn~barley~oat~sorghum
6~veg-oil~linseed~lin-oil~soy-oil~sun-oil~soybean~oilseed~corn~sunseed~grain~sorghum~wheat
7~
8~
9~earn
10~acq
and so on.. i need to create dictionaries for each word for ex: Ideally, the
name "grain" would be a key in the dictionary, and the values would be
dict[grain]: [5,6,..]. similarly, "cocoa" would be another key and values
would be dict[cocoa]:[1,..] Not much,but so far..
with open("topics.txt", "r") as fi: # Data read from a text file is a string
d = {}
for i in fi.readlines():
temp = i.split()
#i am lost here
num = temp[0]
d[name] = [map(int, num)]
Answer: <http://docs.python.org/3/library/collections.html#collections.defaultdict>
import collections
with open('topics.txt') as f:
d = collections.defaultdict(list)
for line in f:
value, *keys = line.strip().split('~')
for key in filter(None, keys):
d[key].append(value)
`value, *keys = ...` is [Extended Iterable
Unpacking](http://www.python.org/dev/peps/pep-3132/) which is only available
in Python 3.x.
|
Qt tcp/ip server works with telnet, but not python or netcat
Question: I have a Qt tcp/ip server listening on a port. I can talk to it with telnet,
but when I try with netcat the input commands are truncated. When I try to
send it a command through python, it doesn't see anything. Has anyone else run
into an issue like this with a Qt tcp server? Code follows.
Server
QTcpServer remoteControlServer;
remoteControlClient = remoteControlServer.nextPendingConnection();
connect(remoteControlClient, SIGNAL(readyRead()), this, SLOT(remoteCommandRead()));
The command interpreter -> This is where I suspect the problem is. Is
canReadLine() not doing what I want? I am just sending strings, so the line-
oriented protocol is what I think I should be using.
void MainWindow::remoteCommandRead()
{
QByteArray lineBuffer;
QByteArray consoleString;
QByteArray command;
QList<QByteArray> commandList;
while(remoteControlClient->canReadLine())
{
lineBuffer = remoteControlClient->readLine();
lineBuffer.chop(2);
lineBuffer.simplified();
commandList = lineBuffer.split(' ');
The python client
import socket
remote_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('address', port)
remote_sock.connect(server_address)
remote_sock.sendall('commandString')
Many thanks.
Answer: Use
trimmedLineBuffer = lineBuffer.trimmed();
commandList = trimmedLineBuffer.split(' ');
instead of
lineBuffer.chop(2);
lineBuffer.simplified();
From python append "/r/n" to the end of the string you are sending and
everything will work fine!
|
Extracting part of a string with irregular delimiters in python
Question: I am wanting to extract the last part of the name of the file that is
delimited by a constant prefix and '.csv'
Name of the file might look like:
> constant_prefix_**my file name**.csv
or
> constant_prefix_**myfilename**.csv
I would like to extract the values marked in bold into a variable.
Please advise.
Answer: Script:
import re
name1 = 'constant_prefix_my file name.csv'
name2 = 'constant_prefix_myfilename.csv'
def get_name(string):
return re.findall(r'constant_prefix_(my.*)\.csv', string)[0]
Demo:
print get_name(name1)
print get_name(name2)
Output:
my file name
myfilename
Or you can do this:
names = [get_name(n) for n in [name1, name2]]
print names
Output:
['my file name', 'myfilename']
|
Multithreading in python using queue
Question: I am quite new to Python and I need to implement multithreading in my code.
I have a huge .csv file (million lines) as my input. I read the line, make a
rest request for each line, do some processing on each line and write the
output into another file. The ordering of lines in input/output file does
matter . Right now I am doing this line by line. I want to run the same code,
but in parallel, i.e read 20 lines of input from .csv file and make the rest
call in parallel so that my program is faster.
I have been reading up on <http://docs.python.org/2/library/queue.html>, but I
read about the python GIL issue which says the code will not run faster even
after multithreading. Is there any other way to achieve multithreading in a
simple way?
Answer: Can you break the .csv file into multiple smaller files? If you can, then you
could have another program running multiple versions of your processer.
Say the files were all named _file1_ , _file2_ , etc. and your processer took
the filename as an argument. You could have:
import subprocess
import os
import signal
for i in range(1,numfiles):
program = subprocess.Popen(['python'], "processer.py", "file" + str(i))
pid = program.pid
#if you need to kill the process:
os.kill(pid, signal.SIGINT)
|
Print multiple variables in one line using python
Question: I need some assistance with a python script. I need to search a dhcpd file for
host entires, their MAC and IP, and print it in one line. I am able to locate
the hostname and IP address but cannot figure out how to get the variables out
of the if statement to put in one line. Any suggestions, the code is below:
#!/usr/bin/python
import sys
import re
#check for arguments
if len(sys.argv) > 1:
print "usage: no arguments required"
sys.exit()
else:
dhcp_file = open("/etc/dhcp/dhcpd.conf","r")
for line in dhcp_file:
if re.search(r'\bhost\b',line):
split = re.split(r'\s+', line)
print split[1]
if re.search(r'\bhardware ethernet\b',line):
ip = re.split(r'\s+',line)
print ip[2]
dhcp_file.close()
Answer: There are a number of ways that you could go about this. The simplest is
probably to initialize an empty string before the if statements. Then, instead
of printing split[1] and ip[2], concatenate them to the empty string and print
that afterwards. So it would look something like this:
printstr = ""
if re.search...
...
printstr += "Label for first item " + split[1] + ", "
if re.search...
...
printstr += "Label for second item " + ip[2]
print printstr
|
Converting an UNIX python program to work in windows
Question: I need to make a program that drives a DYMO LabelManager PnP label printing
device. DYMO provides a SDK for this purpose, but after some desperate trying,
I'd say the SDK is useless. Then I found a program which is just what I need,
written by a guy named S.Bronner. But the problem is that his program is made
for Python in UNIX, and I would need it to work in Windows with python. So I'm
asking, is there anyone who could examine this code and convert it to work in
windows for me? My Python skills are not good enough to accomplish this. Here
is the code which should be converted:
#!/usr/bin/env python
DEV_CLASS = 3
DEV_VENDOR = 0x0922
DEV_PRODUCT = 0x1001
DEV_NODE = None
DEV_NAME = 'Dymo LabelManager PnP'
FONT_FILENAME = '/usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf'
FONT_SIZERATIO = 7./8
import Image
import ImageDraw
import ImageFont
import array
import fcntl
import os
import re
import struct
import subprocess
import sys
import termios
import textwrap
class DymoLabeler:
"""
Create and work with a Dymo LabelManager PnP object.
This class contains both mid-level and high-level functions. In general,
the high-level functions should be used. However, special purpose usage
may require the mid-level functions. That is why they are provided.
However, they should be well understood before use. Look at the
high-level functions for help. Each function is marked in its docstring
with 'HLF' or 'MLF' in parentheses.
"""
def __init__(self, dev):
"""Initialize the LabelManager object. (HLF)"""
self.maxBytesPerLine = 8 # 64 pixels on a 12mm-tape
self.ESC = 0x1b
self.SYN = 0x16
self.cmd = []
self.rsp = False
self.bpl = None
self.dtb = 0
if not os.access(dev, os.R_OK | os.W_OK): return False
self.dev = open(dev, 'r+')
def sendCommand(self):
"""Send the already built command to the LabelManager. (MLF)"""
if len(self.cmd) == 0: return
cmdBin = array.array('B', self.cmd)
cmdBin.tofile(self.dev)
self.cmd = []
if not self.rsp: return
self.rsp = False
rspBin = self.dev.read(8)
rsp = array.array('B', rspBin).tolist()
return rsp
def resetCommand(self):
"""Remove a partially built command. (MLF)"""
self.cmd = []
self.rsp = False
def buildCommand(self, cmd):
"""Add the next instruction to the command. (MLF)"""
self.cmd += cmd
def statusRequest(self):
"""Set instruction to get the device's status. (MLF)"""
cmd = [self.ESC, ord('A')]
self.buildCommand(cmd)
self.rsp = True
def dotTab(self, value):
"""Set the bias text height, in bytes. (MLF)"""
if value < 0 or value > self.maxBytesPerLine: raise ValueError
cmd = [self.ESC, ord('B'), value]
self.buildCommand(cmd)
self.dtb = value
self.bpl = None
def tapeColor(self, value):
"""Set the tape color. (MLF)"""
if value < 0: raise ValueError
cmd = [self.ESC, ord('C'), value]
self.buildCommand(cmd)
def bytesPerLine(self, value):
"""Set the number of bytes sent in the following lines. (MLF)"""
if value < 0 or value + self.dtb > self.maxBytesPerLine: raise ValueError
if value == self.bpl: return
cmd = [self.ESC, ord('D'), value]
self.buildCommand(cmd)
self.bpl = value
def cut(self):
"""Set instruction to trigger cutting of the tape. (MLF)"""
cmd = [self.ESC, ord('E')]
self.buildCommand(cmd)
def line(self, value):
"""Set next printed line. (MLF)"""
self.bytesPerLine(len(value))
cmd = [self.SYN] + value
self.buildCommand(cmd)
def chainMark(self):
"""Set Chain Mark. (MLF)"""
self.dotTab(0)
self.bytesPerLine(self.maxBytesPerLine)
self.line([0x99] * self.maxBytesPerLine)
def skipLines(self, value):
"""Set number of lines of white to print. (MLF)"""
if value <= 0: raise ValueError
self.bytesPerLine(0)
cmd = [self.SYN] * value
self.buildCommand(cmd)
def initLabel(self):
"""Set the label initialization sequence. (MLF)"""
cmd = [0x00] * 8
self.buildCommand(cmd)
def getStatus(self):
"""Ask for and return the device's status. (HLF)"""
self.statusRequest()
rsp = self.sendCommand()
print rsp
def printLabel(self, lines, dotTab):
"""Print the label described by lines. (HLF)"""
self.initLabel
self.tapeColor(0)
self.dotTab(dotTab)
for line in lines:
self.line(line)
self.skipLines(56) # advance printed matter past cutter
self.skipLines(56) # add symmetric margin
self.statusRequest()
rsp = self.sendCommand()
print rsp
def die(message=None):
if message: print >> sys.stderr, message
sys.exit(1)
def pprint(par, fd=sys.stdout):
rows, columns = struct.unpack('HH', fcntl.ioctl(sys.stderr, termios.TIOCGWINSZ, struct.pack('HH', 0, 0)))
print >> fd, textwrap.fill(par, columns)
def getDeviceFile(classID, vendorID, productID):
# find file containing the device's major and minor numbers
searchdir = '/sys/bus/hid/devices'
pattern = '^%04d:%04X:%04X.[0-9A-F]{4}$' % (classID, vendorID, productID)
deviceCandidates = os.listdir(searchdir)
foundpath = None
for devname in deviceCandidates:
if re.match(pattern, devname):
foundpath = os.path.join(searchdir, devname)
break
if not foundpath: return
searchdir = os.path.join(foundpath, 'hidraw')
devname = os.listdir(searchdir)[0]
foundpath = os.path.join(searchdir, devname)
filepath = os.path.join(foundpath, 'dev')
# get the major and minor numbers
f = open(filepath, 'r')
devnums = [int(n) for n in f.readline().strip().split(':')]
f.close()
devnum = os.makedev(devnums[0], devnums[1])
# check if a symlink with the major and minor numbers is available
filepath = '/dev/char/%d:%d' % (devnums[0], devnums[1])
if os.path.exists(filepath):
return os.path.realpath(filepath)
# check if the relevant sysfs path component matches a file name in
# /dev, that has the proper major and minor numbers
filepath = os.path.join('/dev', devname)
if os.stat(filepath).st_rdev == devnum:
return filepath
# search for a device file with the proper major and minor numbers
for dirpath, dirnames, filenames in os.walk('/dev'):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if os.stat(filepath).st_rdev == devnum:
return filepath
def access_error(dev):
pprint('You do not have sufficient access to the device file %s:' % dev, sys.stderr)
subprocess.call(['ls', '-l', dev], stdout=sys.stderr)
print >> sys.stderr
pprint('You probably want to add a rule in /etc/udev/rules.d along the following lines:', sys.stderr)
print >> sys.stderr, ' SUBSYSTEM=="hidraw", \\'
print >> sys.stderr, ' ACTION=="add", \\'
print >> sys.stderr, ' DEVPATH=="/devices/pci[0-9]*/usb[0-9]*/0003:0922:1001.*/hidraw/hidraw0", \\'
print >> sys.stderr, ' GROUP="plugdev"'
print >> sys.stderr
pprint('Following that, turn off your device and back on again to activate the new permissions.', sys.stderr)
# get device file name
if not DEV_NODE:
dev = getDeviceFile(DEV_CLASS, DEV_VENDOR, DEV_PRODUCT)
else:
dev = DEV_NODE
if not dev: die("The device '%s' could not be found on this system." % DEV_NAME)
# create dymo labeler object
lm = DymoLabeler(dev)
if not lm: die(access_error(dev))
# check for any text specified on the command line
labeltext = [arg.decode(sys.stdin.encoding) for arg in sys.argv[1:]]
if len(labeltext) == 0: die("No label text was specified.")
# create an empty label image
labelheight = lm.maxBytesPerLine * 8
lineheight = float(labelheight) / len(labeltext)
fontsize = int(round(lineheight * FONT_SIZERATIO))
font = ImageFont.truetype(FONT_FILENAME, fontsize)
labelwidth = max(font.getsize(line)[0] for line in labeltext)
labelbitmap = Image.new('1', (labelwidth, labelheight))
# write the text into the empty image
labeldraw = ImageDraw.Draw(labelbitmap)
for i, line in enumerate(labeltext):
lineposition = int(round(i * lineheight))
labeldraw.text((0, lineposition), line, font=font, fill=255)
del labeldraw
# convert the image to the proper matrix for the dymo labeler object
labelrotated = labelbitmap.transpose(Image.ROTATE_270)
labelstream = labelrotated.tostring()
labelstreamrowlength = labelheight/8 + (1 if labelheight%8 != 0 else 0)
if len(labelstream)/labelstreamrowlength != labelwidth: die('An internal problem was encountered while processing the label bitmap!')
labelrows = [labelstream[i:i+labelstreamrowlength] for i in range(0, len(labelstream), labelstreamrowlength)]
labelmatrix = [array.array('B', labelrow).tolist() for labelrow in labelrows]
# optimize the matrix for the dymo label printer
dottab = 0
while max(line[0] for line in labelmatrix) == 0:
labelmatrix = [line[1:] for line in labelmatrix]
dottab += 1
for line in labelmatrix:
while len(line) > 0 and line[-1] == 0:
del line[-1]
# print the label
lm.printLabel(labelmatrix, dottab)
Answer:
FONT_FILENAME = '/usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf'
// should be changed to path to the font on your system
won't work because of filesystem differences.
searchdir = '/sys/bus/hid/devices'
// take a look at "pywinusb" library (?)
won't work either, you have to get the devices in a different way. Not sure
from where though. The same problem is
filepath = '/dev/char/%d:%d' % (devnums[0], devnums[1])
this isn't accessible in Windows and you have to do in a different way.
Besides that everything else looks OS independent. If you have any errors
after fixing previous 3 problems, then edit them into your question please.
|
django syncdb script - filesystem location + altering the script?
Question: i'm using django for a few projects already and now i'm facing a problem with
the syncdb command. I need to alter the functionality of that command, have
you got any experience with that?
`python manage.py` looks like this:
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
I haven't found any `execute_from_command_line` on file system (to be more
precise, in the location `/usr/lib/python2.7/site-
packages/django/core/management`).
Any ideas, where is executed script located?
2) question:
Have you got any experience with manual altering of django database
(PostgreSQL) after `syncdb` is run and not running `syncdb` again to keep the
changes?
I need to change django constraints
`ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED` to
`ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED`
but if i do it manually, it is overwritten after syncdb is called again.
Answer: Thanks gertvdijk for the right direction. The solution is to use Custom SQL
queries, which are run just after creating the tables.
Django documentation can be found over here:
<https://docs.djangoproject.com/en/dev/howto/initial-data/#initial-sql>
|
assertion error with np.load following numpy.savez
Question: I have 5 numpy arrays `a,b,c,d` and `e` all defined as:
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
I am saving these arrays like so:
np.savez_compressed('tmp/test',a=a,b=b,c=c,d=d,e=e)
This results in a file, `test.npz` being created.
However I am having problems when trying to load data in (follows example
[here](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savez.html#numpy.savez)):
>>> f=np.load('tmp/test.npz')
>>> f.files
['a', 'c', 'b', 'e', 'd']
>>> f['a']
Gives a large string of errors ending in:
File "C:\Python27\lib\compiler\transformer.py", line 754, in atom_lbrace
return self.com_dictorsetmaker(nodelist[1])
File "C:\Python27\lib\compiler\transformer.py", line 1214, in com_dictorsetmaker
assert nodelist[0] == symbol.dictorsetmaker
AssertionError
I have considered using `pickle` instead. However this results in file sizes
four times that of the .npz files so I'd like to use `savez` or
`savez_compressed`.
Does anyone have any idea what I'm doing wrong, or suggestions for alternative
approaches?
Here is a script that will produce the error:
def saver():
import numpy as np
a= np.arange(1,10)
b=a
c=a
d=a
e=a
np.savez_compressed('tmp/test',a=a,b=b,c=c,d=d,e=e)
f=np.load('tmp/test.npz')
print f.files
print f['a']
Here is the full traceback:
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
saver.saver()
File "C:\Python27\saver.py", line 14, in saver
print f['a']
File "C:\Python27\lib\site-packages\numpy\lib\npyio.py", line 241, in __getitem__
return format.read_array(value)
File "C:\Python27\lib\site-packages\numpy\lib\format.py", line 440, in read_array
shape, fortran_order, dtype = read_array_header_1_0(fp)
File "C:\Python27\lib\site-packages\numpy\lib\format.py", line 336, in read_array_header_1_0
d = safe_eval(header)
File "C:\Python27\lib\site-packages\numpy\lib\utils.py", line 1156, in safe_eval
ast = compiler.parse(source, mode="eval")
File "C:\Python27\lib\compiler\transformer.py", line 53, in parse
return Transformer().parseexpr(buf)
File "C:\Python27\lib\compiler\transformer.py", line 132, in parseexpr
return self.transform(parser.expr(text))
File "C:\Python27\lib\compiler\transformer.py", line 124, in transform
return self.compile_node(tree)
File "C:\Python27\lib\compiler\transformer.py", line 159, in compile_node
return self.eval_input(node[1:])
File "C:\Python27\lib\compiler\transformer.py", line 194, in eval_input
return Expression(self.com_node(nodelist[0]))
File "C:\Python27\lib\compiler\transformer.py", line 805, in com_node
return self._dispatch[node[0]](node[1:])
File "C:\Python27\lib\compiler\transformer.py", line 578, in testlist
return self.com_binary(Tuple, nodelist)
File "C:\Python27\lib\compiler\transformer.py", line 1082, in com_binary
return self.lookup_node(n)(n[1:])
File "C:\Python27\lib\compiler\transformer.py", line 596, in test
then = self.com_node(nodelist[0])
File "C:\Python27\lib\compiler\transformer.py", line 805, in com_node
return self._dispatch[node[0]](node[1:])
File "C:\Python27\lib\compiler\transformer.py", line 610, in or_test
return self.com_binary(Or, nodelist)
File "C:\Python27\lib\compiler\transformer.py", line 1082, in com_binary
return self.lookup_node(n)(n[1:])
File "C:\Python27\lib\compiler\transformer.py", line 615, in and_test
return self.com_binary(And, nodelist)
File "C:\Python27\lib\compiler\transformer.py", line 1082, in com_binary
return self.lookup_node(n)(n[1:])
File "C:\Python27\lib\compiler\transformer.py", line 619, in not_test
result = self.com_node(nodelist[-1])
File "C:\Python27\lib\compiler\transformer.py", line 805, in com_node
return self._dispatch[node[0]](node[1:])
File "C:\Python27\lib\compiler\transformer.py", line 626, in comparison
node = self.com_node(nodelist[0])
File "C:\Python27\lib\compiler\transformer.py", line 805, in com_node
return self._dispatch[node[0]](node[1:])
File "C:\Python27\lib\compiler\transformer.py", line 659, in expr
return self.com_binary(Bitor, nodelist)
File "C:\Python27\lib\compiler\transformer.py", line 1082, in com_binary
return self.lookup_node(n)(n[1:])
File "C:\Python27\lib\compiler\transformer.py", line 663, in xor_expr
return self.com_binary(Bitxor, nodelist)
File "C:\Python27\lib\compiler\transformer.py", line 1082, in com_binary
return self.lookup_node(n)(n[1:])
File "C:\Python27\lib\compiler\transformer.py", line 667, in and_expr
return self.com_binary(Bitand, nodelist)
File "C:\Python27\lib\compiler\transformer.py", line 1082, in com_binary
return self.lookup_node(n)(n[1:])
File "C:\Python27\lib\compiler\transformer.py", line 671, in shift_expr
node = self.com_node(nodelist[0])
File "C:\Python27\lib\compiler\transformer.py", line 805, in com_node
return self._dispatch[node[0]](node[1:])
File "C:\Python27\lib\compiler\transformer.py", line 683, in arith_expr
node = self.com_node(nodelist[0])
File "C:\Python27\lib\compiler\transformer.py", line 805, in com_node
return self._dispatch[node[0]](node[1:])
File "C:\Python27\lib\compiler\transformer.py", line 695, in term
node = self.com_node(nodelist[0])
File "C:\Python27\lib\compiler\transformer.py", line 805, in com_node
return self._dispatch[node[0]](node[1:])
File "C:\Python27\lib\compiler\transformer.py", line 715, in factor
node = self.lookup_node(nodelist[-1])(nodelist[-1][1:])
File "C:\Python27\lib\compiler\transformer.py", line 727, in power
node = self.com_node(nodelist[0])
File "C:\Python27\lib\compiler\transformer.py", line 805, in com_node
return self._dispatch[node[0]](node[1:])
File "C:\Python27\lib\compiler\transformer.py", line 739, in atom
return self._atom_dispatch[nodelist[0][0]](nodelist)
File "C:\Python27\lib\compiler\transformer.py", line 754, in atom_lbrace
return self.com_dictorsetmaker(nodelist[1])
File "C:\Python27\lib\compiler\transformer.py", line 1214, in com_dictorsetmaker
assert nodelist[0] == symbol.dictorsetmaker
AssertionError
Answer: Cannot reproduce your problem neither on Linux or Mac (Python 2.7, numpy
1.6.1/1.7.1)
But, I've noticed you using relative path for saving file `tmp/test.npz`. Is
that intentional? In my recollection recent versions of Windows have some
special treatment for a new files applications trying to create in some
directories (like '/Program Files/') - it moves them away but still tells
application they are there in some cases. It does not seems to be likely case
here, but can you try absolute path for a file you are saving?
BTW: As alternative to ZIP-archive (which `savez` `savez_compressed` creates)
you can try pickle with 'LZMAFile' as a file object. It gives very good
compression rate (but it can be slow and require more memory and time while
compressing/saving file);
It is used as any other file-object wrapper, something like that (to load
pickled data):
from lzma import LZMAFile
import cPickle as pickle
if fileName.endswith('.xz'):
dataFile = LZMAFile(fileName,'r')
else:
dataFile = file(fileName, 'ro')
data = pickle.load(dataFile)
|
Python suds - Recursion error in wsdl.py
Question: I am currently writing a Python script using the suds package to connect to a
new client. When I call suds.Client with the url, I get a recursion error:
RuntimeError: maximum recursion depth exceeded while pickling an object
File "c:\Users\mdriscoll\Documents\projects\test_soap\test_soap.py", line 112, in <module>
main(sys.argv[1:])
File "c:\Users\mdriscoll\Documents\projects\test_soap\test_soap.py", line 100, in main
sendSOAPMsg(agency, fax_id, fax_num, setxid)
File "c:\Users\mdriscoll\Documents\projects\test_soap\test_soap.py", line 32, in sendSOAPMsg
client = Client('https://somerandomclient.com/blahblah.svc?wsdl')
File "c:\Users\mdriscoll\Documents\projects\test_soap\suds\client.py", line 112, in __init__
self.wsdl = reader.open(url)
File "c:\Users\mdriscoll\Documents\projects\test_soap\suds\reader.py", line 152, in open
d = self.fn(url, self.options)
File "c:\Users\mdriscoll\Documents\projects\test_soap\suds\wsdl.py", line 157, in __init__
self.open_imports()
File "c:\Users\mdriscoll\Documents\projects\test_soap\suds\wsdl.py", line 202, in open_imports
imp.load(self)
File "c:\Users\mdriscoll\Documents\projects\test_soap\suds\wsdl.py", line 314, in load
d = Definitions(url, options)
File "c:\Users\mdriscoll\Documents\projects\test_soap\suds\wsdl.py", line 136, in __init__
d = reader.open(url)
File "c:\Users\mdriscoll\Documents\projects\test_soap\suds\reader.py", line 80, in open
cache.put(id, d)
File "c:\Users\mdriscoll\Documents\projects\test_soap\suds\cache.py", line 336, in put
bfr = pickle.dumps(object, self.protocol)
At first, I thought it was related to the issue mentioned earlier on Stack:
* [Python suds showing the following issues "RuntimeError: maximum recursion depth exceeded"](http://stackoverflow.com/questions/5742808/python-suds-showing-the-following-issues-runtimeerror-maximum-recursion-depth)
But that is an issue in suds' schema.py. I tried the patch mentioned just in
case, but it has no effect and the logging that was added in the patch is
never called, so I know that is not the issue here.
I am running Python 2.6 on Windows with suds 4.1 beta. Note: the url in the
traceback has been scrubbed since I am not allowed to mention their name.
Answer: I am the developer working on the other side of this web service. There was
indeed a circular reference in the WSDL. I have since fixed that issue and
Mike is no longer seeing the recursion error.
On my side, the service is being built on the .NET framework using WCF. The
issue was due to my attempt to get rid of the <http://tempuri.org> namespace
in the WSDL. I had added the correct Namespace to the ServiceContract,
DataContract, and ServiceBehavior attributes on the appropriate service
classes, but did not know about the bindingNamespace configuration value on
the server endpoint element. This caused Visual Studio to generate two WSDL
files which referenced eachother, one for the elements belonging in the
correct namespace and one for the binding information which was in the
tempuri.org namespace.
I found the following blog post to be extremely helpful:
<http://www.ilovesharepoint.com/2008/07/kill-tempuri-in-wcf-services.html>
|
python 2.7 isinstance fails at dynamically imported module class
Question: I'm currently writing some kind of tiny api to support extending module
classes. Users should be able to just write their class name in a config and
it gets used in our program. The contract is, that the class' module has a
function called `create(**kwargs)` to return an instance of our base module
class, and is placed in a special folder. But the isinstance check Fails as
soon as the import is made dynamically.
modules are placed in lib/services/_name_
module base class (in lib/services/service)
class Service:
def __init__(self, **kwargs):
#some initialization
example module class (in lib/services/ping)
class PingService(Service):
def __init__(self, **kwargs):
Service.__init__(self,**kwargs)
# uninteresting init
def create(kwargs):
return PingService(**kwargs)
importing function
import sys
from lib.services.service import Service
def doimport( clazz, modPart, kw, class_check):
path = "lib/" + modPart
sys.path.append(path)
mod = __import__(clazz)
item = mod.create(kw)
if class_check(item):
print "im happy"
return item
calling code
class_check = lambda service: isinstance(service, Service)
s = doimport("ping", "services", {},class_check)
print s
from lib.services.ping import create
pingService = create({})
if isinstance(pingService, Service):
print "why this?"
what the hell am I doing wrong
here is a small example zipped up, just extract and run `test.py` without
arguments [zip
example](https://docs.google.com/file/d/0B9fS_Iy9TY0INTA4UmJZQzlKUTQ/edit?usp=sharing)
Answer: The problem was in your `ping.py` file. I don't know exactly why, but when
dinamically importing it was not accepting the line `from service import
Service`, so you just have to change it to the relative path: `from
lib.services.service import Service`. Adding `lib/services` to the `sys.path`
could not make it work the inheritance, which I found strange...
Also, I am using `imp.load_source` which seems more robust:
import os, imp
def doimport( clazz, modPart, kw, class_check):
path = os.path.join('lib', modPart, clazz + '.py')
mod = imp.load_source( clazz, path )
item = mod.create(kw)
if class_check(item):
print "im happy"
return item
|
scrapy - how to get text from 'div'
Question: I just started to get to know scrapy. Now I am trying to crawl by following
tutorials. But I have difficulty to crawl text from div.
This is items.py
from scrapy.item import Item, Fied
class DmozItem(Item):
name = Field()
title = Field()
pass
This is dmoz_spider.py
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item
from dmoz.items import DmozItem
class DmozSpider(BaseSpider):
name = "dmoz"
allowed_domains = ["roxie.com"]
start_urls = ["http://www.roxie.com/events/details.cfm?eventID=4921702B-9E3D-8678-50D614177545A594"]
def parse(self, response):
hxs = HtmlXPathSelector(response)
sites = hxs.select('//div[@id="eventdescription"]')
items = []
for site in sites:
item = DmozItem()
item['name'] = hxs.select("text()").extract()
items.append(item)
return items
And now I am trying to crawl from top folder by commanding this:
scrapy crawl dmoz -o scraped_data.json -t json
But the file was created with only '['.
It perfectly works in the console(by commanding each select), but somehow it
doesn't work as a script. I am really a starter of scrapy. Could you guys let
me know how can I get the data in 'div'? Thanks in advance.
_*_ In addition, this is what I get.
2013-06-19 08:43:56-0700 [scrapy] INFO: Scrapy 0.16.5 started (bot: dmoz)
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/web/microdom.py:181: SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert (oldChild.parentNode is self,
2013-06-19 08:43:56-0700 [scrapy] DEBUG: Enabled extensions: FeedExporter, LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState
2013-06-19 08:43:56-0700 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMiddleware, ChunkedTransferMiddleware, DownloaderStats
2013-06-19 08:43:56-0700 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2013-06-19 08:43:56-0700 [scrapy] DEBUG: Enabled item pipelines:
2013-06-19 08:43:56-0700 [dmoz] INFO: Spider opened
2013-06-19 08:43:56-0700 [dmoz] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2013-06-19 08:43:56-0700 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:6023
2013-06-19 08:43:56-0700 [scrapy] DEBUG: Web service listening on 0.0.0.0:6080
2013-06-19 08:43:56-0700 [dmoz] DEBUG: Crawled (200) <GET http://www.roxie.com/events/details.cfm?eventID=4921702B-9E3D-8678-50D614177545A594> (referer: None)
2013-06-19 08:43:56-0700 [dmoz] INFO: Closing spider (finished)
2013-06-19 08:43:56-0700 [dmoz] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 281,
'downloader/request_count': 1,
'downloader/request_method_count/GET': 1,
'downloader/response_bytes': 27451,
'downloader/response_count': 1,
'downloader/response_status_count/200': 1,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2013, 6, 19, 15, 43, 56, 569164),
'log_count/DEBUG': 7,
'log_count/INFO': 4,
'response_received_count': 1,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'start_time': datetime.datetime(2013, 6, 19, 15, 43, 56, 417661)}
2013-06-19 08:43:56-0700 [dmoz] INFO: Spider closed (finished)
Answer: I can get you the title of the film, but I'm somewhat crappy with XPath so the
description XPath will get you _everything_ within the `<div class="tabbertab"
title="Synopsis">` element. It's not ideal, but it's a starting point. Getting
the image URL is left as an exercise for the OP. :)
from scrapy.item import Item, Fied
class DmozItem(Item):
title = Field()
description = Field()
pass
class DmozSpider(BaseSpider):
name = "test"
allowed_domains = ["roxie.com"]
start_urls = ["http://www.roxie.com/events/details.cfm?eventID=4921702B-9E3D-8678-50D614177545A594"]
def parse(self, response):
hxs = HtmlXPathSelector(response)
item = DmozItem()
item['title'] = hxs.select('//div[@style="width: 100%;"]/text()').extract()
item['description'] = hxs.select('//div[@class="tabbertab"]').extract()
return item
|
Sum all values of database column with Queryset Model.objects.aggregate(Sum(***))
Question: So I'm creating an expense sheet app in Django and I'm trying to get the total
sum of all the expense costs, which I then want to display in my template.
My Model:
class Expense(models.Model):
PAYMENT_CHOICES = (
('Cash', 'cash'),
('Credit', 'credit'),
('Debit', 'debit')
)
date = models.DateField()
store = models.CharField(max_length=100)
price = models.DecimalField(max_digits=20, decimal_places=2)
payment_type = models.CharField(max_length=8, choices=PAYMENT_CHOICES)
category = models.CharField(max_length=100)
def __unicode__(self):
return u'%s' % (self.date)
def _price_sum(self):
return self.objects.aggregate(total_price = Sum('price'))
price_sum = property(_price_sum)
I'm trying to call 'price_sum' in my template with the tag `{{
expenses.price_sum }}`
my template looks like this
{% if expenses %}
<table class='table table-hover'>
<tr>
<thead>
<th>Date</th>
<th>Store</th>
<th>Price</th>
<th>Payment Type</th>
<th>Category</th>
<th></th>
<th></th>
</thead>
</tr>
{% for expense in expenses %}
<tr>
<tbody>
<td>{{expense.date}}</td>
<td>{{expense.store}}</td>
<td>${{expense.price|floatformat:"2"|intcomma}}</td>
<td>{{expense.payment_type}}</td>
<td>{{expense.category}}</td>
<td>
<form action='{{expense.id}}/' method='get'>
<input type="submit" value="Edit" class="btn">
</form></td>
<td>
<form action='{{expense.id}}/delete/' method='post'>{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger" data-dismiss="alert">
</form></td>
</tbody>
</tr>
{% endfor %}
</table>
<h3>Table: {{ expenses.price_sum }}</h3>
{% else %}
<p>No expenses logged.</p>
{% endif %}
I'm not certain if I'm using the template tag incorrectly or if my function is
wrong or what is going wrong. I know this is probably really simple but I've
searched all over StackOverflow and the Django and Python docs and anything I
could find and I just can't figure it out.
UPDATE: views.py
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from expenses.models import Expense
from expenses.form import ExpenseForm
def index(request,template='expenses/index.html'):
all_expenses = Expense.objects.all()
return render(request, template, {'all_expenses': all_expenses})
def new(request, template='expenses/new.html'):
if request.method == 'POST':
new_expense = ExpenseForm(request.POST)
if new_expense.is_valid() and new_expense.clean():
new_expense.save()
return HttpResponseRedirect('/expenses/')
else:
new_expense = ExpenseForm()
return render(request, template, {'new_expense':new_expense})
def edit(request, expense_id, template='expenses/edit.html'):
expense = Expense.objects.get(id=expense_id)
if request.method == 'POST':
form = ExpenseForm(request.post, instance=expense)
if form.is_valid and form.clean():
expense = form.save()
return HttpResponseRedirect('/expenses/')
else:
expense = ExpenseForm(instance=expense)
return render(request, template, {'expense':expense})
def delete(request, expense_id):
if request.method == 'POST':
expense = Expense.objects.get(id=expense_id).delete()
return HttpResponseRedirect('/expenses/')
else:
return HttpResponse(status=404)
Answer: `aggregate` return dictionary that looks like `{'total_price':
Decimal('1234')}`.
So, change `_price_sum` as follow:
def _price_sum(self):
return self.objects.aggregate(total_price=Sum('price'))['total_price']
Or, change the template as follow:
{{ expenses.price_sum.price_sum }}
|
Difference between * and .* in regular expressions (using python)
Question: I'm using Python 2.7.
I would like to know the difference between `*` and `.*` while matching the
words.
Following is the code in python
exp = r'.*c' #here is the expression
line = '''abc dfdfdc dfdfeoriec''' #the words I need to match
re.findall(exp,line) #python expression
The output from the above code is:
['abc dfdfdc dfdfeoriec']
If I change `exp` value to:
exp = r'*c'
...then on execution I get the following error:
Traceback (most recent call last): File "<stdin>", line 1, in
<module> File "C:\Program
Files\Enthought\Canopy32\App\appdata\canopy-1.0.0.1160.win-x86\lib\re.py",
line 177, in findall
return _compile(pattern, flags).findall(string) File "C:\Program Files\Enthought\Canopy32\App\appdata\canopy-1.0.0.1160.win-x86\lib\re.py",
line 242, in _compile
raise error, v # invalid expression error: nothing to repeat
Here is another code
exp = r'c.*'
line1='''cdlfjd ceee cll'''
re.findall(exp,line1)
The output from above code is
['cdlfjd ceee cll']
If I change the `exp` value to:
exp = r'c*'
and then on execution I get the following output.
['c', '', '', '', '', '', '', 'c', '', '', '', '', 'c', '', '', '']
Please explain this behavior.
Answer: From the [docs](http://docs.python.org/2/library/re.html#regular-expression-
syntax):
'*'
> Causes the resulting RE to match 0 or more repetitions of the preceding RE,
> as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’
> followed by any number of ‘b’s.
IN `r'*c"` you've no preceding character to repeat, so it's an error.
>>> import re
>>> strs = "ccceeeddc"
>>> re.findall(r'c*',strs)
['ccc', '', '', '', '', '', 'c', '']
| | | | | |
e e e d d nothing found after last `c`
`c*` means find all `'c'`s(0 to any number of time) that are next to each
other and group them , so here when it reaches `'e'` no `'c'` is found so it
returns en empty string.
`'.*c'`: Group everything up to the last `c` found.
>>> strs = "abccccfoocbar"
>>> exp = r'.*c'
>>> re.findall(exp,strs)
['abccccfooc']
>>> strs = "qwertyu"
>>> re.findall(exp,strs) #no 'c' found
[]
`'c.*'`: This is exact opposite of the last one, group all characters that are
fuund after first 'c'.
>>> exp = r'c.*'
>>> strs = "abccccfoocbar"
>>> re.findall(exp,strs)
['ccccfoocbar']
>>> strs = "qwertyu"
>>> re.findall(exp,strs) #no 'c' found
[]
|
How to display a float matrix as elevation values in a 3D plot in Python?
Question: I currently have a heat map which is a 2D float matrix (list of lists of
floats to be accurate), and I can display it in 2D with matplotlib fairly
easily, but I would like to display it in a 3D plot such that the column and
row indices can by the X and Y values respectively, and the values in the
matrix are Z (elevation) values. What can I use to do that? I tried using
Axes3D but it didn't seem very suitable (or maybe I was using it wrong?). What
I am looking to do is conceptually very simple, to pretend the matrix is a DEM
and display it as such.
Also if possible I would like to be able to change viewing angles on-the-fly,
without having to re-generate the plot.
Any ideas?
These two questions are related but don't quite answer my question:
[3d plotting with
python](http://stackoverflow.com/questions/8841827/3d-plotting-with-python)
[Python: 3D contour from a 2D image - pylab and
contourf](http://stackoverflow.com/questions/15581935/python-3d-contour-
from-a-2d-image-pylab-and-contourf)
NB: The float matrix is rather large, typically 100x100 or more, and the last
time I tried to plot it in 3D my system ran out of memory and started
thrashing.
Answer: Your use case seems like it is tailor made for mayavi/mlab, which has a
function that does exactly what you are asking and by default permits
interactive 3D rotation:
import numpy as np; from mayavi import mlab
data = np.random.random((100,100))
mlab.surf(data)
mlab.show()
|
Apache log file data analysis with python pandas
Question: The problem with me is bit hard to explain. I'm analyzing a Apache log file
which following is one line from it.
112.135.128.20 - [13/May/2013:23:55:04 +0530] "GET /SVRClientWeb/ActionController HTTP/1.1" 302 2 "https://www.example.com/sample" "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10B329" GET /SVRClientWeb/ActionController - HTTP/1.1 www.example.com
Some parts from my code:
df = df.rename(columns={'%>s': 'Status', '%b':'Bytes Returned',
'%h':'IP', '%l':'Username', '%r': 'Request', '%t': 'Time', '%u': 'Userid', '%{Referer}i': 'Referer', '%{User-Agent}i': 'Agent'})
df.index = pd.to_datetime(df.pop('Time'))
test = df.groupby(['IP', 'Agent']).size()
test.sort()
print test[-20:]
I read log file to a data frame and get the following output with hit counts
and user agents.
IP Agent
74.86.158.106 Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/) 369
203.81.107.103 Mozilla/5.0 (Windows NT 6.1; rv:21.0) Gecko/20100101 Firefox/21.0 388
173.199.120.155 Mozilla/5.0 (compatible; AhrefsBot/4.0; +http://ahrefs.com/robot/) 417
124.43.84.242 Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31 448
112.135.196.223 Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36 454
124.43.155.138 Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0 461
124.43.104.198 Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0 467
Then I want to get the
1. Most highest 3 hit counts(their IPs) and find the frequency of their occurrence?(like time difference between each hit occurrence of the IP)
2. How to find whether there are different agents for one single IP?
At least please explain me how to solve above problems?
Answer: To do the first part you could just sort the DataFrame (by count) and take the
top three rows:
In [11]: df.sort('Count', ascending=False).head(3)
Out[11]:
IP Agent Count
6 124.43.104.198 Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20... 467
5 124.43.155.138 Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) G... 461
4 112.135.196.223 Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.3... 454
To test whether there are multiple rows (Agents) for a single IP you can use
groupby:
In [12]: g = df.groupby('IP')
In [13]: repeated = g.count().Count != 1
In [14]: repeated
Out[14]:
IP
112.135.196.223 False
124.43.104.198 False
124.43.155.138 False
124.43.84.242 False
173.199.120.155 False
203.81.107.103 False
74.86.158.106 False
Name: Count, dtype: bool
In [15]: repeated[repeated]
Out[15]: Series([], dtype: bool)
_There are none in this example._
In order to avoid sorting the entire DataFrame, it's possible ~~and it could
be more efficient (update: IT'S NOT)~~ to use
[`heapq`](http://docs.python.org/2/library/heapq.html) (I don't think there is
an nlargest in pandas):
In [21]: from heapq import nlargest
In [22]: top_3 = nlargest(3, df.iterrows(), key=lambda x: x[1]['Count'])
In [23]: pd.DataFrame.from_items(top_3).T
Out[23]:
IP Agent Count
6 124.43.104.198 Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20... 467
5 124.43.155.138 Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) G... 461
4 112.135.196.223 Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.3... 454
|
opening an excel file and writing to it in python
Question: How do I open an existing excel file, write to it, and save it as the same
filename. None of the previous data should be lost and the new data should be
saved.
The pseudocode would be as follows:
open excel file
write data to last row
save excel file
Answer: If you are willing to use csv format (has obvious limitations) you can use
Python's built in [CSV library](http://docs.python.org/2/library/csv.html).
Here is a short reader example:
>>> import csv
>>> with open('eggs.csv', 'rb') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print ', '.join(row)
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
Writer example:
import csv
with open('eggs.csv', 'a') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
Keep in mind with csv, you can only modify spreadsheet data, no fancy graphs
or anything.
|
IronPython convert from Python String to SByte array
Question: for the usage of an external dll in IronPython I have to pass a string to a
**char array** (char var[len]; in C++.NET). It seems to be expected to pass an
SByte array.
If I try
myVarFromCLibrary = myPyString
I get
TypeError: expected Array[SByte], got str
There is very little information in the web. Up to now I found that I can
apply something like this:
from System import Array
...
myCString = Array[System.SByte](myPyString)
myVarFromCLibrary = myCString
If I do so, I get an error like:
TypeError: expected SByte, got str
What is to do to get the right conversion.
Answer: Meanwhile I found a workaround but no solution:
def strToCharArray(theCharArray,theString):
asBytes = bytes(theString,'ascii')
for i in xrange(len(theString)):
theCharArray[i] = ord(asBytes[i])
theCharArray[len(asBytes)] = 0
def charArrayToStr(theCharArray):
chars = []
i = 0
while theCharArray[i]>0:
chars.append(chr(theCharArray[i]))
i += 1
return "".join(chars)
This keeps my program running but is not the real solution
|
How to place QWebView in QTabWidget?
Question: I'm new in Python and pyQt. I'm making desktop application for some forum. My
app work correct, but I'm don't know, how I can to place my QWebView element
in tab "QTabWidget"
Here is my full code:
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui, QtWebKit
from PyQt4.QtWebKit import QWebView
import http.client as http_c
import sys, os, webbrowser #re, html5lib
import lxml.html
from lxml import etree
class BaseWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self.centralWidget = QtGui.QWidget()
self.resize(800, 500)
self.setWindowTitle('PHP-Forum.ru')
#self.menubar = QtGui.QMenuBar()
#file = self.menubar.addMenu('Файл')
self.tabs = QtGui.QTabWidget()
self.tabs.addTab(QtGui.QWidget(),"Темы");
self.tabs.addTab(QtGui.QWidget(),"СМС");
exit = QtGui.QAction(QtGui.QIcon('icons/exit.png'), 'Выход', self)
exit.setShortcut('Ctrl+Q')
self.connect(exit, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))
menubar = self.menuBar()
file = menubar.addMenu('Файл')
file.addAction(exit)
settings = menubar.addMenu('Установки')
class Themes(BaseWindow):
def __init__(self, parent = None):
BaseWindow.__init__(self, parent)
self.webview = QWebView()
con = http_c.HTTPConnection('phpforum.ru')
con.request('GET', '/ssi.php?a=news&show=25')
res = con.getresponse()
html_code = res.read().decode('cp1251')
path = os.getcwd()
rpath = os.path.normpath(path + '/resources/').replace('\\', '/')
self.setWindowIcon(QtGui.QIcon(rpath + '/images/favicon.ico'))
doc = lxml.html.document_fromstring(html_code)
topics = doc.xpath('/html/body/table[@class="topic"]')
data = []
i = 0
for topic in topics:
i += 1
t_str = lxml.html.document_fromstring(etree.tostring(topic))
author_name = t_str.xpath('//a[@class="author"]/text()')
author_link = t_str.xpath('//a[@class="author"]/@href')
last_post = t_str.xpath('//span[@class="post_date"]/text()[1]')
title = t_str.xpath('//span[@class="topic_title"]/text()')
topic_link = t_str.xpath('//a[@class="topic_link"]/@href')
topic_text = t_str.xpath('//table[1]//tr[3]/td/text()')
try:
author_name = author_name[0]
except IndexError:
author_name = 'Guest'
author_link = '#'
else:
author_link = author_link[0]
try:
topic_text = topic_text[0]
except IndexError:
topic_text = None
data.append({
'title': title[0],
'author_name': author_name,
'author_link': author_link,
'last_post': last_post[0],
'topic_link': topic_link[0],
'topic_text': topic_text,
})
html_str = """
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="C:/Python33/scripts/pqt/phpforum/resources/css/style.css">
</head>
<body>
"""
for info in data:
html_str += """
<div class="topic">
<span class="title"><a href="{topic_link}">{title}</a></span>
<span class="author"><a href="{author_link}">{author_name}</a></span>
<span class="time">{last_post}</span>
</div>
<br>
""".format(**info)
html_str += """
</body>
</html>
"""
self.webview.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
self.webview.connect(self.webview.page(), QtCore.SIGNAL("linkClicked(const QUrl&)"), self.link_clicked)
self.webview.setHtml(html_str)
centralLayout = QtGui.QVBoxLayout()
centralLayout.addWidget(self.tabs, 1)
centralLayout.addWidget(self.webview, 2)
self.centralWidget.setLayout(centralLayout)
self.setCentralWidget(self.centralWidget)
def link_clicked(self, url):
webbrowser.open(str(url.toString()))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Themes()
window.show()
sys.exit(app.exec_())
It looks like this 
But I need it

Thanks in advance!
Answer: You've got you you asked for:
centralLayout.addWidget(self.webview, 2)
The you have to add `self.webview` into the layout inside tab of
`QtGui.QTabWidget`.
|
How do I run the OpenGrasp Robot Editor with Blender on Mac OS X?
Question: I'm using Mountain Lion at the moment. I've installed Blender (because it's a
dependency of OpenGrasp), and downloaded OpenGrasp. However, I try to load the
robot editor up and I get this:
$ python GraspRobotEditor.py
Traceback (most recent call last):
File "GraspRobotEditor.py", line 34, in <module>
import Blender
ImportError: No module named Blender
How do I point Python to the Blender python interface? the [Getting Started
guide](http://opengrasp.sourceforge.net/robotEditor.html#getting-started)
doesn't instruct you much here.
(I'm sure this is a trivial problem to solve but I'd like to see this
documented on StackOverflow anyway.)
Answer: From the error you it can't find the python module Blender which represents
the python hook to Blender. So there could be a few This could be any number
of reasons to do with your setup.
The first is that the Blender module is runtime generated whileBlender is
running. The specific 'Blender' module used is part of the Blender 2.4x
series. According to the link you provided there, they mention porting to
newer versions but checking their snv the code is definitely written for 2.49.
Blender 2.49b was the last stable release -
<http://download.blender.org/release/> Ensure you are using that.
The next thing is whether it can be run via the the Run Script command
TL:DR
* Start up blender
* Switch to the text workspace
* Open the script and see if it can be run directly.
If not you will need to install the folder to the Blender modules directory of
your install and then try running it.
Edit: Was looking at into the SVN some more and there does appear to be a
version 2 for blender 2.5+ which can be put into a zip file and installed via
the add-on installer. According to the bl_info it was build for 2.58 but what
support level you would need to try out yourself.
|
Join two timelines / list of tuples
Question: I have timelines/timeseries which consist of a list of two-tuples where the
first part of the tuple is a timestamp and the second part is the value. The
tuples are ordered by their timestamp.
I now have two of these timelines and need to divide them by each other. This
means that if I got values in both timelines for the same timestamp, I need to
divide them. If there is no value in one of the timelines on the timestamp, 0
should be assumed. If (and only if) a division by zero occurs, NaN should be
assumed. The timestamps have large gaps, which means that iterating from
min(timestamp) to max(timestamp) is not a solution.
I constructed a solution which is both, very unpythonic and has a poor running
time. As the timelines are about a million entries long, performance is
important for me. My solution does not take advantage, that both lists are
sorted.
Is there a better solution, if yes which?
#!/usr/bin/env python
l1 = [(1, 100), (2, 1000), (4, 1500), (5, 5400), (7, 7800)]
l2 = [(1, 20), (2, 400), (3, 240), (4, 500), (5, 100), (6, 27), ]
ex = [(1, 5), (2, 2), (3, 0), (4, 3), (5, 54), (6, 0), (7, float('NaN'))]
def f(l1, l2):
#Turn to dicts:
l1d = dict(l1)
l2d = dict(l2)
#Compute Keyspace
keys = set(l1d.keys()).union(set(l2d.keys()))
result = []
for key in keys:
if not key in l2d:
result.append((key, float('NaN')))
elif key not in l1d:
result.append((key, 0))
else:
result.append((key, l1d[key]/l2d[key]))
return result
r = f(l1, l2)
print("L1: %s" % (l1))
print("L2: %s" % (l2))
print("")
print("Expected: %s" % (ex))
print("Result: %s" % (r))
Answer: If performance is needed, have a look at [pandas](http://pandas.pydata.org/):
import pandas as pd
l1 = [(1, 100), (2, 1000), (4, 1500), (5, 5400), (7, 7800)]
l2 = [(1, 20), (2, 400), (3, 240), (4, 500), (5, 100), (6, 27), ]
s1 = pd.Series(dict(l1))
s2 = pd.Series(dict(l2))
now a very explicit mathematical operation:
s1 / s2
returns
1 5.0
2 2.5
3 NaN
4 3.0
5 54.0
6 NaN
7 NaN
If you want to replace `NaN` with zeroes if present in `l2`:
s1.reindex(s1.index|s2.index).fillna(0) / s2
1 5.0
2 2.5
3 0.0
4 3.0
5 54.0
6 0.0
7 NaN
Works perfectly well for million entries as well. You can use datetimes in
index and operate on them datetimecally.
|
64-bit argument for fcntl.ioctl()
Question: In my Python (2.7.3) code, I'm trying to use an ioctl call, accepting a long
int (64 bit) as an argument. I'm on a 64-bit system, so a 64-bit int is the
same size as a pointer.
**My problem is that Python doesn't seem to accept a 64-bit int as the
argument for a fcntl.ioctl() call.** It happily accepts a 32-bit int or a
64-bit pointer - **but what I need is to pass a 64-bit int.**
Here's my ioctl handler:
static long trivial_driver_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
long err = 0;
switch (cmd)
{
case 1234:
printk("=== (%u) Driver got arg %lx; arg<<32 is %lx\n", cmd, arg, arg<<32);
break;
case 5678:
printk("=== (%u) Driver got arg %lx\n", cmd, arg);
break;
default:
printk("=== OH NOES!!! %u %lu\n", cmd, arg);
err = -EINVAL;
}
return err;
}
In existing C code, I use the call like this:
static int trivial_ioctl_test(){
int ret;
int fd = open(DEV_NAME, O_RDWR);
unsigned long arg = 0xffff;
ret = ioctl(fd, 1234, arg); // ===(1234) Driver got arg ffff; arg<<32 is ffff00000000
arg = arg<<32;
ret = ioctl(fd, 5678, arg); // === (5678) Driver got arg ffff00000000
close(fd);
}
In python, I open the device file, and then I get the following results:
>>> from fcntl import ioctl
>>> import os
>>> fd = os.open (DEV_NAME, os.O_RDWR, 0666)
>>> ioctl(fd, 1234, 0xffff)
0
>>> arg = 0xffff<<32
>>> # Kernel log: === (1234) Driver got arg ffff; arg<<32 is ffff00000000
>>> # This demonstrates that ioctl() happily accepts a 32-bit int as an argument.
>>> import struct
>>> ioctl(fd, 5678, struct.pack("L",arg))
'\x00\x00\x00\x00\xff\xff\x00\x00'
>>> # Kernel log: === (5678) Driver got arg 7fff9eb1fcb0
>>> # This demonstrates that ioctl() happily accepts a 64-bit pointer as an argument.
>>> ioctl(fd, 5678, arg)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
ioctl(fd, 5678, arg)
OverflowError: signed integer is greater than maximum
>>> # Kernel log: (no change - OverflowError is within python)
>>> # Oh no! Can't pass a 64-bit int!
>>>
**Is there any way Python can pass my 64-bit argument to ioctl()?**
Answer: Whether or not this is possible using Python's `fcntl.ioctl()` will be system-
dependent. Tracing through the source code, the error message is coming from
the following test on [line 658 of
`getargs.c`](http://hg.python.org/cpython/file/bc6d28e726d8/Python/getargs.c#l658)...
else if (ival > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"signed integer is greater than maximum");
RETURN_ERR_OCCURRED;
}
...and on my system, `/usr/include/limits.h` tells me...
# define INT_MAX 2147483647
...which is (presumably) `(2 ** ((sizeof(int) * 8) - 1)) - 1`.
So, unless you're working on a system where `sizeof(int)` is at least `8`,
you'll have to call the underlying C function directly using the
[`ctypes`](http://docs.python.org/2/library/ctypes.html) module, but it's
platform-specific.
Assuming Linux, something like this ought to work...
from ctypes import *
libc = CDLL('libc.so.6')
fd = os.open (DEV_NAME, os.O_RDWR, 0666)
value = c_uint64(0xffff<<32)
libc.ioctl(fd, 5678, value)
|
Regex for matching string Python
Question: I wanted to match the numeric values of a string:
1,000 metric tonnes per contract month
Five cents ($0.05) per tonne
Five cents ($0.05) per tonne
1,000 metric tonnes per contract month
My current approach:
size = re.findall(r'(\d+(,?\d*).*?)', my_string)
What I get with my approach:
print size
[(u'1,000', u',000')]
As you can see, the number `1` was being cut out from the second element of
the list, why is that? Also, could I get a hint as to how I can match the
`$0.05` terms?
Answer: Something like this:
>>> import re
>>> strs = """1,000 metric tonnes per contract month
Five cents ($0.05) per tonne
Five cents ($0.05) per tonne
1,000 metric tonnes per contract month"""
>>> [m.group(0) for m in re.finditer(r'\$?\d+([,.]\d+)?', strs)]
['1,000', '$0.05', '$0.05', '1,000']
Demo : <http://rubular.com/r/UomzIY3SD3>
|
python format string unused named arguments
Question: Let's say I have:
action = '{bond}, {james} {bond}'.format(bond='bond', james='james')
this wil output:
'bond, james bond'
Next we have:
action = '{bond}, {james} {bond}'.format(bond='bond')
this will output:
KeyError: 'james'
Is there some workaround to prevent this error to happen, something like:
* if keyrror: ignore, leave it alone (but do parse others)
* compare format string with available named arguments, if missing then add
Answer: ## If you are using Python 3.2+, use can use
[str.format_map()](http://docs.python.org/3/library/stdtypes.html#str.format_map).
For `bond, bond`:
>>> from collections import defaultdict
>>> '{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond'))
'bond, bond'
For `bond, {james} bond`:
>>> class SafeDict(dict):
... def __missing__(self, key):
... return '{' + key + '}'
...
>>> '{bond}, {james} {bond}'.format_map(SafeDict(bond='bond'))
'bond, {james} bond'
## In Python 2.6/2.7
For `bond, bond`:
>>> from collections import defaultdict
>>> import string
>>> string.Formatter().vformat('{bond}, {james} {bond}', (), defaultdict(str, bond='bond'))
'bond, bond'
For `bond, {james} bond`:
>>> from collections import defaultdict
>>> import string
>>>
>>> class SafeDict(dict):
... def __missing__(self, key):
... return '{' + key + '}'
...
>>> string.Formatter().vformat('{bond}, {james} {bond}', (), SafeDict(bond='bond'))
'bond, {james} bond'
|
Memory error reading a zip file in python
Question: I have a thread in which I am reading a zip file with
`zipfile.ZipFile().read()`, where I am getting a memory error.
I am aware that `read()` loads the entire file into memory. The size of file
after unzipping is more than 100MB. I also tried with
`zipfile.ZipFile().open().readlines()`, but it takes too much time.
Is there any way that I can read the file with speed without getting memory
error?
Answer: Assuming you're trying to read a zipped text file, you can treat the file-like
object returned by
[`ZipFile.open()`](http://docs.python.org/2/library/zipfile#zipfile.ZipFile.open)
as an iterator, and process it line-by-line...
from zipfile import ZipFile
zip = ZipFile('myzip.zip')
stream = zip.open('myfile.txt')
for line in stream:
do_something_with(line)
|
Assigning a fieldname to a variable in Python
Question: I am new to Python and I am trying to check for nulls in the csv I am
processing. I am using a DictReader object with key pair values. I am using
the key pair values in the for loop to print out the information(kml in this
instance).
I go to run the program and it is not liking my variable assignment. Here is
the error I am receiving.
File "./csvtokml3.py", line 31
Latvariable = str(row["lat_degrees"]),Longvariable = str(row["lon_degrees"])
SyntaxError: can't assign to function call
Here is the code for the program.
#!/usr/bin/python
#
#
#
import csv
#Input the file name.
fname = raw_input("Enter file name WITHOUT extension: ")
data = csv.DictReader(open(fname + '.csv'), delimiter = ',')
#Open the file to be written.
f = open('csv2kml.kml', 'w')
#Writing the kml file.
f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
f.write("<kml xmlns='http://www.opengis.net/kml/2.'>\n")
f.write("<Document>\n")
f.write(" <name>" + fname + '.kml' +"</name>\n")
for row in data:
f.write(" <Placemark>\n")
f.write(" <name>" + str(row["station"]) + "</name>\n")
### f.write(" <description>" + str(row[0]) + "</description>\n")
f.write(" <Point>\n")
#Check for nulls for lat and long
Latvariable = str(row["lat_degrees"]), Longvariable = str(row["lon_degrees"])
if Latvariable !=null and Longvariable !=null:
f.write(" <coordinates>" + str(row["lat_degrees"]) + "," + str(row["lon_degrees"]) + "</coordinates>\n")
f.write(" </Point>\n")
f.write(" </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
f.close()
print "File Created. "
print "Press ENTER to exit. "
raw_input()
Answer: Your syntax is incorrect, you wanted:
Latvariable, Longvariable = str(row["lat_degrees"]), str(row["lon_degrees"])
instead to assign multiple values to multiple names. Alternatively, put the
two statements on separate lines:
Latvariable = str(row["lat_degrees"])
Longvariable = str(row["lon_degrees"])
You cannot combine multiple assignment statements with commas like you tried;
that works in JavaScript but not in Python.
|
Python: Tkinter Treeview Searchable
Question: Fairly straight forward question, and despite my best Google-Fu I can't find
anything on this.
I have a Python app that uses a Tkinter Treeview widget as a table. This works
fine for what I need to use it for, but there are going to end up being a
couple hundred items in a few of the trees.
Is there anyway to make a Treeview searchable, insofar as when the Tree has
focus, the user can just type a few characters and have the first alphabetical
match highlighted (rather than a separate entity in the window to type the
search pattern into)?
Answer: You can define your own recursive method to search in the Treeview widget, and
call
[`selection_set`](http://docs.python.org/2.7/library/ttk.html?highlight=treeview#ttk.Treeview.selection_set)
on the appropiate child if its text starts with the content of the entry:
import Tkinter as tk
import ttk
class App(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text='Search', command=self.search)
self.tree = ttk.Treeview(self)
# ...
def search(self, item=''):
children = self.tree.get_children(item)
for child in children:
text = self.tree.item(child, 'text')
if text.startswith(self.entry.get()):
self.tree.selection_set(child)
return True
else:
res = self.search(child)
if res:
return True
|
Looping through a list read by pickle to find userid
Question: I am having trouble looping through a list read by pickle. The Ultimate aim of
this code was to loop through each Item and return the id number of each item.
## Opening the file, and loading it into a list##
with open('TEMP_ITEMS.txt', 'rb') as openfile:
items = pickle.load(openfile)
My attempt at trying to loop through this and find the id numbers was based on
some old xml scraping techniques, but for some reason the logic doesn't apply
here.
for item in enumerate(items):
pattern0 = re.compile('ID: (.*?) <br>')
idnumber = float(re.findall(pattern0, items[0])[0])
print "ID Number: ",idnumber
Example of the contents of TEMP_ITEMS.txt
(lp0
S'\n <item>\n <title>Timmy</title>\n <link>caturl</link>\n <description><![CDATA[\n Timmy <br>\n ID: 3712 <br>\n Age: 10 <br>\n Weight: 7lbs <br>\n Time: 17:23 <br>\n Cat Name: Timmy <br>\n\n ]]></description>\n <guid isPermaLink="false">04e72b29-065d-4893-a4d2-f16ff30a283e</guid>\n <pubDate>Fri, 21 Jun 2013 01:09:05 GMT</pubDate>\n </item>'
p1
aS'\n <item>\n <title>George</title>\n <link>caturl</link>\n <description><![CDATA[\n George <br>\n ID: 4124 <br>\n Age: 14 <br>\n Weight: 8lbs <br>\n Time: 15:41 <br>\n Cat Name: George <br>\n\n ]]></description>\n <guid isPermaLink="false">212f9fbf-564b-470a-a64a-ef51036ff06a</guid>\n <pubDate>Fri, 21 Jun 2013 01:28:20 GMT</pubDate>\n </item>'
p2
a.
Any help or advice on this problem would be greatly appreciated. Kind regards
AEA
# Code used under recommendations of falsetru, which returns an error
import pickle
import re
with open('TEMP_RSS_ITEMS.txt', 'rb') as temp_rss_items_open4:
items = pickle.load(temp_rss_items_open4)
print items
for item in enumerate(items):
pattern0 = re.compile('ID: (.*) <br>')
for idnumber in re.findall(pattern0, item):
print idnumber
Error this code it producing:
Traceback (most recent call last):
File "C:/Sharing/test1.py", line 9, in <module>
for idnumber in re.findall(pattern0, item):
File "C:\Python27\lib\re.py", line 177, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer
>>>
Answer: Try using a non-greedy version of `.*`:
pattern0 = re.complie(r'ID: (.*?) <br>')
or '+` if ID has only digits:
pattern0 = re.complie(r'ID: (\d+)')
**UPDATE**
import pickle
import re
pattern0 = re.compile('ID: (.*) <br>')
with open('TEMP_RSS_ITEMS.txt', 'rb') as f:
items = pickle.load(f)
for item in items:
for idnumber in pattern0.findall(item):
print idnumber
|
Python: wildcard subset import
Question: We have all been told using `from module import *` is a bad idea. However, is
there a way to import a **subset** of the contents of `module` using a
wildcard?
For example:
module.py:
MODULE_VAR1 = "hello"
MODULE_VAR2 = "world"
MODULE_VAR3 = "The"
MODULE_VAR4 = "quick"
MODULE_VAR5 = "brown"
...
MODULE_VAR10 = "lazy"
MODULE_VAR11 = "dog!"
MODULE_VAR12 = "Now"
MODULE_VAR13 = "is"
...
MODULE_VAR98 = "Thats"
MODULE_VAR99 = "all"
MODULE_VAR100 = "folks!"
def abs():
print "Absolutely useful function: %s" % MODULE_VAR1
Obviously we don't want to use `from module import *` because we'd be
overriding the `abs` function. But suppose we DID want all of the
`MODULE_VAR*` variables to be accessible locally.
Simply putting `from module import MODULE_VAR*` doesn't work. Is there a way
to accomplish this?
I used 100 variables as an illustration, because doing `from module import
MODULE_VAR1, MODULE_VAR2, MODULE_VAR3, ..., MODULE_VAR100` would obviously be
incredibly unwieldy and wouldn't work if more variables (e.g. `MODULE_VAR101`)
were added.
Answer: You can have a helper function for that - and it can be done without magic:
import re
def matching_import(pattern, module, globals):
for key, value in module.__dict__.items():
if re.findall(pattern, key):
globals[key] = value
Now, you can do for example:
from utils import matching_import
import constants
matching_import("MODULE_VAR.*", constants, globals())
Using `globals()` explicitly in this way avoids frame introspection magic,
which is usually considered harmful.
|
Unpickling fails with __new__() takes exactly 1 argument (2 given)
Question: When I'm trying to load a pickled list it says:
>>> import pickle
>>> with open('tests/unit/support/modules_state.samples2.6') as f:
... print(pickle.load(f))
...
Traceback (most recent call last):
File "<console>", line 2, in <module>
File "/usr/lib/python2.6/pickle.py", line 1370, in load
return Unpickler(file).load()
File "/usr/lib/python2.6/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.6/pickle.py", line 1083, in load_newobj
obj = cls.__new__(cls, *args)
TypeError: __new__() takes exactly 1 argument (2 given)
Here's the code that loads/dumps the pickled list:
class FakeModuleNameGenerator(str):
def __new__(cls):
return super(FakeModuleNameGenerator, cls).__new__(cls, binascii.b2a_hex(os.urandom(15)))
class FakeModule(object):
def __new__(cls, *args, **kwargs):
return choice([object(), TestDouble()])
class SamplesIterator(object):
MAX_SAMPLE_LENGTH = os.getenv('MAX_SAMPLE_LENGTH', 12) if is_executing_under_continuous_integration_server() else 6
def __iter__(self):
for sample_length in range(1, SamplesIterator.MAX_SAMPLE_LENGTH):
combinations = [(FakeModuleNameGenerator(), FakeModule()) for i in range(0, sample_length)]
for r in range(1, sample_length + 1):
logger.info("Generating sample in length %d with r=%d" % (sample_length, r))
yield itertools.combinations_with_replacement(combinations, r)
def load_samples():
if is_executing_under_continuous_integration_server() and os.getenv('USE_CACHES_SAMPLES', 'false') != 'true':
list(itertools.chain.from_iterable(SamplesIterator()))
import platform
version = '%s.%s' % (
sys.version_info[0], sys.version_info[1]) if platform.python_implementation() != 'PyPy' else 'pypy'
samples_file = '%s%s' % (get_support_path(), 'modules_state.samples-%s' % version)
if os.path.exists(samples_file) and os.path.getsize(samples_file) == 0 or not os.path.exists(samples_file):
with open(samples_file, 'wb') as f:
samples = list(itertools.chain.from_iterable(SamplesIterator()))
try:
return samples
finally:
pickle.dump(samples, f, pickle.HIGHEST_PROTOCOL)
else:
with open(samples_file, 'rb') as f:
return pickle.load(f)
As you can see I am reading and writing in binary mode.
Here is the complete tox output for the same code before loading the list
(when the code is executed for the first time. After that the list is cached):
/usr/bin/python2.7 /usr/local/bin/tox
GLOB sdist-make: /home/omer/Documents/Projects/Python/nose2-testsuite/setup.py
py26 inst-nodeps: /home/omer/Documents/Projects/Python/nose2-testsuite/.tox/dist/nose2-testsuite-0.1.0.zip
py26 runtests: commands[0]
.................................................................................................................................
----------------------------------------------------------------------
Ran 129 tests in 0.034s
OK
py27 inst-nodeps: /home/omer/Documents/Projects/Python/nose2-testsuite/.tox/dist/nose2-testsuite-0.1.0.zip
py27 runtests: commands[0]
.................................................................................................................................
----------------------------------------------------------------------
Ran 129 tests in 0.029s
OK
py33 inst-nodeps: /home/omer/Documents/Projects/Python/nose2-testsuite/.tox/dist/nose2-testsuite-0.1.0.zip
py33 runtests: commands[0]
.................................................................................................................................
----------------------------------------------------------------------
Ran 129 tests in 0.034s
OK
pypy inst-nodeps: /home/omer/Documents/Projects/Python/nose2-testsuite/.tox/dist/nose2-testsuite-0.1.0.zip
pypy runtests: commands[0]
.................................................................................................................................
----------------------------------------------------------------------
Ran 129 tests in 0.058s
OK
___________________________________ summary ____________________________________
py26: commands succeeded
py27: commands succeeded
py33: commands succeeded
pypy: commands succeeded
congratulations :)
Process finished with exit code 0
We're all happy as everything works just fine right? Now when running tox
again here are the results:
/usr/bin/python2.7 /usr/local/bin/tox
GLOB sdist-make: /home/omer/Documents/Projects/Python/nose2-testsuite/setup.py
py26 inst-nodeps: /home/omer/Documents/Projects/Python/nose2-testsuite/.tox/dist/nose2-testsuite-0.1.0.zip
py26 runtests: commands[0]
EE...........
======================================================================
ERROR: tests.functional.test_isolators (nose2.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.functional.test_isolators
Traceback (most recent call last):
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py26/lib/python2.6/site-packages/nose2/plugins/loader/discovery.py", line 188, in _find_tests_in_file
module = util.module_from_name(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py26/lib/python2.6/site-packages/nose2/util.py", line 78, in module_from_name
__import__(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/functional/test_isolators.py", line 14, in <module>
for current_modules_state in load_samples():
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/common/support/isolators.py", line 63, in load_samples
return pickle.load(f)
File "/usr/lib/python2.6/pickle.py", line 1370, in load
return Unpickler(file).load()
File "/usr/lib/python2.6/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.6/pickle.py", line 1083, in load_newobj
obj = cls.__new__(cls, *args)
TypeError: __new__() takes exactly 1 argument (2 given)
======================================================================
ERROR: tests.unit.test_isolators (nose2.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.unit.test_isolators
Traceback (most recent call last):
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py26/lib/python2.6/site-packages/nose2/plugins/loader/discovery.py", line 188, in _find_tests_in_file
module = util.module_from_name(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py26/lib/python2.6/site-packages/nose2/util.py", line 78, in module_from_name
__import__(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/unit/test_isolators.py", line 48, in <module>
for current_modules_state in load_samples():
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/common/support/isolators.py", line 63, in load_samples
return pickle.load(f)
File "/usr/lib/python2.6/pickle.py", line 1370, in load
return Unpickler(file).load()
File "/usr/lib/python2.6/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.6/pickle.py", line 1083, in load_newobj
obj = cls.__new__(cls, *args)
TypeError: __new__() takes exactly 1 argument (2 given)
----------------------------------------------------------------------
Ran 13 tests in 0.002s
FAILED (errors=2)
ERROR: InvocationError: '/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py26/bin/nose2'
py27 inst-nodeps: /home/omer/Documents/Projects/Python/nose2-testsuite/.tox/dist/nose2-testsuite-0.1.0.zip
py27 runtests: commands[0]
EE...........
======================================================================
ERROR: tests.functional.test_isolators (nose2.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.functional.test_isolators
Traceback (most recent call last):
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py27/local/lib/python2.7/site-packages/nose2/plugins/loader/discovery.py", line 188, in _find_tests_in_file
module = util.module_from_name(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py27/local/lib/python2.7/site-packages/nose2/util.py", line 78, in module_from_name
__import__(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/functional/test_isolators.py", line 14, in <module>
for current_modules_state in load_samples():
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/common/support/isolators.py", line 63, in load_samples
return pickle.load(f)
File "/usr/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1083, in load_newobj
obj = cls.__new__(cls, *args)
TypeError: __new__() takes exactly 1 argument (2 given)
======================================================================
ERROR: tests.unit.test_isolators (nose2.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.unit.test_isolators
Traceback (most recent call last):
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py27/local/lib/python2.7/site-packages/nose2/plugins/loader/discovery.py", line 188, in _find_tests_in_file
module = util.module_from_name(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py27/local/lib/python2.7/site-packages/nose2/util.py", line 78, in module_from_name
__import__(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/unit/test_isolators.py", line 48, in <module>
for current_modules_state in load_samples():
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/common/support/isolators.py", line 63, in load_samples
return pickle.load(f)
File "/usr/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1083, in load_newobj
obj = cls.__new__(cls, *args)
TypeError: __new__() takes exactly 1 argument (2 given)
----------------------------------------------------------------------
Ran 13 tests in 0.002s
FAILED (errors=2)
ERROR: InvocationError: '/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py27/bin/nose2'
py33 inst-nodeps: /home/omer/Documents/Projects/Python/nose2-testsuite/.tox/dist/nose2-testsuite-0.1.0.zip
py33 runtests: commands[0]
EE...........
======================================================================
ERROR: tests.functional.test_isolators (nose2.loader.ModuleImportFailure)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python3.3/unittest/case.py", line 385, in _executeTestPart
function()
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py33/lib/python3.3/site-packages/nose2/loader.py", line 113, in testFailure
raise exception
ImportError: Failed to import test module: tests.functional.test_isolators
Traceback (most recent call last):
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py33/lib/python3.3/site-packages/nose2/plugins/loader/discovery.py", line 188, in _find_tests_in_file
module = util.module_from_name(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py33/lib/python3.3/site-packages/nose2/util.py", line 78, in module_from_name
__import__(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/functional/test_isolators.py", line 14, in <module>
for current_modules_state in load_samples():
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/common/support/isolators.py", line 63, in load_samples
return pickle.load(f)
TypeError: __new__() takes 1 positional argument but 2 were given
======================================================================
ERROR: tests.unit.test_isolators (nose2.loader.ModuleImportFailure)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python3.3/unittest/case.py", line 385, in _executeTestPart
function()
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py33/lib/python3.3/site-packages/nose2/loader.py", line 113, in testFailure
raise exception
ImportError: Failed to import test module: tests.unit.test_isolators
Traceback (most recent call last):
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py33/lib/python3.3/site-packages/nose2/plugins/loader/discovery.py", line 188, in _find_tests_in_file
module = util.module_from_name(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py33/lib/python3.3/site-packages/nose2/util.py", line 78, in module_from_name
__import__(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/unit/test_isolators.py", line 48, in <module>
for current_modules_state in load_samples():
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/common/support/isolators.py", line 63, in load_samples
return pickle.load(f)
TypeError: __new__() takes 1 positional argument but 2 were given
----------------------------------------------------------------------
Ran 13 tests in 0.002s
FAILED (errors=2)
ERROR: InvocationError: '/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/py33/bin/nose2'
pypy inst-nodeps: /home/omer/Documents/Projects/Python/nose2-testsuite/.tox/dist/nose2-testsuite-0.1.0.zip
pypy runtests: commands[0]
EE...........
======================================================================
ERROR: tests.functional.test_isolators (nose2.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.functional.test_isolators
Traceback (most recent call last):
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/pypy/site-packages/nose2/plugins/loader/discovery.py", line 188, in _find_tests_in_file
module = util.module_from_name(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/pypy/site-packages/nose2/util.py", line 78, in module_from_name
__import__(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/functional/test_isolators.py", line 14, in <module>
ERROR: InvocationError: '/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/pypy/bin/nose2'
for current_modules_state in load_samples():
___________________________________ summary ____________________________________
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/common/support/isolators.py", line 63, in load_samples
ERROR: py26: commands failed
return pickle.load(f)
ERROR: py27: commands failed
File "/usr/lib/pypy/lib-python/2.7/pickle.py", line 1421, in load
ERROR: py33: commands failed
return Unpickler(file).load()
ERROR: pypy: commands failed
File "/usr/lib/pypy/lib-python/2.7/pickle.py", line 901, in load
dispatch[key](self)
File "/usr/lib/pypy/lib-python/2.7/pickle.py", line 1126, in load_newobj
obj = cls.__new__(cls, *args)
TypeError: __new__() takes exactly 1 argument (2 given)
======================================================================
ERROR: tests.unit.test_isolators (nose2.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.unit.test_isolators
Traceback (most recent call last):
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/pypy/site-packages/nose2/plugins/loader/discovery.py", line 188, in _find_tests_in_file
module = util.module_from_name(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/.tox/pypy/site-packages/nose2/util.py", line 78, in module_from_name
__import__(name)
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/unit/test_isolators.py", line 48, in <module>
for current_modules_state in load_samples():
File "/home/omer/Documents/Projects/Python/nose2-testsuite/tests/common/support/isolators.py", line 63, in load_samples
return pickle.load(f)
File "/usr/lib/pypy/lib-python/2.7/pickle.py", line 1421, in load
return Unpickler(file).load()
File "/usr/lib/pypy/lib-python/2.7/pickle.py", line 901, in load
dispatch[key](self)
File "/usr/lib/pypy/lib-python/2.7/pickle.py", line 1126, in load_newobj
obj = cls.__new__(cls, *args)
TypeError: __new__() takes exactly 1 argument (2 given)
----------------------------------------------------------------------
Ran 13 tests in 0.004s
FAILED (errors=2)
Process finished with exit code 1
Answer: I found it!
The problem was here:
class FakeModuleNameGenerator(str):
@classmethod
def __new__(cls, *args, **kwargs):
return str(binascii.b2a_hex(os.urandom(15)))
Since this inherits from str, `__new__` has to accept another argument. Doh!
|
How to mention height and Width in terms of percentage in size() in wxpython
Question: How do I mention `size(350,450)` in terms of percentages in `wxpython`?
# -*- coding: utf-8 -*-
# gotoclass.py
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title,
size=(390, 350))
self.InitUI()
self.Centre()
self.Show()
def InitUI(self):
panel = wx.Panel(self)
font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
font.SetPointSize(9)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
st1 = wx.StaticText(panel, label='Class Name')
st1.SetFont(font)
hbox1.Add(st1, flag=wx.RIGHT, border=8)
tc = wx.TextCtrl(panel)
hbox1.Add(tc, proportion=1)
vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
vbox.Add((-1, 10))
panel.SetSizer(vbox)
if __name__ == '__main__':
app = wx.App()
Example(None, title='Go To Class')
app.MainLoop()
Answer: Get the screen resolution using `wx.GetDisplaySize()`. Compute the percentage
in pixels. Set the size by `self.SetSize()` later, not in the constructor but
before `self.Show()`.
|
Speeding up summation for loop in python
Question: I have the following bottleneck and am wondering if anyone can suggest ways to
speed it up.
I have three lists `x,y,z` of length `N`. and I apply the following
[summation](http://en.wikipedia.org/wiki/Correlation_sum).
def abs_val_diff(x1, x2, x3, y1, y2, y3):
""" Find the absolute value of the difference between x and y """
return py.sqrt((x1 - y1) ** 2.0 + (x2 - y2) ** 2.0 + (x3 - y3) ** 2.0)
R = 0.1
sumV = 0.0
for i in xrange(N):
for j in xrange(i + 1, N):
if R > abs_val_diff(x[i], y[i], z[i],
x[j], y[j], z[j]):
sumV += 1.0
I have tried using numpy arrays, but either I am doing something wrong or
there is a reduction in speed of about a factor of 2.
Any ideas would be highly appreciated.
Answer: I believe you can utilize numpy a little more efficiently by doing something
like the following. Make a small modification to your function to use the
numpy.sqrt:
import numpy as np
def abs_val_diff(x1, x2, x3, y1, y2, y3):
""" Find the absolute value of the difference between x and y """
return np.sqrt((x1 - y1) ** 2.0 + (x2 - y2) ** 2.0 + (x3 - y3) ** 2.0)
Then call with the full arrays:
res = abs_val_diff(x[:-1],y[:-1],z[:-1],x[1:],y[1:],z[1:])
Then, because you're adding 1 for each match, you can simply take the length
of the array resulting from a query against the result:
sumV = len(res[R>res])
This lets numpy handle the iteration. Hopefully that works for you
|
How to insert a HTML element in a tree of lxml.html
Question: _I am using python 3.3 and lxml 3.2.0_
Problem: I have a web page in a variable `webpageString =
"<html><head></head><body>webpage content</body></html>"` And I want to insert
a css link tag between the two header tags, so that I get `webpageString =
"<html><head><link rel='stylesheet' type='text/css'></head><body>webpage
content</body></html>"`
I have written the following code:
def addCssCode(self):
tree = html.fromstring(self.article)
headTag = tree.xpath("//head")
#htmlTag = tree.getroot()
if headTag is None:
pass #insert the head tag first
cssLinkString = "<link rel='stylesheet' type='text/css' href='"+ self.cssLocation+"'>"
headTag[0].insert(1, html.HtmlElement(cssLinkString))
print(cssLinkString)
self.article = html.tostring(tree).decode("utf-8")
Which results in insertion of-
<HtmlElement>< link rel='stylesheet' type='text/css' href='cssCode.css' ></HtmlElement>
I also tried solution in the following page to an identical problem, but it
also didn't work. [python lxml append element after another
element](http://stackoverflow.com/questions/7474972/python-lxml-append-
element-after-another-element)
How can I solve this? Thanks
Answer: Use `.insert`/`.append` method.
import lxml.html
def add_css_code(webpageString, linkString):
root = lxml.html.fromstring(webpageString)
link = lxml.html.fromstring(linkString).find('.//link')
head = root.find('.//head')
title = head.find('title')
if title == None:
where = 0
else:
where = head.index(title) + 1
head.insert(where, link)
return lxml.html.tostring(root)
webpageString1 = "<html><head><title>test</title></head><body>webpage content</body></html>"
webpageString2 = "<html><head></head><body>webpage content</body></html>"
linkString = "<link rel='stylesheet' type='text/css'>"
print(add_css_code(webpageString1, linkString))
print(add_css_code(webpageString2, linkString))
|
Find bottleneck of flask application
Question: I wrote a flask application. I found it very slow when I deployed it in a
remote server. So, I did some profiling practices with it. Please take a look
at the pictures below:
The code I use to profiling is:
#coding: utf-8
from werkzeug.contrib.profiler import ProfilerMiddleware
from app import app
app.config['PROFILE'] = True
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions = [30])
app.run(debug = True)
### Picture 1
profiling in the **remote server**. Maybe the bottleneck is
`_socket.getaddrinfo`

### Picture 2
profiling in the local machine. Nothing found bottleneck.

### Picture 3
Sometimes, even in the remote server, there are no bottleneck found. No
`_socket.getaddrinfo` found. Weird! 
I did profiling in remote server python shell, too, with `cProfile`. Take a
look at this:
In [10]: cProfile.run("socket.getaddrinfo('easylib.gdufslib.org', 80, 0, 0, socket.SOL_TCP)")
3 function calls in 8.014 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 8.014 8.014 :1()
1 8.014 8.014 8.014 8.014 {_socket.getaddrinfo}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
In [11]: cProfile.run("socket.getaddrinfo('easylib.gdufslib.org', 80, 0, 0, socket.SOL_TCP)")
3 function calls in 8.009 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 8.009 8.009 :1()
1 8.009 8.009 8.009 8.009 {_socket.getaddrinfo}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Maybe there is a fact that it takes much time to do some `dns resolve` job,
and I can't change this myself.
Can any one tell me: why `_socket.getaddrinfo` is called and why sometimes not
called? How to prevent the `_socket.getaddrinfo` being called? Because it slow
down my website which let me down saddly.
Answer: I just ran into this myself on a Flask app running on a dedicated box from
Digital Ocean, so I'll post the solution in case someone else hits this in the
future.
I noticed a few days ago that API requests to GitHub were _insanely_ slow,
sometimes taking between 10 and 20 seconds. But running my app locally didn't
have any issues. I profiled my app, and `socket.getaddrinfo` was indeed the
culprit:
1 15058.431 15058.4310 15058.431 15058.4310 {_socket.getaddrinfo}
1 26.545 26.5450 26.545 26.5450 {_ssl.sslwrap}
1 23.246 23.2460 23.246 23.2460 {built-in method do_handshake}
4 22.387 5.5968 22.387 5.5968 {built-in method read}
1 7.632 7.6320 7.632 7.6320 {method 'connect' of '_socket.socket' objects}
103 4.995 0.0485 7.131 0.0692 <s/werkzeug/urls.py:374(url_quote)>
2 2.459 1.2295 2.578 1.2890 <ssl.py:294(close)>
36 1.495 0.0415 10.548 0.2930 <s/werkzeug/routing.py:707(build)>
859 1.442 0.0017 1.693 0.0020 {isinstance}
.... etc.
Working with Digital Ocean support, and suspecting it was somehow a DNS issue,
the working solution was to change (in `/etc/resolv.conf`)
nameserver 4.2.2.2
nameserver 8.8.8.8
to
nameserver 8.8.4.4
nameserver 8.8.8.8
For whatever reason, `4.2.2.2` (run by Level3) decided it hated me but for the
time being me and Google's DNS are cool.
Update: My colleague Karl suggested I go ahead and set up a local DNS caching
server with bind to prevent Google's DNS from hating me as well. [This link
was super helpful.](https://www.digitalocean.com/community/tutorials/how-to-
configure-bind-as-a-caching-or-forwarding-dns-server-on-ubuntu-14-04)
|
Merge 2 lists at every x position
Question: Say I have two lists one longer than the other, `x = [1,2,3,4,5,6,7,8]` and `y
= [a,b,c]` and I want to merge each element in y to every 3rd index in x so
the resulting list z would look like: `z = [1,2,a,3,4,b,5,6,c,7,8]`
What would be the best way of going about this in python?
Answer: Here is an adapted version of the roundrobin recipe from the [itertools
documentation](http://docs.python.org/2/library/itertools.html#recipes) that
should do what you want:
from itertools import cycle, islice
def merge(a, b, pos):
"merge('ABCDEF', [1,2,3], 3) --> A B 1 C D 2 E F 3"
iterables = [iter(a)]*(pos-1) + [iter(b)]
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
Example:
>>> list(merge(xrange(1, 9), 'abc', 3)) # note that this works for any iterable!
[1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8]
Or here is how you could use `roundrobin()` as it is without any
modifications:
>>> x = [1,2,3,4,5,6,7,8]
>>> y = ['a','b','c']
>>> list(roundrobin(*([iter(x)]*2 + [y])))
[1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8]
Or an equivalent but slightly more readable version:
>>> xiter = iter(x)
>>> list(roundrobin(xiter, xiter, y))
[1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8]
Note that both of these methods work with any iterable, not just sequences.
Here is the original `roundrobin()` implementation:
from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
|
How can one Python module break another?
Question: After several hours of debugging and trial and error, I found that importing
two independent Python modules caused a function in one of them to stop
working.
import arcpy
# works
sde_conn = arcpy.ArcSDESQLExecute(r"C:\temp\test.sde")
Yet:
import arcpy
import rtree
# fails
sde_conn = arcpy.ArcSDESQLExecute(r"C:\temp\test.sde")
The two Python modules are [rtree](https://github.com/Toblerity/rtree) and
ESRI's
[arcpy](http://resources.arcgis.com/en/help/main/10.1/index.html#//000v00000001000000),
both of which I have running on Windows (the issue occurs on both Windows 7
and Windows Server 2008 R2, and on 32 bit and 64 bit Python installations).
I [logged the issue](http://github.com/Toblerity/rtree/issues/10), but I'd
like to know what are the possible causes of one module breaking a function in
another?
I had a quick check for globals, and modifying the system path. Both also rely
on DLLs.
What other factors could be responsible?
Answer: It happens when using:
from (module) import *
if both modules have functions with the same names. Shamelessly taken from
@karthikr
|
Getting mentions and DMs through twitter stream API 1.1? (Using twython)
Question: I'm using twython (twitter API library for python) to connect to the streaming
API, but I seem to only get the public twitter stream possibly filtered by
words. Isn't there a way to get a real-time stream of the authenticated user
timeline or @mentions?
I've been looping through delayed calls to the REST API to get those mentions
but twitter doesn't like me to make so many requests.
Twython documentation isn't helping me much about it, neither is the official
twitter doc.
If there's another python library that can work better than twython for
streaming (for Twitter API v1.1). I'd appreciate the suggestion... Thanks.
Answer: In the beginning of my research I thought [python-
twitter](https://github.com/bear/python-twitter) is _the_ twitter library for
Python. But finally, it seems as if the **[Python Twitter
Tools](https://github.com/sixohsix/twitter)** are more popular and support
also twitter streaming.
It's a bit tricky, the streaming API and the REST api are not equal for direct
messages. This small **example script** demonstrates how you can use the user
stream to get direct messages:
import twitter # if this module does not
# contain OAuth or stream,
# check if sixohsix' twitter
# module is used!
auth = twitter.OAuth(
consumer_key='...',
consumer_secret='...',
token='...',
token_secret='...'
)
stream = twitter.stream.TwitterStream(auth=auth, domain='userstream.twitter.com')
for msg in stream.user():
if 'direct_message' in msg:
print msg['direct_message']['text']
This script will print all new messages - not the ones already received before
starting the script.
|
Installing anaconda to use with windows
Question: I am lost in the installation process of installing anaconda on windows.
I've installed the windows 32bit package (I'm running windows 7 x64)
I have anaconda in the start menu and I can open the python console and use
scipy.stats.t.interval(), the function I am interested in.
However, how do I go about including this in another python program? I think
it's something like adding it to the path. For instance, I have the
scipy.stats.t.interval() function call in my other python file which I run
through cygwin via `python myscript.py`. However it returns the error:
from scipy.stats import t
ImportError: No module named scipy.stats
I think it might be a change of path / add to path issue, but I'm not sure how
to fix it :/. While I try to fix it, I figure I will post for help here.
Answer: well you might have two installations of python, one inside the anaconda
package, and other which you might have installed earlier. try doing :
which python
from CygWin console. If it returns:
/usr/bin
then it is definitely a add-to-path problem. to fix it for CygWin, you have to
add the python installation from anaconda to the path.
try this fromn CygWin:
PATH=path-where-anaconda-is-installed/anaconda/bin:$PATH
and then doing:
which python
should give you:
/path-to-anaconda/anaconda/bin
and then it will work.
Cheers
|
Measuring curvature of contiguous points
Question: I have a list of points (in the order of magnitude of tens of thousands), and
I need to identify two things using python:
1- the groups of contiguous points (abs(x2-x1)<=1 and abs(y2-y1)<=1) among
these points
2- the degree/radius of curvaure of each group
Here is a sample set of points:
> [[331, 400], [331, 1200], [332, 400], [332, 486], [332, 522], [332, 655],
> [332, 1200], [332, 3800], [332, 3877], [332, 3944], [332, 3963], [332,
> 3992], [332, 4050], [333, 400], [333, 486], [333, 522], [333, 560], [333,
> 588], [333, 655], [333, 700], [333, 1200], [333, 3800], [333, 3877], [333,
> 3944], [333, 3963], [333, 3992], [333, 4050], [334, 400], [334, 486], [334,
> 522], [334, 558], [334, 586], [334, 654], [334, 697], [334, 1200], [334,
> 3800], [334, 3877], [334, 3944], [334, 3963], [334, 3992], [334, 4050],
> [335, 400], [335, 486], [335, 521], [335, 556], [335, 585], [335, 653],
> [335, 695], [335, 1200], [335, 3800], [335, 3877], [335, 3944], [335, 3963],
> [335, 3992], [335, 4050], [336, 400], [336, 486], [336, 520], [336, 555],
> [336, 584], [336, 651], [336, 693], [336, 1200], [336, 3800], [336, 3877],
> [336, 3944], [336, 3963], [336, 3992], [336, 4050], [337, 400], [337, 486],
> [337, 554], [337, 583], [337, 649], [337, 692], [337, 1200], [337, 3800],
> [337, 3877], [337, 3944], [337, 3963], [337, 3992], [337, 4050], [338, 377],
> [338, 400], [338, 486], [338, 553], [338, 582], [338, 647], [338, 691],
> [338, 1200], [338, 3800], [338, 3877], [338, 3944], [338, 3963], [338,
> 3992], [338, 4050], [339, 377], [339, 400], [339, 486], [339, 553], [339,
> 581], [339, 585], [339, 644], [339, 654], [339, 690], [339, 706], [339,
> 1200], [339, 3800], [339, 3877], [339, 3944], [339, 3963], [339, 3992],
> [339, 4050], [340, 376], [340, 400], [340, 486], [340, 552], [340, 580],
> [340, 585], [340, 641], [340, 655], [340, 689], [340, 713], [340, 1200],
> [340, 3800], [340, 3877], [340, 3944], [340, 3963], [340, 3992], [340,
> 4050], [341, 376], [341, 400], [341, 486], [341, 552], [341, 579], [341,
> 585], [341, 639], [341, 655], [341, 688], [341, 715], [341, 1200], [341,
> 3800], [341, 3877], [341, 3944], [341, 3963], [341, 3992], [341, 4050],
> [342, 375], [342, 400], [342, 486], [342, 552], [342, 578], [342, 585],
> [342, 637], [342, 655], [342, 688], [342, 717], [342, 1200], [342, 3800],
> [342, 3858], [342, 3925], [342, 3954], [342, 4011], [342, 4050], [342,
> 4107], [343, 374], [343, 400], [343, 486], [343, 521], [343, 552], [343,
> 577], [343, 585], [343, 635], [343, 642], [343, 687], [343, 718], [343,
> 1200], [343, 3800], [343, 3858], [343, 3925], [343, 3954], [343, 4011],
> [343, 4050], [343, 4107], [344, 373], [344, 400], [344, 486], [344, 521],
> [344, 552], [344, 576], [344, 585], [344, 633], [344, 642], [344, 687],
> [344, 719], [344, 1200], [344, 3800], [344, 3858], [344, 3925], [344, 3954],
> [344, 4011], [344, 4050], [344, 4107], [345, 372], [345, 400], [345, 486],
> [345, 521], [345, 552], [345, 575], [345, 585], [345, 630], [345, 642],
> [345, 687], [345, 720], [345, 1200], [345, 3800], [345, 3858], [345, 3925],
> [345, 3954], [345, 4011], [345, 4050], [345, 4107], [346, 370], [346, 400],
> [346, 486], [346, 521], [346, 552], [346, 574], [346, 585], [346, 628],
> [346, 642], [346, 686], [346, 721], [346, 1200], [346, 3800], [346, 3858],
> [346, 3925], [346, 3954], [346, 4011], [346, 4050], [346, 4107], [347, 368],
> [347, 400], [347, 486], [347, 521], [347, 552], [347, 572], [347, 585],
> [347, 626], [347, 642], [347, 686], [347, 721], [347, 1200], [347, 3800],
> [347, 3858], [347, 3925], [347, 3954], [347, 4011], [347, 4050], [347,
> 4107], [348, 366], [348, 400], [348, 487], [348, 521], [348, 552], [348,
> 570], [348, 585], [348, 624], [348, 642], [348, 686], [348, 721], [348,
> 1200], [348, 3800], [348, 3858], [348, 3925], [348, 3954], [348, 4011],
> [348, 4050], [348, 4107], [349, 364], [349, 400], [349, 487], [349, 521],
> [349, 553], [349, 568], [349, 585], [349, 622], [349, 642], [349, 686],
> [349, 722], [349, 1200], [349, 3800], [349, 3858], [349, 3925], [349, 3954],
> [349, 4011], [349, 4050], [349, 4107], [350, 362], [350, 400], [350, 487],
> [350, 521], [350, 553], [350, 585], [350, 619], [350, 642], [350, 686],
> [350, 722], [350, 1200], [350, 3800], [350, 3858], [350, 3925], [350, 3954],
> [350, 4011], [350, 4050], [350, 4107], [351, 357], [351, 400], [351, 487],
> [351, 521], [351, 554], [351, 585], [351, 619], [351, 642], [351, 686],
> [351, 722], [351, 1200], [351, 3800], [351, 3819], [351, 3858], [351, 3877],
> [351, 3915], [351, 3934], [351, 3963], [351, 3992], [351, 4050], [351,
> 4069], [351, 4107], [352, 355], [352, 373], [352, 400], [352, 487], [352,
> 520], [352, 555], [352, 585], [352, 621], [352, 642], [352, 686], [352,
> 722], [352, 1200], [352, 3800], [352, 3819], [352, 3858], [352, 3877], [352,
> 3915], [352, 3934], [352, 3963], [352, 3992], [352, 4050], [352, 4069],
> [352, 4107], [353, 353], [353, 375], [353, 400], [353, 487], [353, 520],
> [353, 556], [353, 585], [353, 623], [353, 642], [353, 686], [353, 722],
> [353, 1200], [353, 3800], [353, 3819], [353, 3858], [353, 3877], [353,
> 3915], [353, 3934], [353, 3963], [353, 3992], [353, 4050], [353, 4069],
> [353, 4107], [354, 351], [354, 376], [354, 400], [354, 487], [354, 520],
> [354, 558], [354, 584], [354, 625], [354, 642], [354, 686], [354, 721],
> [354, 1200], [354, 3800], [354, 3819], [354, 3858], [354, 3877]]
Answer: This will give you the clusters and a [list of
angles](http://stackoverflow.com/a/13226141/390913):
from sklearn.cluster import DBSCAN
from scipy.spatial import distance
from scipy.optimize import curve_fit
import numpy as np, math
data = [[331, 400], [331, 1200], [332, 400], [332, 486], [332, 522]] #....
def angle(pt1, pt2):
x1, y1 = pt1
x2, y2 = pt2
inner_product = x1*x2 + y1*y2
len1 = math.hypot(x1, y1)
len2 = math.hypot(x2, y2)
return math.acos(inner_product/(len1*len2))
db=DBSCAN(eps=1,min_samples=2,metric='precomputed').fit(
distance.squareform(distance.pdist(data)))
core_samples = db.core_sample_indices_
labels = db.labels_
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
unique_labels = set(labels)
for k in unique_labels:
class_members = [index[0] for index in np.argwhere(labels == k)]
cluster_core_samples = [index for index in core_samples
if labels[index] == k]
curve = np.array([data[index] for index in class_members])
print k, curve, [angle(p1,p2) for p1,p2 in zip(curve,curve[1:])]
|
Python: Serving files, All carriage returns lost in text file
Question: I'm using the method described in the link
<http://stackoverflow.com/a/8601118/2497977>
import os
import mimetypes
from django.core.servers.basehttp import FileWrapper
def download_file(request):
the_file = '/some/file/name.png'
filename = os.path.basename(the_file)
response = HttpResponse(FileWrapper(open(the_file)),
content_type=mimetypes.guess_type(the_file)[0])
response['Content-Length'] = os.path.getsize(the_file)
response['Content-Disposition'] = "attachment; filename=%s" % filename
return response
Initially get data in a form, when submitted, i process the data to generate a
"config" and write it out to a file. then when valid, pass the file back to
the user as a download. It works great except I'm running into the problem
that in my situation the file is text, so when the file is downloaded, its
coming as a blob of text without CR/LF.
Any suggestions on how to address this?
Answer: Open with binary mode.
open(the_file, 'rb')
<http://docs.python.org/2/library/functions.html#open>
> The default is to use text mode, which may convert '\n' characters to a
> platform-specific representation on writing and back on reading. Thus, when
> opening a binary file, you should append 'b' to the mode value to open the
> file in binary mode, which will improve portability. (Appending 'b' is
> useful even on systems that don’t treat binary and text files differently,
> where it serves as documentation.)
|
python client reading json list from python server
Question: I know there are many json tutorials and Q&A here and on the net, which I've
read; but I'm still struggling to get my python script working.
I'm calling a python server program from a client to read a sample list. My
error is:
<type 'exceptions.ValueError'>: No JSON object could be decoded
args = ('No JSON object could be decoded',)
message = 'No JSON object could be decoded'
Somewhere in the server I've got the wrong code, which is not taking the list
and sending it as a json string.
I'm running everything on a Mongoose webserver.
Server (psptest5.py):
#!C:\Mongoose\Python26\python.exe
import cgi
import cgitb
cgitb.enable()
import pyodbc
import json
import urllib2
import requests
url = "http://localhost:8080/"
value= {'customer' : 'Varun Inc','email' : '[email protected]'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(value), headers=headers)
Client(jsonreadtest.py):
#!C:\Mongoose\Python26\python.exe
import cgi
import cgitb
cgitb.enable()
import json
import urllib2
from pprint import pprint
import csv, sys
url = 'http://localhost:8080/psptest5.py'
data = json.load(urllib2.urlopen(url))
print data
Any help appreciated
Answer: Your server doesn't seem to be actually _returning_ anything, so when your
client runs `data = json.load(urllib2.urlopen(url))` it's trying to load JSON
from an empty string.
|
Python - organising code and test suite
Question: I am very new to python, coming from a php background and cant figure out the
best way to organise my code.
Currently I am working through the project euler exercises to learn python. I
would like to have a directory for my solution to the problem and a directory
that mirrors this for tests.
So ideally:
Problem
App
main.py
Tests
maintTest.py
Using php this is very easy as i can just require_once the correct file, or
amend the `include_path`.
How can this be achieved in python? Obviously this is a very simplistic
example - therefore some advice on how this is approached on a larger scale
would also be extremely grateful.
Answer: This depends on which test runner you want to use.
**pytest**
I recently learned to like [pytest](http://pytest.org/latest/getting-
started.html#our-first-test-run).
It has a section about [how to organize the
code](http://pytest.org/latest/goodpractises.html#choosing-a-test-layout-
import-rules).
If you can not import your main into the code then you can use the tricks
below.
**unittest**
When I use `unittest` I do it like this:
**with import main**
Problem
App
main.py
Tests
test_main.py
`test_main.py`
import sys
import os
import unittest
sys.path.append(os.path.join(os.path.dirname(__file__), 'App'))
import main
# do the tests
if __name__ == '__main__':
unittest.run()
**or with import App.main**
Problem
App
__init__.py
main.py
Tests
test.py
test_main.py
`test.py`
import sys
import os
import unittest
sys.path.append(os.path.dirname(__file__))
`test_main.py`
from test import *
import App.main
# do the tests
if __name__ == '__main__':
unittest.run()
|
How to parse XML file from European Central Bank with Python
Question: I am trying to parse an XML file from the European Central Bank with the Euro
rates. Unfortunatly I get stuck with parsing the XML file. When I remove the
difficult part (everything related with "gesmes") I have no problem iterating
through the "Cube" elements but I am not able to deal with the "gesmes" part
of the xml file. I used the ElementTree API for this.
Sample XML file: <http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml>
<?xml version="1.0" encoding="UTF-8"?>
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time='2013-06-21'>
<Cube currency='USD' rate='1.3180'/>
<Cube currency='JPY' rate='128.66'/>
<Cube currency='BGN' rate='1.9558'/>
<Cube currency='CZK' rate='25.825'/>
<Cube currency='DKK' rate='7.4582'/>
<Cube currency='GBP' rate='0.85330'/>
<Cube currency='HUF' rate='298.87'/>
<Cube currency='LTL' rate='3.4528'/>
<Cube currency='LVL' rate='0.7016'/>
<Cube currency='PLN' rate='4.3289'/>
<Cube currency='RON' rate='4.5350'/>
<Cube currency='SEK' rate='8.6927'/>
<Cube currency='CHF' rate='1.2257'/>
<Cube currency='NOK' rate='7.9090'/>
<Cube currency='HRK' rate='7.4905'/>
<Cube currency='RUB' rate='43.2260'/>
<Cube currency='TRY' rate='2.5515'/>
<Cube currency='AUD' rate='1.4296'/>
<Cube currency='BRL' rate='2.9737'/>
<Cube currency='CAD' rate='1.3705'/>
<Cube currency='CNY' rate='8.0832'/>
<Cube currency='HKD' rate='10.2239'/>
<Cube currency='IDR' rate='13088.24'/>
<Cube currency='ILS' rate='4.7891'/>
<Cube currency='INR' rate='78.1200'/>
<Cube currency='KRW' rate='1521.52'/>
<Cube currency='MXN' rate='17.5558'/>
<Cube currency='MYR' rate='4.2222'/>
<Cube currency='NZD' rate='1.7004'/>
<Cube currency='PHP' rate='57.707'/>
<Cube currency='SGD' rate='1.6790'/>
<Cube currency='THB' rate='41.003'/>
<Cube currency='ZAR' rate='13.4906'/>
</Cube>
</Cube>
</gesmes:Envelope>
What I want is to search for a specific currency (from users input) and get
the rate back so I can use the result.
Answer: You have a namespaced XML file. ElementTree is not too smart about namespaces.
You need to give the `.find()`, `findall()` and `iterfind()` methods an
explicit namespace dictionary. This is not documented very well:
namespaces = {'ex': 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref'} # add more as needed
for cube in root.findall('.//ex:Cube[@currency]', namespaces=namespaces):
print(cube.attrib['currency'], cube.attrib['rate'])
This uses a simple XPath query; './/' means find any child tag, `ex:Cube`
limits the search to the `<Cube>` tags in the namespace labeled with the `ex`
prefix (from the `namespaces` mapping) and `[@currency]` limits the search to
elements that have a `currency` attribute.
Demo:
>>> import requests
>>> r = requests.get('http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml', stream=True)
>>> from xml.etree import ElementTree as ET
>>> tree = ET.parse(r.raw)
>>> root = tree.getroot()
>>> namespaces = {'ex': 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref'}
>>> for cube in root.findall('.//ex:Cube[@currency]', namespaces=namespaces):
... print(cube.attrib['currency'], cube.attrib['rate'])
...
USD 1.3180
JPY 128.66
BGN 1.9558
CZK 25.825
DKK 7.4582
GBP 0.85330
HUF 298.87
LTL 3.4528
LVL 0.7016
PLN 4.3289
RON 4.5350
SEK 8.6927
CHF 1.2257
NOK 7.9090
HRK 7.4905
RUB 43.2260
TRY 2.5515
AUD 1.4296
BRL 2.9737
CAD 1.3705
CNY 8.0832
HKD 10.2239
IDR 13088.24
ILS 4.7891
INR 78.1200
KRW 1521.52
MXN 17.5558
MYR 4.2222
NZD 1.7004
PHP 57.707
SGD 1.6790
THB 41.003
ZAR 13.4906
You can use this information to search for the specific rate too; either build
a dictionary, or search the XML document directly for matching currencies:
currency = input('What currency are you looking for? ')
match = root.find('.//ex:Cube[@currency="{}"]'.format(currency.upper()), namespaces=namespaces)
if match is not None:
print('The rate for {} is {}'.format(currency, match.attrib['rate']))
|
Getting a memory error when parsing a large XML file in Python
Question: My XML file looks like this:
<root>
<group from="1", to="100">
<link target="1"/>
...
<link target="100"/>
</group>
...
</root>
I have a 6000 `<group>` elements and 5M `<link>` elements. I want to have a
dictionary with the tuple (`from`, `to`) as keys and a list of `<link>`s'
`target` attributes, but I get a memory error with following code:
from lxml import etree
from gzip import open as gopen
def extractTargets(fin):
targets = dict()
with gopen(fin) as xml:
context = etree.iterparse(xml, tag="group")
for event, elem in context:
targets[(elem.get("from"), elem.get("to"))] = elem.xpath("link/@target")
elem.clear()
while elem.getprevious() is not None:
del elem.getparent()[0]
del context
Answer: Try following code:
## lxml.etree
import lxml.etree
from gzip import open as gopen
class GroupDictTarget(object):
def __init__(self, d):
self.d = d
def start(self, tag, attrib):
if tag == 'group':
self.group = self.d[attrib['from'], attrib['to']] = []
elif tag == 'link':
self.group.append(attrib['target'])
def close(self):
pass
def extractTargets(fin):
with gopen(fin) as xml:
targets = {}
parser = lxml.etree.XMLParser(target=GroupDictTarget(targets))
lxml.etree.parse(xml, parser)
return targets
## xml.parsers.expat
import xml.parsers.expat
from gzip import open as gopen
class GroupDictTarget(object):
# Same as above
def extractTargets(fin):
targets = {}
p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = GroupDictTarget(targets).start
with gopen(fin) as f:
p.ParseFile(f)
return targets
## xml.sax
import xml.sax
from gzip import open as gopen
class GroupDictTarget(object):
# Same as above
def extractTargets(fin):
targets = {}
handler = xml.sax.handler.ContentHandler()
handler.startElement = GroupDictTarget(targets).start
with gopen(fin) as f:
xml.sax.parse(f, handler)
return targets
|
Expand a relative path but not follow any symlink in the path in Python
Question: This is a subtle question, I know, but I hope you can bear with me for a
moment.
Suppose `/tmp/dir` is a symlink to `/home/user/some/dir`. Suppose also that
your current working directory is `/tmp/dir`.
Even expanding something like `.` does not seem to be possible, as
`os.getcwd()` returns `/home/user/some/dir` instead of `/tmp/dir`, which is
what `pwd` command returns. Relative dir can also be `../dir/../dir/subdir`,
`.././././dir/foo`, etc.
So my question: Is there any reliable function that does path expansion of a
relative path but does not follow the symlink that may exist in the relative
path. In case of `../dir/../dir/subdir`, for example, I would like to get
`/tmp/dir/subdir` and NOT `/home/user/some/dir/subdir`.
Just to avoid getting something I do not want, the answer is NOT
`os.path.abspath`, `os.path.realpath`, `os.path.expanduser`, or
`os.path.relpath`.
Answer: Seems as if [you're not the
first](http://stackoverflow.com/questions/8390502/how-to-make-gnu-make-stop-
de-referencing-symbolic-links-to-directories) to notice this odd behavior of
[`chdir(2)`](http://linux.die.net/man/2/chdir).
There's nothing about it in the Linux manpage, but [a similar
page](http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/apis/chdir.htm)
says...
> `int chdir(const char *path);`
>
> [...]
>
> The **chdir()** function makes the directory named by _path_ the new current
> directory. If the last component of _path_ is a symbolic link, **chdir()**
> resolves the contents of the symbolic link. If the **chdir()** function
> fails, the current directory is unchanged.
...although with no explanation as to why it resolves the symbolic link.
So, you can't technically have a current working directory of `/tmp/dir`, even
if your shell claims otherwise.
However, you can exploit the fact that the shell's built-in `cd` command sets
the environment variable `PWD` to the value you entered, so you can do this...
$ cd /tmp/dir
$ python
>>> import os
>>> os.getcwd()
'/home/user/some/dir'
>>> os.environ['PWD']
'/tmp/dir'
>>> os.path.normpath(os.path.join(os.environ['PWD'], '../dir/../dir/subdir'))
'/tmp/dir/subdir'
...although it may fail in cases when the process wasn't started from a shell.
|
Matplotlib, adding text with more than one line. Adding text that can follow the curve
Question: I have added text to a plot, coded in each line, and then adjusted it look
decent, increase or decrease the width, or change the placement. However, is
there a way to have Python know where you want the text and how you want it
set? Then I could add the text and Python would work out the details.
For example, take a look at the image below:

In the figure, I have 3 lines of text in the upper left corner and one line
above the line of the plot.
I had to adjust the 3 lines to get a decent spacing. This wasnt a difficult
task but it would be easy if I could say here is the text, here is the
location, and then Python stacks it with proper spacing.
For the lone line, I had to make adjustments so it wasn't on the line and
lower the line. For this case, is is possible to tell python I would like the
text above the plot and 80% down the line?
I am used to `LaTeX` where I can make this adjustments without hard coding the
coordinates. The advantage are
(1) if I want to change the location, I can change the percentage shift and not the coordinate.
(2) if the line is angled, the text will adjust to the line.
The advantage to (2) is that I am trying to put text on the top portion of the
figure that slopes upward with the line.
Can this be done or am I asking to much? If so, how do I do this?
Here is the code that implements the figure:
import numpy as np
import pylab
r1 = 1 # AU Earth
r2 = 1.524 # AU Mars
deltanu = 75 * np.pi / 180 # angle in radians
mu = 38.86984154054163
c = np.sqrt(r1 ** 2 + r2 ** 2 - 2 * r1 * r2 * np.cos(deltanu))
s = (r1 + r2 + c) / 2
am = s / 2
def g(a):
alphag = 2* np.pi - 2 * np.arcsin(np.sqrt(s / (2 * a)))
return (np.sqrt(a ** 3 / mu)
* (alphag - betag - (np.sin(alphag) - np.sin(betag))))
def f(a):
alpha = 2 * np.arcsin(np.sqrt(s / (2 * a)))
beta = 2 * np.arcsin(np.sqrt((s - c) / (2 * a)))
return (np.sqrt(a **3 / mu) * (alpha - betag - (np.sin(alpha)
- np.sin(betag))))
betag = -2 * np.arcsin(np.sqrt((s - c) / (2 * a)))
a = np.linspace(am, 2, 500000)
a = np.linspace(am, 2, 500000)
fig = pylab.figure()
ax = fig.add_subplot(111)
ax.plot(a, f(a), color = '#000000')
ax.plot(a, g(a), color = '#000000')
pylab.xlim((0.9, 2))
pylab.ylim((0, 2))
pylab.xlabel('Semi-major Axis $a$ in AU')
pylab.ylabel('Time of Flight in Years')
pylab.text(1, 1.8, '$r_1 = 1.0$ AU', fontsize = 11, color = 'r')
pylab.text(1, 1.7, '$r_2 = 1.524$ AU', fontsize = 11, color = 'r')
pylab.text(1, 1.6, '$\\Delta \\nu = 75^{\\circ}$', fontsize = 11,
color = 'r')
pylab.text(1.75, 0.35, '$\\alpha = \\alpha_0$', fontsize = 11,
color = 'r')
pylab.savefig('lamberttransferties.eps', format = 'eps')
pylab.show()
Answer: You can use line separators `\n`:
pylab.text(1, 1.5, '$r_1 = 1.0$ AU\n' +\
'$r_2 = 1.524$ AU\n' +\
'$\\Delta \\nu = 75^{\\circ}$', fontsize = 11, color = 'r')
`pylab.text()` uses data coordinates by default, but you can use relative
positions `(0,0)` to the lower-left and `(1,1)` to the upper-right, passing
the parameter `transform`. See this example:
pylab.text(0.6, 0.75, 'using axis coords', transform=ax.transAxes)
The parameters: `verticalalignment` and `horizontalalignment` can also help
you tremendously. Suppose you want to place a texts at the very corners:
pylab.text(1.,1.,'top-right', transform=ax.transAxes,
horizontalalignment='right', verticalalignment='top')
pylab.text(0.,0.,'bottom-left', transform=ax.transAxes,
horizontalalignment='left', verticalalignment='bottom')

To automatically calculate an angle to the text depending on your data you can
do the following approach:
* detect the data closest point
* find the a sequence near the closest point and fit a curve using this sequence (the example below uses a fourth order curve)
* calculate the derivative at the point where you want the text placed
* correct the direvative with `ax.get_data_ratio()` OBS: not needed if `ax.axis('scaled')` is used, for example
This algorithm can be implemented as follows:
def rtext(line,x,y,s, **kwargs):
from scipy.optimize import curve_fit
xdata,ydata = line.get_data()
dist = np.sqrt((x-xdata)**2 + (y-ydata)**2)
dmin = dist.min()
TOL_to_avoid_rotation = 0.3
if dmin > TOL_to_avoid_rotation:
r = 0.
else:
index = dist.argmin()
xs = xdata[ [index-2,index-1,index,index+1,index+2] ]
ys = ydata[ [index-2,index-1,index,index+1,index+2] ]
def f(x,a0,a1,a2,a3):
return a0 + a1*x + a2*x**2 + a3*x**3
popt, pcov = curve_fit(f, xs, ys, p0=(1,1,1,1))
a0,a1,a2,a3 = popt
ax = pylab.gca()
derivative = (a1 + 2*a2*x + 3*a3*x**2)
derivative /= ax.get_data_ratio()
r = np.arctan( derivative )
return pylab.text(x, y, s, rotation=np.rad2deg(r), **kwargs)
The following test example shows how to use it:
ax = pylab.subplot(111)
thetas = np.linspace(0,6*np.pi,1000)
i = np.arange(len(thetas))
xdata = (1. + (3.-1.)*i/len(thetas))*np.cos(thetas)
ydata = (1. + (3.-1.)*i/len(thetas))*np.sin(thetas)
ax.plot(xdata, ydata, color = 'b')
pylab.xlabel('x')
pylab.ylabel('y')
for x, y in zip(xdata,ydata)[::25]:
rtext(ax.lines[0], x, y,
'$\\alpha = \\alpha_0$', fontsize = 14, color = 'r',
horizontalalignment='center', verticalalignment='center')

Changing `verticalalignment='bottom'`

|
What causes the NZEC (Non Zero Exit Code) error in my Sums in a Triangle solution?
Question: I was doing [this practice problem](http://www.codechef.com/problems/SUMTRIAN)
on codechef. I have already [solved this in
C](http://www.codechef.com/status/SUMTRIAN,anshbansal) and was trying to do
the same in Python 2.7. I am getting NZEC error on codechef judge which is
"Non Zero Exit Code". I don't understand why this could be happening. The
program is working fine on my computer. What kind of corner case can be giving
this problem?
import sys
from itertools import islice
def p():
cases = int(sys.stdin.readline())
for case in xrange(cases):
height = int(sys.stdin.readline())
triangle = [map(int, i.split()) for i in islice(sys.stdin,height)]
prev_row = triangle[0]
for i in xrange(1, height):
cur_row = triangle[i]
cur_row[0] += prev_row[0]
cur_row[len(cur_row) - 1] += prev_row[len(prev_row) - 1]
for j in xrange(1, len(cur_row) - 1):
if(prev_row[j - 1] > prev_row[j]):
cur_row[j] += prev_row[j - 1]
else:
cur_row[j] += prev_row[j]
prev_row = cur_row
print max(prev_row)
p()
Answer: change this line:
triangle = [map(int, i.split()) for i in islice(sys.stdin,height)]
to this:
triangle = [map(int, sys.stdin.readline().split()) for _ in xrange(height)]
From the [docs](http://docs.python.org/2/library/stdtypes.html#file.next):
> As a consequence of using a read-ahead buffer, combining `next()` with other
> file methods (like `readline()`) does not work right.
#so.py
import sys
from itertools import islice
print list(islice(sys.stdin,3))
print sys.stdin.readline()
Demo:
$ python so.py <abc
['2\n', '3\n', '1\n']
Traceback (most recent call last):
File "so.py", line 4, in <module>
print sys.stdin.readline()
ValueError: Mixing iteration and read methods would lose data
|
Fastest and/or most pythonic way to convert string into a number
Question: first of all, I've seen quite a few questions related to this (convert string
to float, etc etc), but I need something more generic, which I could not find
(so I hope this will also help out other people with a similar problem). I
have made a solution, but am wondering whether it is the best solution in
terms of 1) performance and 2) pythonic elegance.
The problem in short:
* I get data from a variety of sources, these are made into a list with dicts (as a row/column table setup).
* The variety means that I cannot rely on a fixed input type (basically they might be string, boolean, int, float) but the user can designate which columns (keys in the dict) are values.
* Which I then need to convert to actual value types (we're talking about 100s of millions of rows of data here, so performance is rather key).
* If the input is not a real number (like: 'aaa'), then it should return None.
* There might be currency symbols and thousand separators (which need to be removed), and decimal separators (which need to be replaced by the standard dot, if it's not a dot)
So what have I made:
import ast
import types
NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
def mk_value(s, currency_sign='', thousand_sep='', decimal_sep='.'):
if isinstance(s, bool): # make boolean into a 0/1 value
if s:
result = 1
else:
result = 0
elif isinstance(s, NumberTypes): # keep numbers as/is
result = s
else: # convert a string
# prepare the string for conversion
if currency_sign != '':
s = s.replace(currency_sign, '')
if thousand_sep != '':
s = s.replace(thousand_sep, '')
if decimal_sep != '.':
s = s.replace(decimal_sep, '.')
s = s.strip()
# convert the string
if s == '':
result = None
else:
try:
# convert the string by a safe evaluation
result = ast.literal_eval(s)
# check if result of the evaluation is a number type
if not isinstance(result, NumberTypes):
result = None
except ValueError:
# if the conversion gave an error, the string is not a number
result = None
return result
You can test it by:
mk_value(True)
mk_value(1234)
mk_value(1234.56)
mk_value('1234')
mk_value('1234.56')
mk_value('1,234.56') # without an explicit decimal separator this is not a number
mk_value('1.234.567,89 EUR', currency_sign='EUR', thousand_sep='.', decimal_sep=',') # all exceptions
So this works (as far as I can see); but is this the best/most pythonic way?
Are there faster ways? Should I look into Cython for this? Any ideas on
improving this would be really helpful!
BR
Carst
Edit: I've updated my code based on the suggestions by Andrew and WoLpH. It
now looks like this:
import types
NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
def mk_value(s, currency_sign='', thousand_sep='', decimal_sep='.'):
if isinstance(s, bool): # make boolean into a 0/1 value
if s:
result = 1
else:
result = 0
elif isinstance(s, NumberTypes): # keep numbers as/is
result = s
else: # convert a string
# prepare the string for conversion
if currency_sign:
s = s.replace(currency_sign, '')
if thousand_sep:
s = s.replace(thousand_sep, '')
if decimal_sep != '.':
s = s.replace(decimal_sep, '.')
s = s.strip()
# convert the string
if not s: # if the string is empty, it's not a number
result = None
else:
try: # try int
result = int(s)
except ValueError:
try: # if there's an error, try float
result = float(s)
except ValueError:
# if the conversion gave an error, the string is not a number
result = None
return result
the previous code's performance was this:
>>> timeit.timeit("mk_value(1234)", 'from __main__ import mk_value', number=100000)
0.050575971603393555
>>> timeit.timeit("mk_value(1234.56)", 'from __main__ import mk_value', number=100000)
0.07073187828063965
>>> timeit.timeit("mk_value('1234')", 'from __main__ import mk_value', number=100000)
0.8333430290222168
>>> timeit.timeit("mk_value('1234.56')", 'from __main__ import mk_value', number=100000)
0.8230760097503662
>>> timeit.timeit("mk_value('1,234.56', thousand_sep=',')", 'from __main__ import mk_value', number=100000)
0.9358179569244385
the new code's performance:
>>> timeit.timeit("mk_value(1234)", 'from __main__ import mk_value', number=100000)
0.04723405838012695
>>> timeit.timeit("mk_value(1234.56)", 'from __main__ import mk_value', number=100000)
0.06952905654907227
>>> timeit.timeit("mk_value('1234')", 'from __main__ import mk_value', number=100000)
0.1798090934753418
>>> timeit.timeit("mk_value('1234.56')", 'from __main__ import mk_value', number=100000)
0.45616698265075684
>>> timeit.timeit("mk_value('1,234.56', thousand_sep=',')", 'from __main__ import mk_value', number=100000)
0.5290899276733398
So that's a lot faster: almost twice as fast for the most complex one and much
much faster for the int (I guess as it's the first in the try/except logic)!
Really great, thanks for your input.
I'm going to leave it open for now to see if someone has a brilliant idea on
how to improve more :) At the very least I hope this will help other people in
the future (it must be a very common issue)
Answer: It could be slightly more Pythonic imho, but I'm not sure about the best
solution yet.
# Code
## `benchmark.py`
# vim: set fileencoding=utf-8 :
import timeit
import pyximport
pyximport.install()
def timer(func, mod):
import_ = 'from %s import mk_value' % mod
time = timeit.timeit(func, import_, number=100000)
ms = 1000 * time
us = 1000 * ms
if func[40:]:
func_short = func[:37] + '...'
else:
func_short = func
print '%(mod)s.%(func_short)-40s %(ms)6dms %(us)12dμs' % locals()
for mod in 'abcd':
timer("mk_value(1234)", mod)
timer("mk_value(1234.56)", mod)
timer("mk_value('1234')", mod)
timer("mk_value('1234.56')", mod)
timer("mk_value('1,234.56', thousand_sep=',')", mod)
timer("mk_value('1.234.567,89 EUR', currency_sign='EUR', "
"thousand_sep='.', decimal_sep=',')", mod)
## `a.py`
import ast
import types
NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
def mk_value(s, currency_sign='', thousand_sep='', decimal_sep='.'):
if isinstance(s, bool): # make boolean into a 0/1 value
if s:
result = 1
else:
result = 0
elif isinstance(s, NumberTypes): # keep numbers as/is
result = s
else: # convert a string
# prepare the string for conversion
if currency_sign != '':
s = s.replace(currency_sign, '')
if thousand_sep != '':
s = s.replace(thousand_sep, '')
if decimal_sep != '.':
s = s.replace(decimal_sep, '.')
s = s.strip()
# convert the string
if s == '':
result = None
else:
try:
# convert the string by a safe evaluation
result = ast.literal_eval(s)
# check if result of the evaluation is a number type
if not isinstance(result, NumberTypes):
result = None
except ValueError:
# if the conversion gave an error, the string is not a number
result = None
return result
## `b.py`
import types
NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
def mk_value(s, currency_sign='', thousand_sep='', decimal_sep='.'):
if isinstance(s, bool): # make boolean into a 0/1 value
if s:
result = 1
else:
result = 0
elif isinstance(s, NumberTypes): # keep numbers as/is
result = s
else: # convert a string
# prepare the string for conversion
if currency_sign:
s = s.replace(currency_sign, '')
if thousand_sep:
s = s.replace(thousand_sep, '')
if decimal_sep != '.':
s = s.replace(decimal_sep, '.')
s = s.strip()
# convert the string
if not s: # if the string is empty, it's not a number
result = None
else:
try: # try int
result = int(s)
except ValueError:
try: # if there's an error, try float
result = float(s)
except ValueError:
# if the conversion gave an error, the string is not a number
result = None
return result
## `c.pyx`
import types
NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
def mk_value(s, currency_sign='', thousand_sep='', decimal_sep='.'):
if isinstance(s, bool): # make boolean into a 0/1 value
if s:
result = 1
else:
result = 0
elif isinstance(s, NumberTypes): # keep numbers as/is
result = s
else: # convert a string
# prepare the string for conversion
if currency_sign:
s = s.replace(currency_sign, '')
if thousand_sep:
s = s.replace(thousand_sep, '')
if decimal_sep != '.':
s = s.replace(decimal_sep, '.')
s = s.strip()
# convert the string
if not s: # if the string is empty, it's not a number
result = None
else:
try: # try int
result = int(s)
except ValueError:
try: # if there's an error, try float
result = float(s)
except ValueError:
# if the conversion gave an error, the string is not a number
result = None
return result
## `d.pyx`
import types
NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
def mk_value(s, currency_sign='', thousand_sep='', decimal_sep='.'):
if isinstance(s, bool): # make boolean into a 0/1 value
if s:
result = 1
else:
result = 0
elif isinstance(s, NumberTypes): # keep numbers as/is
result = s
elif s:
if currency_sign:
s = s.replace(currency_sign, '')
result = _mk_value(s, currency_sign, thousand_sep, decimal_sep)
else:
result = None
return result
cdef object _mk_value(char *s, char *currency_sign, char *thousand_sep, char *decimal_sep):
cdef int i=0, j=0
result = None
while s[i]:
if s[i] == decimal_sep[0]:
s[j] = '.'
j += 1
elif s[i] == thousand_sep[0]:
pass
elif s[i] == ' ':
pass
else:
s[j] = s[i]
j += 1
i += 1
# convert the string
if not s: # if the string is empty, it's not a number
result = None
else:
try: # try int
result = int(s)
except ValueError:
try: # if there's an error, try float
result = float(s)
except ValueError:
# if the conversion gave an error, the string is not a number
pass
return result
# Results
a.mk_value(1234) 27ms 27526μs
a.mk_value(1234.56) 42ms 42097μs
a.mk_value('1234') 502ms 502109μs
a.mk_value('1234.56') 520ms 520395μs
a.mk_value('1,234.56', thousand_sep=',') 570ms 570749μs
a.mk_value('1.234.567,89 EUR', currency... 627ms 627456μs
b.mk_value(1234) 27ms 27082μs
b.mk_value(1234.56) 40ms 40014μs
b.mk_value('1234') 94ms 94444μs
b.mk_value('1234.56') 276ms 276519μs
b.mk_value('1,234.56', thousand_sep=',') 315ms 315310μs
b.mk_value('1.234.567,89 EUR', currency... 374ms 374861μs
c.mk_value(1234) 11ms 11482μs
c.mk_value(1234.56) 22ms 22765μs
c.mk_value('1234') 69ms 69251μs
c.mk_value('1234.56') 176ms 176908μs
c.mk_value('1,234.56', thousand_sep=',') 226ms 226709μs
c.mk_value('1.234.567,89 EUR', currency... 285ms 285431μs
d.mk_value(1234) 11ms 11483μs
d.mk_value(1234.56) 22ms 22355μs
d.mk_value('1234') 69ms 69151μs
d.mk_value('1234.56') 169ms 169364μs
d.mk_value('1,234.56', thousand_sep=',') 187ms 187460μs
d.mk_value('1.234.567,89 EUR', currency... 233ms 233935μs
|
Python an open-source list of words by valence or categories for comparison
Question: I tend to take notes quite regularly and since the great tablet revolution
I've been taking them electronically. I've been trying to see if I can find
any patterns in the way I take notes. So I've put together a small hack to
load the notes and filter out proper nouns and fluff to leave a list of key
words I employ.
import os
import re
dr = os.listdir('/home/notes')
dr = [i for i in dr if re.search('.*txt$',i)]
ignore = ['A','a','of','the','and','in','at','our','my','you','your','or','to','was','will','because','as','also','is','eg','e.g.','on','for','Not','not']
words = set()
d1 = open('/home/data/en_GB.dic','r')
dic = d1.read().lower()
dic = re.findall('[a-z]{2,}',dic)
sdic = set(dic)
for i in dr:
a = open(os.path.join('/home/notes',i),'r')
atmp = a.read()
atmp = atmp.lower()
atmp = re.findall('[a-z]{3,}',atmp)
atmp = set(atmp)
atmp.intersection_update(sdic)
atmp.difference_update(set(ignore))
words.update(atmp)
a.close()
words = sorted(words)
I now have a list of about 15,000 words I regularly use while taking notes. It
would be a little unmanageable to sort by hand and I wondered if there was an
open-source library of `positive-negative-neutral` or `optimistic-pessimistic-
indifferent` or other form of word list along any meaning scale that I could
run the word list through.
In a perfect scenario I would also be able to run it through some kind of
thesarus so I could group the words into meaning clusters to get a high level
view of what sense terms I've been employing most.
Does anyone know if there are any such lists out there and if so, how would I
go about employing them in Python?
Thanks
Answer: I found a list of words used for sentiment analysis of Twitter at:
<http://alexdavies.net/twitter-sentiment-analysis/>
It includes example Python code for how to use it.
See also: [Sentiment Analysis
Dictionaries](http://stackoverflow.com/questions/4188706/sentiment-analysis-
dictionaries)
|
tagging pos in nltk using backoff ngrams
Question: I tried make part of speech (or POS) tagger in nltk but I can't get it to work
for more than one ngram tagger for a time using backoff. I read that you use
more taggers for higher scores but it won't work for me. I want it to first
use more words then use less down to one. I tried it like this,
import nltk
from nltk.corpus import brown
#sentence = brown.sents(categories = "news")
trains = brown.tagged_sents(categories = "news")
from nltk import NgramTagger
fortest = ["hi", "how","are", "you"]
tagger = (nltk.NgramTagger (n, trains, backoff=n-1) for n in range (3))
print tagger.tag(fortest)
But it gives me error AttributeError: 'generator' object has no attribute
'tag'
so i make it without a list:
for n in range(3):
tagger = nltk.NgramTagger(n, trains, backoff=n-1)
But then I get:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nltk/tag/sequential.py", line 271, in __init__
ContextTagger.__init__(self, model, backoff)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nltk/tag/sequential.py", line 121, in __init__
SequentialBackoffTagger.__init__(self, backoff)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nltk/tag/sequential.py", line 46, in __init__
self._taggers = [self] + backoff._taggers AttributeError: 'int' object has no attribute '_taggers'
Please help would be appreciated for I am new to doing python.
Answer: Spaceghost is correct, you need to provide a reference back to an actual
`NgramTagger` object as the `backoff` argument and not just an `int`. Simply
using a number as backoff is meaningless - when creating a new tagger, it has
no idea where to look for the previously created tagger with a smaller
relative context.
This is why you get the `AttributeError: 'int' object has no attribute
'_taggers'`. NLTK is looking for an object of a class inheriting from
[`SequentialBackoffTagger`](http://nltk.googlecode.com/svn/trunk/doc/api/nltk.tag.sequential-
pysrc.html#SequentialBackoffTagger).
Based on your `range(3)`, I'm going to guess you actually wanted a _trigram
tagger_ with backoff to a _bigram tagger_ , with backoff to a _unigram
tagger_.
You can try something like,
from nltk.corpus import brown
from nltk import NgramTagger
trains = brown.tagged_sents(categories="news")
tagger = None # None here is okay since it's the default argument anyway
for n in range(1,4): # start at unigrams (1) up to and including trigrams (3)
tagger = NgramTagger(n, trains, backoff=tagger)
**NOTE:** No need to import nltk multiple times.
>>> tagger.tag('hi how are you'.split())
[('hi', None), ('how', 'WRB'), ('are', 'BER'), ('you', 'PPSS')]
Notice, we get `None` for the POS of words like "hi" since it doesn't occur in
the given corpus (Brown's news category). You can set a default tagger if you
want by initially setting `tagger` (before the for-loop) like,
from nltk import DefaultTagger
tagger = DefaultTagger('NN')
|
Can't import module from library
Question: I have a script that requires two other modules to be loaded from another
folder in the same directory as the script.
In the main script I have the line:
from modules import *
But I keep getting this error:
AttributeError: 'module' object has no attribute 'ts3'
I have an `__init__.py` file in the `modules` folder which has this line:
__all__ = ['setjoin', 'ts3']
Python is for some reason unable to load just the `ts3` module. **It is able
to load`setjoin` completely fine.**
Folder structure:
MAOW\
maow.py
\modules\
__init__.py
setjoin.py
ts3.py
Any help would be much appreciated, thanks :)
Answer: I've found the problem. I'm not sure why I did this, but I was trying to
`import maow` from ts3.py. I've now removed that import and it works fine :)
|
Bash commands tail fails to produce output in python
Question:
#!/usr/bin/env bash
I am working on using bash commands in python I found this example in Red hat
magazine the tail command does not produce any output. I would like to
understand why it is failing and I have also tried to import subprocess but
that just hangs.
#Create Commands**strong text**
SPACE=`df -h`
MESSAGES=`tail /var/log/messages`
#Assign to an array(list in Python)
cmds=("$MESSAGES" "$SPACE")
#iteration loop
count=0
for cmd in "${cmds[@]}"; do
count=$((count + 1))
printf "Running Command Number %s \n" $count
echo "$cmd"
done
Answer: Printing the command doesn't mean executing it. Look at Python's
[subprocess](http://docs.python.org/2/library/subprocess.html) library for API
and examples for doing what you want.
|
Cannot plot anything or display pylab frame in new process using python multiprocessing
Question: Does anyone have any idea why the code below won't even open up a pylab figure
window? If the body of the test function is moved to the main process it works
fine, but I'd like to do some plotting from within a new process specifically.
from multiprocessing import Process
from pylab import *
def test():
frac = [10, 10, 10, 10, 10, 10, 40]
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
ion()
hold(False)
while True:
pie(frac, labels = labels, autopct='%1.1f%%')
title('test', bbox={'facecolor' : '0.8', 'pad' : 5})
draw()
p1 = Process(target = test)
p1.daemon = True
p1.start()
while True:
pass
Answer: Move all the GUI statements -- including the import statement -- into `test`:
import multiprocessing as mp
def test():
import matplotlib.pyplot as plt
frac = [10, 10, 10, 10, 10, 10, 40]
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
plt.pie(frac, labels = labels, autopct='%1.1f%%')
plt.title('test', bbox={'facecolor' : '0.8', 'pad' : 5})
plt.show()
p1 = mp.Process(target = test)
p1.daemon = True
p1.start()
p1.join()
Use `p1.join()` instead of `while True: pass`. It is much less CPU-intensive.
Finally, be sure to read the [Matplotlib animation
cookbook](http://www.scipy.org/Cookbook/Matplotlib/Animations) for examples on
how to do animation right.
|
Python, Django, Mongodb: ImportError: No module named bson.objectid
Question: I'm following this tutorial exactly. Tried deleting and restarting many times
with virtualenv and I'm still getting errors. Is it python, mongodb and django
supposed to be this frustrating to set up?
<http://docs.mongodb.org/manual/tutorial/write-a-tumblelog-application-with-
django-mongodb-engine/>
I get a problem when I try to call
post.save()
I then get this error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py", line 460, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py", line 553, in save_base
result = manager._insert(values, return_id=update_pk, using=using)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py", line 195, in _insert
return insert_query(self.model, values, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 1436, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/query.py", line 213, in get_compiler
return connection.ops.compiler(self.compiler)(self, connection, using)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/__init__.py", line 576, in compiler
self._cache = import_module(self.compiler_module)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/marcochiang/Desktop/Development/caesarWorkflow/lib/python2.7/site-packages/django_mongodb_engine/compiler.py", line 18, in <module>
from bson.objectid import ObjectId
**ImportError: No module named bson.objectid**
Please someone lead me in the right direction. Is there a better tutorial to
follow because every single tutorial I follow I run into errors. I'm about to
give up on pymongo and django...
Answer: It looks like the environment isn't setup correctly. Can you ensure that
pymongo is available in your python shell:
$> python.exe
Then in the shell:
>>> import pymongo
>>> pymongo.version
What version does that report?
Also try importing bson:
>>> import bson
If those work then make sure you are running your django mongodb-engine app in
the same environment.
|
python pack() and grid() methods together
Question: Im new to python so please forgive my Noob-ness. Im trying to create a status
bar at the bottom of my app window, but it seems every time I use the pack()
and grid() methods together in the same file, the main app window doesn't
open. When I comment out the line that says statusbar.pack(side = BOTTOM, fill
= X) my app window opens up fine but if I leave it in it doesn't, and also if
I comment out any lines that use the grid method the window opens with the
status bar. It seems like I can only use either pack() or grid() but not both.
I know I should be able to use both methods. Any suggestions? Here's the code:
from Tkinter import *
import tkMessageBox
def Quit():
answer = tkMessageBox.askokcancel('Quit', 'Are you sure?')
if answer:
app.destroy()
app = Tk()
app.geometry('700x500+400+200')
app.title('Title')
label_1 = Label(text = "Enter number")
label_1.grid(row = 0, column = 0)
text_box1 = DoubleVar()
input1 = Entry(app, textvariable = text_box1)
input1.grid(row = 0, column = 2)
statusbar = Label(app, text = "", bd = 1, relief = SUNKEN, anchor = W)
statusbar.pack(side = BOTTOM, fill = X)
startButton = Button(app, text = "Start", command = StoreValues).grid(row = 9, column = 2, padx = 15, pady = 15)
app.mainloop()
Any help is appreciated! Thanks!
Answer: You cannot use both `pack` and `grid` in the same containing widget. The first
one will adjust the size of the widget. The other will see the change, and
resize everything to fit it's own constraints. The first will see these
changes and resize everything again to fit _its_ constraints. The other will
see the changes, and so on ad infinitum. They will be stuck in an eternal
struggle for supremacy.
While it is technically possible if you really, _really_ know what you're
doing, for all intents and purposes you can't mix them _in the same
container_. You can mix them all you want in your app as a whole, but for a
given container (typically, a frame), you can use only one to manager the
direct contents of the container.
A very common technique is to divide your GUI into pieces. In your case you
have a bottom statusbar, and a top "main" area. So, pack the statusbar along
the bottom and create a frame that you pack above it for the main part of the
GUI. Then, everything else has the main frame as its parent, and inside that
frame you can use grid or pack or whatever you want.
|
PySide QThread and QProgressBar
Question: I'm kinda new in GUI programming with PySide, and in Python GUI in general.
I'm trying to set a progress bar value using a thread, but it doesn't work and
there is these errors that keeps on appearing:
QPixmap: It is not safe to use pixmaps outside the GUI thread
or
QWidget::repaint: Recursive repaint detected
And the program crashes suddenly especially when I'm trying to interact with
another widget in the gui.
* * *
The following is not the actual code, it's only a simulation of what I wanted
to do:
from PySide.QtGui import *
from PySide.QtCore import *
import os, time, platform, sys
class main(QDialog):
def __init__(self, parent = None):
super(main, self).__init__(parent)
self.resize(300, 100)
self.setMinimumSize(QSize(300, 100))
self.setMaximumSize(QSize(300, 100))
self.setWindowTitle("Test")
self.buttonStart = QPushButton("Start")
self.progressBar = QProgressBar()
self.gridLayout = QGridLayout(self)
self.setLayout(self.gridLayout)
self.gridLayout.addWidget(self.progressBar, 0, 0, 1, 1)
self.gridLayout.addWidget(self.buttonStart, 0, 1, 1, 1)
self.connect(self.buttonStart, SIGNAL("clicked()"), self.startProgress)
self.genericThread = GenericThread(self.test)
def startProgress(self):
self.genericThread.start()
def test(self):
print "started"
for i in range(100):
time.sleep(0.3)
print i
self.progressBar.setValue(i)
print "done"
class GenericThread(QThread):
def __init__(self, function, *args, **kwargs):
QThread.__init__(self)
self.function = function
self.args = args
self.kwargs = kwargs
def run(self):
self.function(*self.args,**self.kwargs)
return
app = QApplication(sys.argv)
start = main()
start.show()
app.exec_()
So, the GenericThread is supposed to run any function passed into it in a
thread, instead of creating a thread for each function. I know that I should
be using signals to make a thread change a widget in the gui thread, but
actually I failed to apply that with this thread class. I tried to add the
signal to the test function, and connect it to the main class, but it didn't
do anything.
So what should I do? I don't want to change the thread class GenericThread, as
the actual code has many functions that need to be run in separate threads,
and at the same time I need to show the thread's progress to the user.
Answer: Use a signal to the gui thread to have it update the progress bar and/or draw
the Pixmap.
And when you connect that signal, make sure that you tell it to use a
`Qt::QueuedConnection`, instead of a `Qt::AutoConnection`.
<http://doc.qt.io/qt-4.8/qt.html#ConnectionType-enum>
<http://doc.qt.io/qt-4.8/qobject.html#connect>
<http://doc.qt.io/qt-4.8/qcoreapplication.html#processEvents>
Hope that helps.
|
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type
Question: I am writing a proxy crawler which stores data in sqlite database,and I prefer
to saving a complex object by statement like `cur.execute("insert into test(p)
values (?)", (p,))`
Then I find a useful official document
[here](http://docs.python.org/2/library/sqlite3.html#converting-sqlite-values-
to-custom-python-types)
The example in official document works very well.
But there is a problem come to me.
I change the official code to :
import sqlite3
import time
class Proxy:
def __init__(self,ip,port,speed,area,level,active,last_check_time):
self.ip = ip
self.port = port
self.speed = speed
self.area = area
self.level = level
self.active = active
self.last_check_time = last_check_time
def __repr__(self):
return '%s;%s;%s;%s;%s;%d;%d' % (self.ip,self.port,self.speed,self.area,self.level,self.active,self.last_check_time)
def adapt_proxy(proxy):
return '%s;%s;%s;%s;%s;%d;%d' % (proxy.ip,proxy.port,proxy.speed,proxy.area,proxy.level,proxy.active,proxy.last_check_time)
def convert_proxy(s):
ip,port,speed,area,level,active,last_check_time = map(str, s.split(";"))
return Proxy(ip,port,speed,area,level,int(active),int(last_check_time))
# Register the adapter
sqlite3.register_adapter(Proxy, adapt_proxy)
# Register the converter
sqlite3.register_converter("proxy", convert_proxy)
p = Proxy('231', '123', '2424','444','555',1,int(time.time()))
#########################
# 1) Using declared types
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(p proxy)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test")
print "with declared types:", cur.fetchone()[0]
cur.close()
con.close()
#######################
# 1) Using column names
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(p)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute('select p as "p [proxy]" from test')
print "with column names:", cur.fetchone()[0]
cur.close()
con.close()
error occur:
Traceback (most recent call last):
File "C:\Users\kss\Desktop\py\ts1.py", line 52, in <module>
cur.execute("insert into test(p) values (?)", (p,))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
[Finished in 0.1s with exit code 1]
It is really odd.I can not figure out it
Answer: Change your declaration of Proxy to:
class Proxy(object):
# all the stuff before
The problem is that your class is not a "new style" class; inheriting from
`object` makes it one.
Notice how the
[documentation](http://docs.python.org/2/library/sqlite3.html#registering-an-
adapter-callable) says:
> The type/class to adapt must be a new-style class, i. e. it must have object
> as one of its bases.
|
How to extract using beautifulsoup python
Question: I am only interested to use beautifulsoup to extract all the value of 3-hr PSI
Readings from 12AM to 11.59PM. Such as the latest **bold** text of **82** at
5pm.
Example of website is at <http://app2.nea.gov.sg/anti-pollution-radiation-
protection/air-pollution/psi/psi-readings-over-the-last-24-hours>. Can anyone
teach me how ? Thanks in advance !
<!-- start content -->
<h1 class="title" id="top">
PSI Readings over the last 24 Hours</h1>
<script type="text/javascript">
var baseUrl = '/anti-pollution-radiation-protection/air-pollution/psi/psi-readings-over-the-last-24-hours';
function changetime(ddl) {
var strTime = ddl.options[ddl.selectedIndex].value;
if (strTime != null) {
var npage = baseUrl + "/time/" + strTime + "#psi24";
window.location = npage;
}
}
</script>
<h1 id="psi24">
24-hr PSI Readings on 24 Jun 2013
</h1>
<p>
View reading for:
<select class="default" id="ContentPlaceHolderContent_C001_DDLTime" name="ctl00$ContentPlaceHolderContent$C001$DDLTime" onchange="changetime(this);">
<option value="0000">12AM</option>
<option value="0100">1AM</option>
<option value="0200">2AM</option>
<option value="0300">3AM</option>
<option value="0400">4AM</option>
<option value="0500">5AM</option>
<option value="0600">6AM</option>
<option value="0700">7AM</option>
<option value="0800">8AM</option>
<option value="0900">9AM</option>
<option value="1000">10AM</option>
<option value="1100">11AM</option>
<option value="1200">12PM</option>
<option value="1300">1PM</option>
<option value="1400">2PM</option>
<option value="1500">3PM</option>
<option value="1600">4PM</option>
<option selected="selected" value="1700">5PM</option>
</select>
</p>
<table border="0" cellpadding="4" cellspacing="1" class="text_psinormal" width="100%">
<thead>
<tr>
<th width="33%">
<center><strong>Region</strong></center>
</th>
<th width="33%">
<center><strong>PSI</strong></center>
</th>
<th width="34%">
<center><strong>24-hr PM2.5 Concentration (µg/m<sup>3</sup>)</strong></center>
</th>
</tr>
</thead>
<tr>
<td align="center">North
</td>
<td align="center">
61
</td>
<td align="center">
47
</td>
</tr>
<tr>
<td align="center">South
</td>
<td align="center">
62
</td>
<td align="center">
46
</td>
</tr>
<tr>
<td align="center">East
</td>
<td align="center">
55
</td>
<td align="center">
39
</td>
</tr>
<tr>
<td align="center">West
</td>
<td align="center">
87
</td>
<td align="center">
83
</td>
</tr>
<tr>
<td align="center">Central
</td>
<td align="center">
58
</td>
<td align="center">
40
</td>
</tr>
<tr>
<td align="center">Overall Singapore
</td>
<td align="center">
55-87
</td>
<td align="center">
39-83
</td>
</tr>
</table>
<div>
</div>
<div>
<h1>3-hr PSI Readings from 12AM to 11.59PM on
24 Jun 2013</h1>
<table border="0" cellpadding="4" cellspacing="1" width="100%">
<tr>
<td align="center" width="16%">
<strong>Time</strong>
</td>
<td align="center" width="7%"><strong>12AM</strong>
</td>
<td align="center" width="7%"><strong>1AM</strong>
</td>
<td align="center" width="7%"><strong>2AM</strong>
</td>
<td align="center" width="7%"><strong>3AM</strong>
</td>
<td align="center" width="7%"><strong>4AM</strong>
</td>
<td align="center" width="7%"><strong>5AM</strong>
</td>
<td align="center" width="7%"><strong>6AM</strong>
</td>
<td align="center" width="7%"><strong>7AM</strong>
</td>
<td align="center" width="7%"><strong>8AM</strong>
</td>
<td align="center" width="7%"><strong>9AM</strong>
</td>
<td align="center" width="7%"><strong>10AM</strong>
</td>
<td align="center" width="7%"><strong>11AM</strong>
</td>
</tr>
<tr>
<td align="center">
<strong>3-hr PSI</strong>
</td>
<td align="center">
76
</td>
<td align="center">
70
</td>
<td align="center">
64
</td>
<td align="center">
59
</td>
<td align="center">
54
</td>
<td align="center">
51
</td>
<td align="center">
48
</td>
<td align="center">
47
</td>
<td align="center">
47
</td>
<td align="center">
47
</td>
<td align="center">
49
</td>
<td align="center">
52
</td>
</tr>
<tr>
<td align="center" width="16%">
<strong>Time</strong>
</td>
<td align="center" width="7%"><strong>12PM</strong>
</td>
<td align="center" width="7%"><strong>1PM</strong>
</td>
<td align="center" width="7%"><strong>2PM</strong>
</td>
<td align="center" width="7%"><strong>3PM</strong>
</td>
<td align="center" width="7%"><strong>4PM</strong>
</td>
<td align="center" width="7%"><strong>5PM</strong>
</td>
<td align="center" width="7%"><strong>6PM</strong>
</td>
<td align="center" width="7%"><strong>7PM</strong>
</td>
<td align="center" width="7%"><strong>8PM</strong>
</td>
<td align="center" width="7%"><strong>9PM</strong>
</td>
<td align="center" width="7%"><strong>10PM</strong>
</td>
<td align="center" width="7%"><strong>11PM</strong>
</td>
</tr>
<tr>
<td align="center">
<strong>3-hr PSI</strong>
</td>
<td align="center">
54
</td>
<td align="center">
59
</td>
<td align="center">
65
</td>
<td align="center">
72
</td>
<td align="center">
79
</td>
<td align="center">
<strong style="font-size:14px;">82</strong>
</td>
<td align="center">
-
</td>
<td align="center">
-
</td>
<td align="center">
-
</td>
<td align="center">
-
</td>
<td align="center">
-
</td>
<td align="center">
-
</td>
</tr>
</table>
</div>
<div class="sfContentBlock">
<p class="table-caption">Hourly updates of 3-hr PSI readings are provided from 12am to 11:59pm. The 3hr PSI readings are calculated based on PM10 concentrations only</p>
</div>
<div>
</div>
<div class="backToTop">
<a href="#top">Back to Top</a>
</div>
</div>
</div>
<!-- end content -->
Answer: Though you should have shown that you've tried to do it yourself, but here is
the code:
from pprint import pprint
import urllib2
from bs4 import BeautifulSoup as soup
url = "http://app2.nea.gov.sg/anti-pollution-radiation-protection/air-pollution/psi/psi-readings-over-the-last-24-hours"
web_soup = soup(urllib2.urlopen(url))
table = web_soup.find(name="div", attrs={'class': 'c1'}).find_all(name="div")[2].find_all('table')[0]
table_rows = []
for row in table.find_all('tr'):
table_rows.append([td.text.strip() for td in row.find_all('td')])
data = {}
for tr_index, tr in enumerate(table_rows):
if tr_index % 2 == 0:
for td_index, td in enumerate(tr):
data[td] = table_rows[tr_index + 1][td_index]
pprint(data)
prints:
{'10AM': '49',
'10PM': '-',
'11AM': '52',
'11PM': '-',
'12AM': '76',
'12PM': '54',
'1AM': '70',
'1PM': '59',
'2AM': '64',
'2PM': '65',
'3AM': '59',
'3PM': '72',
'4AM': '54',
'4PM': '79',
'5AM': '51',
'5PM': '82',
'6AM': '48',
'6PM': '79',
'7AM': '47',
'7PM': '-',
'8AM': '47',
'8PM': '-',
'9AM': '47',
'9PM': '-',
'Time': '3-hr PSI'}
|
distance calculation in python for google earth coordinates
Question: Hi I have a kml file called Placemark and 4 nodes (placemarks) that are
located in an area on Google Earth. Each placemark-node has a longitude and a
latitude.
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<name>placemarks.kml</name>
<StyleMap id="m_ylw-pushpin">
<Pair>
<key>normal</key>
<styleUrl>#s_ylw-pushpin</styleUrl>
</Pair>
<Pair>
<key>highlight</key>
<styleUrl>#s_ylw-pushpin_hl</styleUrl>
</Pair>
</StyleMap>
<Style id="s_ylw-pushpin_hl">
<IconStyle>
<scale>1.3</scale>
<Icon>
<href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href>
</Icon>
<hotSpot x="20" y="2" xunits="pixels" yunits="pixels"/>
</IconStyle>
</Style>
<Style id="s_ylw-pushpin">
<IconStyle>
<scale>1.1</scale>
<Icon>
<href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href>
</Icon>
<hotSpot x="20" y="2" xunits="pixels" yunits="pixels"/>
</IconStyle>
</Style>
<Folder>
<name>placemarks</name>
<open>1</open>
<Placemark>
<name>node0</name>
<LookAt>
<longitude>21.78832062146911</longitude>
<latitude>38.28791526390673</latitude>
<altitude>0</altitude>
<heading>0.001539813336055052</heading>
<tilt>44.99941206765101</tilt>
<range>990.2435222326291</range>
<gx:altitudeMode>relativeToSeaFloor</gx:altitudeMode>
</LookAt>
<styleUrl>#m_ylw-pushpin</styleUrl>
<Point>
<coordinates>21.78400936610002,38.2874355527483,67.51641688336248</coordinates>
</Point>
</Placemark>
<Placemark>
<name>node1</name>
<LookAt>
<longitude>21.78832062146911</longitude>
<latitude>38.28791526390673</latitude>
<altitude>0</altitude>
<heading>0.001539813336055052</heading>
<tilt>44.99941206765101</tilt>
<range>990.2435222326291</range>
<gx:altitudeMode>relativeToSeaFloor</gx:altitudeMode>
</LookAt>
<styleUrl>#m_ylw-pushpin</styleUrl>
<Point>
<coordinates>21.78453228393861,38.28690995466475,67.51641688336248</coordinates>
</Point>
</Placemark>
<Placemark>
<name>node2</name>
<LookAt>
<longitude>21.78832062146911</longitude>
<latitude>38.28791526390673</latitude>
<altitude>0</altitude>
<heading>0.001539813336055052</heading>
<tilt>44.99941206765101</tilt>
<range>990.2435222326291</range>
<gx:altitudeMode>relativeToSeaFloor</gx:altitudeMode>
</LookAt>
<styleUrl>#m_ylw-pushpin</styleUrl>
<Point>
<coordinates>21.7848823502596,38.2869152766261,67.51641688336248</coordinates>
</Point>
</Placemark>
<Placemark>
<name>node3</name>
<LookAt>
<longitude>21.78832062146911</longitude>
<latitude>38.28791526390673</latitude>
<altitude>0</altitude>
<heading>0.001539813336055052</heading>
<tilt>44.99941206765101</tilt>
<range>990.2435222326291</range>
<gx:altitudeMode>relativeToSeaFloor</gx:altitudeMode>
</LookAt>
<styleUrl>#m_ylw-pushpin</styleUrl>
<Point>
<coordinates>21.78459887820567,38.28740826552452,67.51641688336248</coordinates>
</Point>
</Placemark>
</Folder>
</Document>
</kml>
What I want is to calculate the distance between node0 and node2,3,4...
(keeping node0 constant in the distance function) and then, print the results.
By using the code below: (I need to modify it in order to have the output
below)
# adapted from haversine.py <https://gist.github.com/rochacbruno/2883505>
# see also <http://en.wikipedia.org/wiki/Haversine_formula>
from math import atan2, cos, sin, sqrt, radians
def calc_distance(origin, destination):
"""great-circle distance between two points on a sphere
from their longitudes and latitudes"""
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km. earth
dlat = radians(lat2-lat1)
dlon = radians(lon2-lon1)
a = (sin(dlat/2) * sin(dlat/2) + cos(radians(lat1)) * cos(radians(lat2)) *
sin(dlon/2) * sin(dlon/2))
c = 2 * atan2(sqrt(a), sqrt(1-a))
d = radius * c
return d
from xml.dom import minidom
xmldoc = minidom.parse("placemarks.kml")
kml = xmldoc.getElementsByTagName("kml")[0]
document = kml.getElementsByTagName("Document")[0]
placemarks = document.getElementsByTagName("Placemark")
nodes = {}
for placemark in placemarks:
nodename = placemark.getElementsByTagName("name")[0].firstChild.data[:-1]
coords = placemark.getElementsByTagName("coordinates")[0].firstChild.data
lst1 = coords.split(",")
longitude = float(lst1[0])
latitude = float(lst1[1])
nodes[nodename] = (latitude, longitude)
Ang get an output like:
node1: (21.78453228393861, 38.28690995466475), distance from node0:
node2: (21.78488235025960, 38.28691527662610), distance from node0:
node3: (21.78459887820567, 38.28740826552452), distance from node0:
Answer: In the code where you collect nodes extracted from the KML file, the names of
nodes, as you extract them from the XML, are always the same, so when you try
to store it in the dictionary `nodes` you get only one point in the end. Here
is a corrected script (only the last part, which needed to be be fixed), which
I think does what you require (please tell us if it's not the case and you
need something else):
nodes = {}
for placemark in placemarks:
nodename = placemark.getElementsByTagName("name")[0].firstChild.data
coords = placemark.getElementsByTagName("coordinates")[0].firstChild.data
lst1 = coords.split(",")
longitude = float(lst1[0])
latitude = float(lst1[1])
nodes[nodename] = (latitude, longitude)
for n in nodes:
if n == 'node0':
continue
print n, nodes[n], 'distance from node0:', calc_distance(nodes['node0'], nodes[n])
Here is the output:
node1 (38.28690995466475, 21.78453228393861) distance from node0: 0.074152874049
node3 (38.28740826552452, 21.78459887820567) distance from node0: 0.0515409901388
node2 (38.2869152766261, 21.7848823502596) distance from node0: 0.0956671636024
|
How to create a self-destroying child window to monitor an activity?
Question: As a followup to [this
question](http://stackoverflow.com/questions/17117156/create-a-python-tkinter-
window-with-no-x-close-button), I wanted to know whether there's a way in
Python/Tkinter to create a child window, have it show text progress updates
for a 30-60 second process, and then destroy itself when the process
completes. The process in question involves multiple steps such as file
copying, database updates, etc.
The linked-to question has a code sample showing the approach I used to create
a custom dialog window that collects user input and then closes after an
OK/Cancel button is clicked. I've found that using this same approach doesn't
work for the status-update child I want to create. If I put all the code
inside the `showWin` method, I hit a race condition where the window tries to
destroy itself before it's displayed (even when I used `update_idletasks`).
But if I try moving the file/DB code to a separate method, there's no event to
trigger it and so the processing never happens.
Do I just need to give up on using a child window for this purpose? Or is
there some arrangement that lets the processing happen while avoiding the race
condition?
Answer: I don't quite understand what you're trying to accomplish, but based solely on
the title of the question I'm guessing you want some sort of pop-up progress
window that destroys itself when progress is complete.
Here's a contrived example that displays a window that self-destructs when
progress passes 100%. It's not very bullet-proof, but it shows that it's
possible to create a window that self-destructs.
import Tkinter as tk
class App(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
go_button = tk.Button(text="Go!", command=self.go)
go_button.pack()
def go(self):
self.dialog = ProgressWindow(self)
self.do_real_work(0)
def do_real_work(self, count):
# simulate doing work; update the status window periodically
self.dialog.set(count)
self.after(500, lambda count=count+10: self.do_real_work(count))
class ProgressWindow(tk.Toplevel):
def __init__(self, *args, **kwargs):
tk.Toplevel.__init__(self, *args, **kwargs)
self.label = tk.Label(self, text="0%")
self.label.pack(side="top", fill="both", expand=True)
self.wm_geometry("200x200")
def set(self, value):
if value > 100:
self.destroy()
else:
self.label.configure(text="%s %%" % value)
if __name__ == "__main__":
root = tk.Tk()
App(root).pack(side="top", fill="both", expand=True)
root.mainloop()
|
iPython Notebook in Windows - Error on Startup
Question: I am trying desperately to get ipython notebook to work in a windows
environment. I installed Continuum IO's Anaconda, a scientific distribution of
python. I want to use ipython notebook, but get the following error. `ipython`
in the terminal works fine. Any thoughts?
UPDATE: As asked for below, here is the output from sys.path on my system.
['',
'C:\\Anaconda\\scripts',
'C:\\Anaconda\\lib\\site-packages\\distribute-0.6.45-py2.7.egg',
'C:\\Anaconda',
'C:\\Users\\btibert\\ C:\\Anaconda\\Scripts',
'C:\\Anaconda\\python27.zip',
'C:\\Anaconda\\DLLs',
'C:\\Anaconda\\lib',
'C:\\Anaconda\\lib\\plat-win',
'C:\\Anaconda\\lib\\lib-tk',
'C:\\Users\\btibert\\AppData\\Roaming\\Python\\Python27\\site-packages',
'C:\\Users\\btibert\\AppData\\Roaming\\Python\\Python27\\site-packages\\Orange\\orng',
'C:\\Users\\btibert\\AppData\\Roaming\\Python\\Python27\\site-packages\\setuptools-0.6c11-py2.7.egg-info',
'C:\\Anaconda\\lib\\site-packages',
'C:\\Anaconda\\lib\\site-packages\\PIL',
'C:\\Anaconda\\lib\\site-packages\\win32',
'C:\\Anaconda\\lib\\site-packages\\win32\\lib',
'C:\\Anaconda\\lib\\site-packages\\Pythonwin',
'C:\\Users\\btibert\\AppData\\Roaming\\Python\\Python27\\site-packages\\IPython\\extensions']
And here is the error:
C:\Users\btibert>ipython notebook
Traceback (most recent call last):
File "C:\Anaconda\Scripts\ipython-script.py", line 5, in <module>
sys.exit(launch_new_instance())
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\frontend\terminal\ipapp.py", line 402, in
launch_new_instance
app.initialize()
File "<string>", line 2, in initialize
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\config\application.py", line 84, in catch
_config_error
return method(app, *args, **kwargs)
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\frontend\terminal\ipapp.py", line 302, in
initialize
super(TerminalIPythonApp, self).initialize(argv)
File "<string>", line 2, in initialize
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\config\application.py", line 84, in catch
_config_error
return method(app, *args, **kwargs)
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\core\application.py", line 325, in initia
lize
self.parse_command_line(argv)
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\frontend\terminal\ipapp.py", line 297, in
parse_command_line
return super(TerminalIPythonApp, self).parse_command_line(argv)
File "<string>", line 2, in parse_command_line
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\config\application.py", line 84, in catch
_config_error
return method(app, *args, **kwargs)
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\config\application.py", line 413, in pars
e_command_line
return self.initialize_subcommand(subc, subargv)
File "<string>", line 2, in initialize_subcommand
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\config\application.py", line 84, in catch
_config_error
return method(app, *args, **kwargs)
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\config\application.py", line 349, in init
ialize_subcommand
subapp = import_item(subapp)
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\utils\importstring.py", line 40, in impor
t_item
module = __import__(package,fromlist=[obj])
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\IPython\frontend\html\notebook\notebookapp.py", l
ine 34, in <module>
from zmq.eventloop import ioloop
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\zmq\eventloop\__init__.py", line 3, in <module>
from zmq.eventloop.ioloop import IOLoop
File "C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\zmq\eventloop\ioloop.py", line 56, in <module>
from zmq.eventloop.platform.auto import set_close_exec, Waker
ImportError: No module named platform.auto
Answer: It would be helpful to know what your `sys.path` is. You can find that by
doing:
$ ipython
In [1]: import sys
In [2]: sys.path
And then share here the output. Next, you want to check what files you have in
this directory:
C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages\zmq\eventloop\platform
Ideally, you'll see `auto.py` there, and if
`C:\Users\btibert\AppData\Roaming\Python\Python27\site-packages` is in your
sys.path then it is a mystery why it isn't working, but if that file isn't
there, the directory doesn't exist, or the path to `site-packages` isn't in
your `sys.path`, then those need to be resolved first.
Let us know and we can try to take it from there!
|
taking mean of data read in 'error cannot perform reduce with flexible type' python
Question: I am trying to read in data from a text file and take the mean of this data,
but I am getting the error cannot perform reduce with flexible type. I dont
know why, can somebody please help. here is my code.
right=open('01phi.txt','r').readlines()
right=str(right)
a=np.asarray(right)
b=np.mean(a)
print b
**EDIT** : I am now using this line `right=np.genfromtxt('01phi.txt')` but it
produces this error `Line #10 (got 3 columns instead of 7)` as this line in
the array is not as big. [Using genfromtxt to import csv data with missing
values in numpy](http://stackoverflow.com/questions/3761103/using-genfromtxt-
to-import-csv-data-with-missing-values-in-numpy) this link tells my how to
ignore the bottom line or how to fill it in but both of these methods would
sque the mean. is there a way to get around this?
Answer: `right` is a string. `np.asarray(some_string)` returns an array with string
dtype. NumPy's `np.mean` function raises a TypeError when passed an array of
string dtype.
In [29]: np.asarray('1 2 3')
Out[29]:
array('1 2 3',
dtype='|S5')
In [31]: np.mean(a)
TypeError: cannot perform reduce with flexible type
Instead, use
[np.genfromtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html)
or
[np.loadtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy.loadtxt)
to load an array from a text file:
a = np.genfromtxt(filename, ...)
|
Process xml input with python regex
Question: I need to clean up an xml file before I can process it. The file has junk at
the start and end, and then junk in between elements. Here is an example file:
junkjunkjunkjunk<root>
\par junkjunkjunkjunkjunk<level1>useful info to keep</level1>
</root>
junkjunkjunkjunk
How do I use regex to cut out (with replace?) the start and end junk, and then
the middle junk? The middle junk always starts with "\par ...".
Answer: The following statements should remove the junk (assuming your document is
stored in a variable called `xml`):
import re
xml = re.sub(r'.*<root>', '<root>', xml, flags=re.DOTALL) # Remove leading junk
xml = re.sub(r'\\par[^<]*<', '<', xml) # Middle junk
xml = re.sub(r'</root>.*', '</root>', xml, flags=re.DOTALL) # Trailing junk
Note that this assumes you know the name of the root element (and in this
case, it's called `root`), otherwise you may need to adjust this slightly.
|
Python 3 script using libnotify fails as cron job
Question: I've got a Python 3 script that gets some JSON from a URL, processes it, and
notifies me if there's any significant changes to the data I get. I've tried
using [notify2](https://pypi.python.org/pypi/notify2) and
[PyGObject](https://live.gnome.org/PyGObject/)'s libnotify bindings
(gi.repository.Notify) and get similar results with either method. This script
works a-ok when I run it from a terminal, but chokes when cron tries to run
it.
import notify2
from gi.repository import Notify
def notify_pygobject(new_stuff):
Notify.init('My App')
notify_str = '\n'.join(new_stuff)
print(notify_str)
popup = Notify.Notification.new('Hey! Listen!', notify_str,
'dialog-information')
popup.show()
def notify_notify2(new_stuff):
notify2.init('My App')
notify_str = '\n'.join(new_stuff)
print(notify_str)
popup = notify2.Notification('Hey! Listen!', notify_str,
'dialog-information')
popup.show()
Now, if I create a script that calls `notify_pygobject` with a list of
strings, cron throws this error back at me via the mail spool:
Traceback (most recent call last):
File "/home/p0lar_bear/Documents/devel/notify-test/test1.py", line 3, in <module>
main()
File "/home/p0lar_bear/Documents/devel/notify-test/test1.py", line 4, in main
testlib.notify(notify_projects)
File "/home/p0lar_bear/Documents/devel/notify-test/testlib.py", line 8, in notify
popup.show()
File "/usr/lib/python3/dist-packages/gi/types.py", line 113, in function
return info.invoke(*args, **kwargs)
gi._glib.GError: Error spawning command line `dbus-launch --autolaunch=776643a88e264621544719c3519b8310 --binary-syntax --close-stderr': Child process exited with code 1
...and if I change it to call `notify_notify2()` instead:
Traceback (most recent call last):
File "/home/p0lar_bear/Documents/devel/notify-test/test2.py", line 3, in <module>
main()
File "/home/p0lar_bear/Documents/devel/notify-test/test2.py", line 4, in main
testlib.notify(notify_projects)
File "/home/p0lar_bear/Documents/devel/notify-test/testlib.py", line 13, in notify
notify2.init('My App')
File "/usr/lib/python3/dist-packages/notify2.py", line 93, in init
bus = dbus.SessionBus(mainloop=mainloop)
File "/usr/lib/python3/dist-packages/dbus/_dbus.py", line 211, in __new__
mainloop=mainloop)
File "/usr/lib/python3/dist-packages/dbus/_dbus.py", line 100, in __new__
bus = BusConnection.__new__(subclass, bus_type, mainloop=mainloop)
File "/usr/lib/python3/dist-packages/dbus/bus.py", line 122, in __new__
bus = cls._new_for_bus(address_or_type, mainloop=mainloop)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NotSupported: Unable to autolaunch a dbus-daemon without a $DISPLAY for X11
I did some research and saw suggestions to put a `PATH=` into my crontab, or
to export `$DISPLAY` (I did this within the script by calling
`os.system('export DISPLAY=:0')`) but neither resulted in any change...
Answer: You are in the right track. This behavior is because cron is run in a
multiuser headless environment (think of it as running as root in a terminal
without GUI, kinda), so he doesn't know to what display (X Window Server
session) and user target to. If your application open, for example, windows or
notification to some user desktop, then this problems is raised.
I suppose you edit your cron with `crontab -e` and the entry looks like this:
`m h dom mon dow command`
Something like:
`0 5 * * 1 /usr/bin/python /home/foo/myscript.py`
Note that I use full path to Python, is better if this kind of situation where
PATH environment variable could be different.
Then just change to:
`0 5 * * 1 export DISPLAY=:0 && /usr/bin/python /home/foo/myscript.py`
If this still doesn't work you need to allow your user to control the X
Windows server:
Add to your `.bash_rc`:
`xhost +si:localuser:$(whoami)`
|
How would I go about improving/making this run faster?
Question: I'm a beginner in Python trying to get better, and I stumbled across the
following exercise:
> Let n be an integer greater than 1 and s(n) the sum of the dividors of n.
> For example,
>
>
> s(12) 1 + 2 + 3 + 4 + 6 + 12 = 28
>
>
> Also,
>
>
> s(s(12)) = s(28) = 1 + 2 + 4 + 7 + 14 + 28 = 56
>
>
> And
>
>
> s(s(s(12))) = s(56) = 1 + 2 + 4 + 7 + 8 + 14 + 28 + 56 = 120
>
>
> We use the notations:
>
>
> s^1(n) = s(n)
> s^2(n) = s(s(n))
> s^3(n) = s(s(s(n)))
> s^ m (n) = s(s(. . .s(n) . . .)), m times
>
>
> For the integers n for which exists a positive integer k so that
>
>
> s^m(n) = k * n
>
>
> are called (m, k)-perfect, for instance 12 is (3, 10)-perfect since s^3(12)
> = s(s(s(12))) = 120 = 10 * 12
>
> Special categories:
>
> For m =1 we have multiperfect numbers
>
> A special case of the above exist for m = 1 and k = 2 which are called
> perfect numbers.
>
> For m = 2 and k = 2 we have superperfect numbers.
>
> Write a program which finds and prints all (m, k)-perfect numbers for m <=
> MAXM, which are less or equal to (<=) MAXNUM. If an integer belongs to one
> of the special categories mentioned above the program should print a
> relevant message. Also, the program has to print how many different (m,
> k)-perfect numbers were found, what percentage of the tested numbers they
> were, in how many occurrences for the different pairs of (m, k), and how
> many from each special category were found(perfect numbers are counted as
> multiperfect as well).
Here's my code:
import time
start_time = time.time()
def s(n):
tsum = 0
i = 1
con = n
while i < con:
if n % i == 0:
temp = n / i
tsum += i
if temp != i:
tsum += temp
con = temp
i += 1
return tsum
#MAXM
#MAXNUM
i = 2
perc = 0
perc1 = 0
perf = 0
multperf = 0
supperf = 0
while i <= MAXNUM:
pert = perc1
num = i
for m in xrange(1, MAXM + 1):
tsum = s(num)
if tsum % i == 0:
perc1 += 1
k = tsum / i
mes = "%d is a (%d-%d)-perfect number" % (i, m, k)
if m == 1:
multperf += 1
if k == 2:
perf += 1
print mes + ", that is a perfect number"
else:
print mes + ", that is a multiperfect number"
elif m == 2 and k == 2:
supperf += 1
print mes + ", that is a superperfect number"
else:
print mes
num = tsum
i += 1
if pert != perc1: perc += 1
print "Found %d distinct (m-k)-perfect numbers (%.5f per cent of %d ) in %d occurrences" % (
perc, float(perc) / MAXNUM * 100, MAXNUM, perc1)
print "Found %d perfect numbers" % perf
print "Found %d multiperfect numbers (including perfect numbers)" % multperf
print "Found %d superperfect numbers" % supperf
print time.time() - start_time, "seconds"
It works fine, but I would like suggestions on how to make it run faster. For
instance is it faster to use
I = 1
while I <= MAXM:
…..
I += 1
instead of
for I in xrange(1, MAXM + 1)
Would it be better if instead of defining s(n) as a function I put the code
into the main program? etc. If you have anything to suggest for me to read on
how to make a program run faster, I'd appreciate it. And one more thing,
originally the exercise required the program to be in C (which I don't know),
having written this in Python, how difficult would it be for it to be made
into C?
Answer: The biggest improvements come from using a better algorithm. Things like
> Would it be better if instead of defining `s(n)` as a function I put the
> code into the main program?
or whether to use a `while` loop instead of `for i in xrange(1, MAXM + 1):`
don't make much difference, so should not be considered before one has reached
a state where algorithmic improvements are at least _very_ hard to come by.
So let's take a look at your algorithm and how we can drastically improve it
without caring about minuscule things like whether a `while` loop or a `for`
iteration are faster.
def s(n):
tsum = 0
i = 1
con = n
while i < con:
if n % i == 0:
temp = n / i
tsum += i
if temp != i:
tsum += temp
con = temp
i += 1
return tsum
That already contains a good idea, you know that the divisors of `n` come in
pairs and add both divisors once you found the smaller of the pair. You even
correctly handle squares.
It works very well for numbers like 120: when you find the divisor 2, you set
the stop condition to 60, when you find 3, to 40, ..., when you find 8, you
set it to 15, when you find 10, you set it to 12, and then you have only the
division by 11, and stop when `i` is incremented to 12. Not bad.
But it doesn't work so well when `n` is a prime, then `con` will never be set
to a value smaller than `n`, and you need to iterate all the way to `n` before
you found the divisor sum. It's also bad for numbers of the form `n = 2*p`
with a prime `p`, then you loop to `n/2`, or `n = 3*p` (`n/3`, unless `p = 2`)
etc.
By the prime number theorem, the number of primes not exceeding `x` is
asymptotically `x/log x` (where `log` is the natural logarithm), and you have
a lower bound of
Ω(MAXNUM² / log MAXNUM)
just for computing the divisor sums of the primes. That's not good.
Since you already consider the divisors of `n` in pairs `d` and `n/d`, note
that the smaller of the two (ignoring the case `d = n/d` when `n` is a square
for the moment) is smaller than the square root of `n`, so once the test
divisor has reached the square root, you know that you have found and added
all divisors, and you're done. Any further looping is futile wasted work.
So let us consider
def s(n):
tsum = 0
root = int(n**0.5) # floor of the square root of n, at least for small enough n
i = 1
while i < root + 1:
if n % i == 0:
tsum += i + n/i
i += 1
# check whether n is a square, if it is, we have added root twice
if root*root == n:
tsum -= root
return tsum
as a first improvement. Then you always loop to the square root, and computing
`s(n)` for `1 <= n <= MAXNUM` is `Θ(MAXNUM^1.5)`. That's already quite an
improvement. (Of course, you have to compute the iterated divisor sums, and
`s(n)` can be larger than `MAXNUM` for some `n <= MAXNUM`, so you can't infer
a complexity bound of `O(MAXM * MAXNUM^1.5)` for the total algorithm from
that. But `s(n)` cannot be very much larger, so the complexity can't be much
worse either.)
But we can still improve on that by using what
[twalberg](http://stackoverflow.com/users/1253222/twalberg)
[suggested](http://stackoverflow.com/questions/17279480/how-would-i-go-about-
improving-making-this-run-faster#comment25052120_17279480), using the prime
factorisation of `n` to compute the divisor sum.
First, if `n = p^k` is a prime power, the divisors of `n` are `1, p, p², ...,
p^k`, and the divisor sum is easily computed (a closed formula for the
geometric sum is
(p^(k+1) - 1) / (p - 1)
but whether one uses that or adds the `k+1` powers of `p` dividing `n` is not
important).
Next, if `n = p^k * m` with a prime `p` and an `m` such that `p` does not
divide `m`, then
s(n) = s(p^k) * s(m)
An easy way to see that decomposition is to write each divisor `d` of `n` in
the form `d = p^a * g` where `p` does not divide `g`. Then `p^a` must divide
`p^k`, i.e. `a <= k`, and `g` must divide `m`. Conversely, for every `0 <= a
<= k` and every `g` dividing `m`, `p^a * g` is a divisor of `n`. So we can lay
out the divisors of `n` (where `1 = g_1 < g_2 < ... < g_r = m` are the
divisors of `m`)
1*g_1 1*g_2 ... 1*g_r
p*g_1 p*g_2 ... p*g_r
: : :
p^k*g_1 p^k*g_2 ... p^k*g_r
and the sum of each row is `p^a * s(m)`.
If we have a list of primes handy, we can then write
def s(n):
tsum = 1
for p in primes:
d = 1
# divide out all factors p of n
while n % p == 0:
n = n//p
d = p*d + 1
tsum *= d
if p*p > n: # n = 1, or n is prime
break
if n > 1: # one last prime factor to account for
tsum *= 1 + n
return tsum
The trial division goes to the second largest prime factor of `n` [if `n` is
composite] or the square root of the largest prime factor of `n`, whichever is
larger. It has a worst-case bound for the largest divisor tried of `n**0.5`,
which is reached for primes, but for most composites, the division stops much
earlier.
If we don't have a list of primes handy, we can replace the line `for p in
primes:` with `for p in xrange(2, n):` [the upper limit is not important,
since it is never reached if it is larger than `n**0.5`] and get a not too
much slower factorisation. (But it can easily be sped up a lot by avoiding
even trial divisors larger than 2, that is using a list `[2] + [3,5,7...]` \-
best as a generator - for the divisors, even more by also skipping multiples
of 3 (except 3), `[2,3] + [5,7, 11,13, 17,19, ...]` and if you want of a few
further small primes.)
Now, that helped, but computing the divisor sums for all `n <= MAXNUM` still
takes `Ω(MAXNUM^1.5 / log MAXNUM)` time (I haven't analysed, that could be
also an upper bound, or the `MAXNUM^1.5` could still be a lower bound, anyway,
a logarithmic factor rarely makes much of a difference [beyond a constant
factor]).
And you compute a lot of divisor sums more than once (in your example, you
compute `s(56)` when investigating 12, again when investigating 28, again when
investigating 56). To alleviate the impact of that, memoizing `s(n)` would be
a good idea. Then you need to compute each `s(n)` only once.
And now we have already traded space for time, so we can use a better
algorithm to compute the divisor sums for all `1 <= n <= MAXNUM` in one go,
with a better time complexity (and also smaller constant factors). Instead of
trying out each small enough (prime) number whether it divides `n`, we can
directly mark only multiples, thus avoiding all divisions that leave a
remainder - which is the vast majority.
The easy method to do that is
def divisorSums(n):
dsums = [0] + [1]*n
for k in xrange(2, n+1):
for m in xrange(k, n+1, k):
dsums[m] += k
return dsums
with an `O(n * log n)` time complexity. You can do it a bit better (`O(n * log
log n)` complexity) by using the prime factorisation, but that method is
somewhat more complicated, I'm not adding it now, maybe later.
Then you can use the list of all divisor sums to look up `s(n)` if `n <=
MAXNUM`, and the above implementation of `s(n)` to compute the divisor sum for
values larger than `MAXNUM` [or you may want to memoize the values up to a
larger limit].
dsums = divisorSums(MAXNUM)
def memo_s(n):
if n <= MAXNUM:
return dsums[n]
return s(n)
* * *
That's not too shabby,
Found 414 distinct (m-k)-perfect numbers (0.10350 per cent of 400000 ) in 496 occurrences
Found 4 perfect numbers
Found 8 multiperfect numbers (including perfect numbers)
Found 7 superperfect numbers
12.709428072 seconds
for
import time
start_time = time.time()
def s(n):
tsum = 1
for p in xrange(2,n):
d = 1
# divide out all factors p of n
while n % p == 0:
n = n//p
d = p*d + 1
tsum *= d
if p*p > n: # n = 1, or n is prime
break
if n > 1: # one last prime factor to account for
tsum *= 1 + n
return tsum
def divisorSums(n):
dsums = [0] + [1]*n
for k in xrange(2, n+1):
for m in xrange(k, n+1, k):
dsums[m] += k
return dsums
MAXM = 6
MAXNUM = 400000
dsums = divisorSums(MAXNUM)
def memo_s(n):
if n <= MAXNUM:
return dsums[n]
return s(n)
i = 2
perc = 0
perc1 = 0
perf = 0
multperf = 0
supperf = 0
while i <= MAXNUM:
pert = perc1
num = i
for m in xrange(1, MAXM + 1):
tsum = memo_s(num)
if tsum % i == 0:
perc1 += 1
k = tsum / i
mes = "%d is a (%d-%d)-perfect number" % (i, m, k)
if m == 1:
multperf += 1
if k == 2:
perf += 1
print mes + ", that is a perfect number"
else:
print mes + ", that is a multiperfect number"
elif m == 2 and k == 2:
supperf += 1
print mes + ", that is a superperfect number"
else:
print mes
num = tsum
i += 1
if pert != perc1: perc += 1
print "Found %d distinct (m-k)-perfect numbers (%.5f per cent of %d ) in %d occurrences" % (
perc, float(perc) / MAXNUM * 100, MAXNUM, perc1)
print "Found %d perfect numbers" % perf
print "Found %d multiperfect numbers (including perfect numbers)" % multperf
print "Found %d superperfect numbers" % supperf
print time.time() - start_time, "seconds"
By memoizing also the needed divisor sums for `n > MAXNUM`:
d = {}
for i in xrange(1, MAXNUM+1):
d[i] = dsums[i]
def memo_s(n):
if n in d:
return d[n]
else:
t = s(n)
d[n] = t
return t
the time drops to
3.33684396744 seconds
|
Python: Trying to set attributes of a class instance from output of another class instance
Question: I have list of content block 'instances' which as the list is processed the
content for each block is generated in an instance of a content type class (if
that makes sense).
As I iterate through the list I am trying to set the attributes of the modules
instance with output from an instance of the named module from extra_modules.
If there is a better way to to write this question please feel free to edit.
The following is just an example of the testing code I'm trying to run using
the Python Bottle framework. I'm trying to get a test output to begin with
before I actually put content generating code into the photoGallery class.
core.py:
import extra_modules
module_blocks_in_db = [
# module-ID, module-sys-name, module-sys-desc, module-function, module-variables
[1, 'photo_gallery_main', 'A little intro gallery', 'photoGallery', '{"images": ["photo1.jpg", "photo2.jpg", "photo3.jpg"]}'],
]
class moduleBlocks:
def __init__(self, mbidb):
for i in mbidb:
setattr(self, i[1], getattr(extra_modules, i[3])(i[4]))
@route('/')
def home():
page_id = 1
modules = moduleBlocks(module_blocks_in_db)
return modules.photo_gallery_main
extra_modules.py:
class photoGallery:
def __init__(self, *args):
self.output = 'Output from photoGallery class instance'
return self.output
This is the error I'm getting from Bottle's development server:
File "core.py", line 46, in __init__
setattr(self, i[1], getattr(extra_modules, i[3])(i[4]))
TypeError: __init__() should return None
I'm really not understanding this error well and the more I'm looking at the
code the more I'm confusing myself. I've tried several different ways now to
grab output from a class instance and assign it as an attribute of the
moduleBlocks class in my example. Where am I going wrong with this?
EDIT: I have now changed my setattr line to two separate lines and got rid of
the return output in the extra_modules photoGallery class and things are now
working fine, thanks:
x = getattr(extra_modules, i[3])(i[4])
setattr(self, i[1], x.output)
Answer: The following is incorrect:
class photoGallery:
def __init__(self, *args):
self.output = 'Output from photoGallery class instance'
return self.output
"**__init_ _**" is the constructor for photoGallery which has the
responsibility of initialising the photoGallery object. As such it doesn't
make sense for it to to return anything. Get rid of return self.output and try
again
|
Can distutils install the module/package as an executable script?
Question: I'm using distutils.core.setup for the first time. I got it to install my
module in /usr/lib/python/site-packages.
If I run python from any directory and do `import my_module` it all works
great.
However, I need to run my module as script. It's not intended as a library,
but rather as an application. If I run from terminal `python my_module` it
does not find the file.
I wanted to make an executable script that will run my module and put a sym
link to it in /usr/bin, but that seems like a hacky way to solve this. I
presume distutils has something to install your module as an executable
script, except I wasn't able to find it. Could someone please point me to an
example or doc file for this?
Edit: Also, if this is not the right way to distribute a python application,
what should I use instead?
Answer: Use distutils.core.setup(scripts=['myprogram']) instead of
py_modules=['mymodule.py']
|
How do I log in to my online bank account and print the transaction history?
Question: I want to log in to my online bank account and print the transaction history.
I'm using an alternative to
[mechanize](http://wwwsearch.sourceforge.net/mechanize/) called
[Splinter](http://splinter.cobrateam.info/) because it's much easier to use
and more clearly documented.
The code I wrote gives me an error when trying to fill the password form. I
can't seem to successfully identify the password form field. Since it doesn't
have a "name=" attribute or a css class attribute.
Here's the code:
username2 = '***'
password2 = '***'
browser2 = Browser()
browser2.visit('https://mijn.ing.nl/internetbankieren/SesamLoginServlet')
browser2.find_by_css('.firstfield').fill(username2)
browser2.find_by_id('#ewyeszipl').fill(password2)
browser2.click_link_by_text('Inloggen')
url2 = browser2.url
title2 = browser2.title
titlecheck2 = 'Mijn ING Overzicht - Mijn ING'
print "Stap 2 (Mijn ING):"
if title2 == titlecheck2:
print('Succeeded')
print 'The source is:'
print browser2.html
browser2.quit()
else:
print('Failed')
browser2.quit()
The full traceback:
/Library/Frameworks/Python.framework/Versions/2.7/bin/python "/Users/*/Dropbox/Python/Test environment 2.7.3/Splinter.py"
Traceback (most recent call last):
File "/Users/*/Dropbox/Python/Test environment 2.7.3/Splinter.py", line 45, in <module>
browser2.find_by_id('#ewyeszipl').fill_form(password2)
File "/Users/*/Library/Python/2.7/lib/python/site-packages/splinter/element_list.py", line 73, in __getattr__
self.__class__.__name__, name))
AttributeError: 'ElementList' object has no attribute 'fill_form'
Process finished with exit code 1
Answer: Problem solved with the help of Miklos.
Here's the working code:
from splinter import *
# Define the username and password
username2 = '***'
password2 = '***'
# Choose the browser (default is Firefox)
browser2 = Browser()
# Fill in the url
browser2.visit('https://mijn.ing.nl/internetbankieren/SesamLoginServlet')
# Find the username form and fill it with the defined username
browser2.find_by_id('gebruikersnaam').first.find_by_tag('input').fill(username2)
# Find the password form and fill it with the defined password
browser2.find_by_id('wachtwoord').first.find_by_tag('input').fill(password2)
# Find the submit button and click
browser2.find_by_css('.submit').first.click()
# Print the current url
print browser2.url
# Print the current browser title
print browser2.title
# Print the current html source code
print browser2.html
|
Python - Search for hex value marker and extract data
Question: I am new to python and have tried searching for help prior to posting.
I have binary file that contains a number of values I need to parse. Each
value has a hex header of two bytes and a third byte that gives a size of the
data in that record to parse. The following is an example:
\x76\x12\x0A\x08\x00\x00\x00\x00\x00\x00\x00\x00
The `\x76\x12` is the record marker and `\x0A` is the number of bytes to be
read next.
This data always has the two byte marker and a third byte size. However the
data to be parsed is variable and the record marker increments as follows:
`\x76\x12` and `\x77\x12` and so on until `\x79\x12` where is starts again.
This is just example data for the use of this posting.
Many Thanks for any help or pointers.
Answer: Is something like this what you want?
>>> b = b'\x76\x12\x0A\x08\x00\x00\x00\x00\x00\x00\x00\x00'
>>> from StringIO import StringIO
>>> io = StringIO(b)
>>> io.seek(0)
>>> io.read(2) #read 2 bytes, maybe validate?
'v\x12'
>>> import struct
>>> nbytes = struct.unpack('B',io.read(1))
>>> print nbytes
(10,)
>>> data = io.read(nbytes[0])
>>> data
'\x08\x00\x00\x00\x00\x00\x00\x00\x00'
|
Can socket objects be shared with Python's multiprocessing? socket.close() does not seem to be working
Question: I'm writing a server which uses multiprocessing.Process for each client.
socket.accept() is being called in a parent process and the connection object
is given as an argument to the Process.
The problem is that when calling socket.close() the socket does not seem to be
closing. The client's recv() should return immediately after close() has been
called on the server. This is the case when using threading.Thread or just
handle the requests in the main thread, however when using multiprocessing,
the client's recv seem to be hanging forever.
[Some sources](http://stackoverflow.com/a/8686107/1132184) indicate that
socket objects should be shared as handles with multiprocessing.Pipes and
multiprocess.reduction but it does not seem to make a difference.
EDIT: I am using Python 2.7.4 on Linux 64 bit .
Below are the sample implementation demonstrating this issue.
# server.py
import socket
from multiprocessing import Process
#from threading import Thread as Process
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 5001))
s.listen(5)
def process(s):
print "accepted"
s.close()
print "closed"
while True:
print "accepting"
c, _ = s.accept()
p = Process(target=process, args=(c,))
p.start()
print "started process"
# client.py
import socket
s = socket.socket()
s.connect(('', 5001))
print "connected"
buf = s.recv(1024)
print "buf: '" + buf +"'"
s.close()
Answer: The problem is that the socket is not closed in the parent process. Therefore
it remains open, and causes the symptom you are observing.
Immediately after forking off the child process to handle the connection, you
should close the parent process' copy of the socket, like so:
while True:
print "accepting"
c, _ = s.accept()
p = Process(target=process, args=(c,))
p.start()
print "started process"
c.close()
|
Working with large primes in Python
Question: What is an efficient way for working with large prime numbers with Python? You
search on here or on google, and you find many different methods for doing
so... sieves, primality test algorithms... Which ways work for larger primes?
Answer: For determining if a number is a prime, there a sieves and primality tests.
# for large numbers, xrange will throw an error.
# OverflowError: Python int too large to convert to C long
# to get over this:
def mrange(start, stop, step):
while start < stop:
yield start
start += step
# benchmarked on an old single-core system with 2GB RAM.
from math import sqrt
def is_prime(num):
if num == 2:
return True
if (num < 2) or (num % 2 == 0):
return False
return all(num % i for i in mrange(3, int(sqrt(num)) + 1, 2))
# benchmark is_prime(100**10-1) using mrange
# 10000 calls, 53191 per second.
# 60006 function calls in 0.190 seconds.
This seems to be the fastest. There is another version using `not any` that
you see,
def is_prime(num)
# ...
return not any(num % i == 0 for i in mrange(3, int(sqrt(num)) + 1, 2))
However, in the benchmarks I got `70006 function calls in 0.272 seconds.` over
the use of `all` `60006 function calls in 0.190 seconds.` while testing if
`100**10-1` was prime.
If you're needing to find the next highest prime, this method will not work
for you. You need to go with a primality test, I have found the [Miller-
Rabin](http://en.wikipedia.org/wiki/Miller-Rabin_primality_test) algorithm to
be a good choice. It is a little slower the
[Fermat](http://en.wikipedia.org/wiki/Fermat_primality_test) method, but more
accurate against pseudoprimes. Using the above mentioned method takes +5
minutes on this system.
`Miller-Rabin` algorithm:
from random import randrange
def is_prime(n, k=10):
if n == 2:
return True
if not n & 1:
return False
def check(a, s, d, n):
x = pow(a, d, n)
if x == 1:
return True
for i in xrange(s - 1):
if x == n - 1:
return True
x = pow(x, 2, n)
return x == n - 1
s = 0
d = n - 1
while d % 2 == 0:
d >>= 1
s += 1
for i in xrange(k):
a = randrange(2, n - 1)
if not check(a, s, d, n):
return False
return True
`Fermat` algoithm:
def is_prime(num):
if num == 2:
return True
if not num & 1:
return False
return pow(2, num-1, num) == 1
To get the next highest prime:
def next_prime(num):
if (not num & 1) and (num != 2):
num += 1
if is_prime(num):
num += 1
while True:
if is_prime(num):
break
num += 2
return num
print next_prime(100**10-1) # returns `100000000000000000039`
# benchmark next_prime(100**10-1) using Miller-Rabin algorithm.
1000 calls, 337 per second.
258669 function calls in 2.971 seconds
Using the `Fermat` test, we got a benchmark of `45006 function calls in 0.885
seconds.`, but you run a higher chance of pseudoprimes.
So, if just needing to check if a number is prime or not, the first method for
`is_prime` works just fine. It is the fastest, if you use the `mrange` method
with it.
Ideally, you would want to store the primes generated by `next_prime` and just
read from that.
For example, using `next_prime` with the `Miller-Rabin` algorithm:
print next_prime(10^301)
# prints in 2.9s on the old single-core system, opposed to fermat's 2.8s
1000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000531
You wouldn't be able to do this with `return all(num % i for i in mrange(3,
int(sqrt(num)) + 1, 2))` in a timely fashion. I can't even do it on this old
system.
And to be sure that `next_prime(10^301)` and `Miller-Rabin` yields a correct
value, this was also tested using the `Fermat` and the `Solovay-Strassen`
algorithms.
See: [fermat.py](https://gist.github.com/bnlucas/5857437),
[miller_rabin.py](https://gist.github.com/bnlucas/5857478), and
[solovay_strassen.py](https://gist.github.com/bnlucas/5857525) on
_gist.github.com_
|
Python xml : list all elements in item
Question: I need to list all elements in my `<product>` item, because the elements of
`<product>` is variable.
XML file :
<catalog>
<product>
<element1>text 1</element1>
<element2>text 2</element2>
<element..>text ..</element..>
</produc>
</catalog>
Python parser : I use fast_iter because my xml file is large...
import lxml.etree as etree
import configs.application as configs
myfile = configs.application.tmp + '/xml_hug_file.xml'
def fast_iter(context, func, *args, **kwargs):
for event, elem in context:
func(elem, *args, **kwargs)
elem.clear()
while elem.getprevious() is not None:
del elem.getparent()[0]
del context
def process_element(catalog):
print("List all element of <product>")
context = etree.iterparse(myfile, tag='catalog', events = ('end', ))
fast_iter(context, process_element)
Answer: You could use the XPath `'product/*[starts-with(local-name(),"element")]'`:
* * *
import lxml.etree as ET
import io
content = '''\
<catalog>
<product>
<element1>text 1</element1>
<element2>text 2</element2>
<element3>text ..</element3>
</product>
</catalog>'''
def fast_iter(context, func, *args, **kwargs):
"""
http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
Author: Liza Daly
See also http://effbot.org/zone/element-iterparse.htm
"""
for event, elem in context:
func(elem, *args, **kwargs)
# It's safe to call clear() here because no descendants will be
# accessed
elem.clear()
# Also eliminate now-empty references from the root node to elem
for ancestor in elem.xpath('ancestor-or-self::*'):
while ancestor.getprevious() is not None:
del ancestor.getparent()[0]
del context
def process_element(catalog):
for elt in catalog.xpath('product/*[starts-with(local-name(),"element")]'):
print(elt)
context = ET.iterparse(io.BytesIO(content), tag='catalog', events = ('end', ))
fast_iter(context, process_element)
yields
<Element element1 at 0xb7449374>
<Element element2 at 0xb744939c>
<Element element3 at 0xb74493c4>
* * *
By the way, I made an alteration to Liz Daly's fast_iter, which will delete
more elements as they become unused. This should reduce memory requirements
when parsing large XML files.
Here is a example which shows how the modified `fast_iter` above removes more
elements than the original `fast_iter`:
import logging
import textwrap
import lxml.etree as ET
import io
logger = logging.getLogger(__name__)
level = logging.INFO
# level = logging.DEBUG # uncomment to see more debugging information
logging.basicConfig(level=level)
def fast_iter(context, func, *args, **kwargs):
"""
http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
Author: Liza Daly
See also http://effbot.org/zone/element-iterparse.htm
"""
for event, elem in context:
logger.debug('Processing {e}'.format(e=ET.tostring(elem)))
func(elem, *args, **kwargs)
# It's safe to call clear() here because no descendants will be
# accessed
logger.debug('Clearing {e}'.format(e=ET.tostring(elem)))
elem.clear()
# Also eliminate now-empty references from the root node to elem
for ancestor in elem.xpath('ancestor-or-self::*'):
logger.debug('Checking ancestor: {a}'.format(a=ancestor.tag))
while ancestor.getprevious() is not None:
logger.info('Deleting {p}'.format(
p=(ancestor.getparent()[0]).tag))
del ancestor.getparent()[0]
del context
def orig_fast_iter(context, func, *args, **kwargs):
for event, elem in context:
logger.debug('Processing {e}'.format(e=ET.tostring(elem)))
func(elem, *args, **kwargs)
logger.debug('Clearing {e}'.format(e=ET.tostring(elem)))
elem.clear()
while elem.getprevious() is not None:
logger.info('Deleting {p}'.format(
p=(elem.getparent()[0]).tag))
del elem.getparent()[0]
del context
def setup_ABC():
content = textwrap.dedent('''\
<root>
<A1>
<B1></B1>
<C>1<D1></D1></C>
<E1></E1>
</A1>
<A2>
<B2></B2>
<C>2<D></D></C>
<E2></E2>
</A2>
</root>
''')
return content
content = setup_ABC()
context = ET.iterparse(io.BytesIO(content), events=('end', ), tag='C')
orig_fast_iter(context, lambda elem: None)
# DEBUG:__main__:Deleting B1
# DEBUG:__main__:Deleting B2
print('-'*80)
"""
The improved fast_iter deletes A1. The original fast_iter does not.
"""
content = setup_ABC()
context = ET.iterparse(io.BytesIO(content), events=('end', ), tag='C')
fast_iter(context, lambda elem: None)
# DEBUG:__main__:Deleting B1
# DEBUG:__main__:Deleting A1
# DEBUG:__main__:Deleting B2
Thus you see the modified `fast_iter` manages to delete the `A1` element
because it is not needed by the time the second `C` element is processed. The
original `fast_iter` only deletes parents of `C` elements (i.e. `B` elements).
You could imagine things like `A1` could be quite large in a large XML file,
and there could be many such elements. So the modified `fast_iter` will allow
reclamation of a lot of memory that the original `fast_iter` does not free.
|
What if/ should I use threading to update global variables.[pythonic way]
Question: I have a function to update a global/class variable. So, What should care
after regularly invoke such function as subthread?(in asynchronous way)
Or, any suggestions to avoid using this pattern? (the pathonic way)
import time
import threading
# through global variable or class variable
_a = 123
def update_a(): # may be called more than once
"slow updating process"
time.sleep(3)
global _a
_a += 10
return
if __name__ == '__main__':
print(_a)
th = threading.Thread(target=update_a)
th.setDaemon(True)
th.start()
print(_a)
# updating aynchrounously
time.sleep(5)
print(_a)
Answer: First of all, threads are a thing to avoid in Python altogether, but if you
really want to, I'd do it like this. First, create a thread-safe object with a
[lock](http://docs.python.org/2/library/threading.html#lock-objects):
class ThreadSafeValue(object):
def __init__(self, init):
self._value = init
self._lock = threading.Lock()
def atomic_update(self, func):
with self._lock:
self._value = func(self._value)
@property
def value(self):
return self._value
then I'd pass that to the thread target function:
def update(val):
time.sleep(3)
val.atomic_update(lambda v: v + 10)
def main():
a = ThreadSaveValue(123)
print a.value
th = threading.Thread(target=update, args=(a,))
th.daemon = True
th.start()
print a.value
th.join()
print a.value
if __name__ == '__main__':
main()
That way you will avoid global variables and ensure the thread-safety.
|
pyqt Using QDataWidgetMapper to update row in database
Question: I am trying to use the QDataWidgetmapper to update a row in the database but
my issue is when trying to call the update function row is not a global
variable and I have tried to use it in the same function that calls the
Qdialog for the input int. I cannot get it to work. I have tried many
variations but I am now at my wits end. I'm sure there is something simple I
am missing but I am still learning python and pyqt.
import sys
from testdbtableform import *
from PyQt4 import QtSql, QtGui
def createConnection():
"""Creates the pyqt connection to the database"""
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('demo.db')
if db.open():
return True
else:
print db.lastError().text()
return False
class MyForm(QtGui.QDialog):
"""Creates the class"""
def __init__(self, parent=None):
"""Initiates the class"""
QtGui.QDialog.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.model = QtSql.QSqlRelationalTableModel(self)
self.model.setTable("userlist")
self.model.setSort(0, 0)
self.model.setEditStrategy(2)
self.model.select()
self.mapper = QtGui.QDataWidgetMapper(self)
self.mapper.setSubmitPolicy(1)
self.mapper.setModel(self.model)
self.mapper.addMapping(self.ui.lineEditUser, 0)
self.mapper.addMapping(self.ui.lineEditEmail, 1)
self.ui.tableView.setModel(self.model)
self.ui.pushSearch.clicked.connect(self.dbfilter)
self.ui.Submit.clicked.connect(self.dbinput)
self.ui.pushButton.clicked.connect(self.mapindex)
self.ui.updateButton.clicked.connect(self.updaterow)
self.ui.updateButton.hide()
def mapindex(self):
"""Function called to update a row in the tableview and database"""
i, ok = QtGui.QInputDialog.getInteger(self,
"Update Row", "Row:", 1, 1, 100, 1)
row = "%d" % i
row = int(row) - 1
if ok:
self.ui.Submit.hide()
self.ui.updateButton.show()
self.mapper.setCurrentIndex(row)
def updaterow(self):
"""Function to update data from line edits to the database"""
text1 = self.ui.lineEditUser.text()
text2 = self.ui.lineEditEmail.text()
self.model.setData(self.model.index(row, 0), str(text1).upper())
self.model.setData(self.model.index(row, 1), str(text2))
self.model.submitAll()
self.ui.lineEditUser.clear()
self.ui.lineEditEmail.clear()
self.ui.Submit.show()
self.ui.updateButton.hide()
def dbinput(self):
"""Function to input data from line edits to the database"""
self.model.insertRow(0)
text1 = self.ui.lineEditUser.text()
text2 = self.ui.lineEditEmail.text()
self.model.setData(self.model.index(0, 0), str(text1).upper())
self.model.setData(self.model.index(0, 1), str(text2))
self.model.submitAll()
self.ui.lineEditUser.clear()
self.ui.lineEditEmail.clear()
def dbfilter(self):
"""Function to search through the database for the username"""
self.model.setFilter("USERNAME like '"+self.ui.lineEditSearch.text()+"%'")
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
if not createConnection():
sys.exit(1)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
Answer: Alright after banging my head against a wall for a few minutes and then just
watching random youtube videos on random things davidb from the pyqt irc
channel asked me "Is row the same as self.mapper.currentIndex()" so I chanaged
row under the update function to row = self.mapper.currentIndex() and it
worked. Something simple that I was over looking because I was getting
frustrated. Below are the correct functions.
def mapindex(self):
"""Function called to update a row in the tableview and database"""
i, ok = QtGui.QInputDialog.getInteger(self,
"Update Row", "Row:", 1, 1, 100, 1)
row = "%d" % i
row = int(row) - 1
if ok:
self.ui.Submit.hide()
self.ui.updateButton.show()
self.mapper.setCurrentIndex(row)
def updaterow(self):
"""Function to update data from line edits to the database"""
text1 = self.ui.lineEditUser.text()
text2 = self.ui.lineEditEmail.text()
row = self.mapper.currentIndex() #being the missing link
self.model.setData(self.model.index(row, 0), str(text1).upper())
self.model.setData(self.model.index(row, 1), str(text2))
self.model.submitAll()
self.ui.lineEditUser.clear()
self.ui.lineEditEmail.clear()
self.ui.Submit.show()
self.ui.updateButton.hide()
|
How to control gdb using Python subprocess.Popen?
Question: So I'm writing (or at least trying to) a program to compare the outputs of two
gdb runs in python. This is what I have so far:
from subprocess import *
import subprocess
file = raw_input('enter program name (with a ./ if in local directory): ')
p1 = Popen(['gdb', file], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = Popen(['gdb', file], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p1.communicate(input='break main')
p2.communicate(input='break main')
args1 = raw_input('args for running program (from file) (ie r < input.txt): ')
args2 = raw_input('args for running program (from file) (for program 2...): ')
p1.communicate(input=args1)
p2.communicate(input=args2)
while True:
p1out = p1.communicate(input='continue')[0]
p2out = p2.communicate(input='continue')[0]
if p1out != p2out:
print 'difference: '
print 'p1: ' + p1out
print 'p2: ' + p2out
cont = raw_input('continue (y/n): ')
if cont != 'y':
break
Now the problem is that this doesn't seem to be working. Any ideas on where I
might be going wrong?
More detail: The point of the program is to take in an executable, break at
the main function, and then run through each until the output varies between
the two. This is intended as a debugging tool (that I would use, even if no
one else would!). Then when you find a difference it gives you the choice of
whether to end the program, or to continue. In theory, this should work, but
I'm just not sure what's messing up.
Answer: `.communicate` waits for a `Popen` object to finish execution. Since you are
trying to talk to gdb while it's running, this will just hang forever. gdb
isn't going to exit without any input. Additionally you need to write the
newlines yourself to emulate the user hitting _enter_.
what you want to do is write into and read from gdb while it is executing. For
this, use `p1.stdin.write('break main\n')` (note the `'\n'`) when sending
input, and `p1.stdout.readline()` when reading output. This applies to the
break in the beginning, the args you are sending, and the continues.
On sending the arguments and beggining executing, you should also be sure to
`start` gdb.
p1.stdin.write('start ' + args1 + '\n')
p2.stdin.write('start ' + args2 + '\n')
You also want to handle the case where one process terminates before another.
You can use `Popen.poll` to check if a process has completed yet, it will
return `None` if it has not. Although this may not be exactly how you want to
handle it, you can change the top of your loop to something like this:
while True:
if p1.poll() is not None and p2.poll is not None:
print 'p1 and p2 have both finished'
break
elif p1.poll() is not None:
print 'p1 finished before p2'
break
elif p2.poll() is not None:
print 'p2 finished before p1'
break
p1.stdin.write('continue\n')
p2.stdin.write('continue\n')
p1out = p1.stdout.readline()
p2out = p2.stdout.readline()
Reading a single line will likely not be correct, and you will have to
calibrate the number of lines you read in order to get the correct output.
You should either add reads to `stderr`, or send it to `/dev/null` if you
don't care about it. If you don't do either of these, the PIPE buffer can fill
and cause it to hang.
|
Websocket/TCP proxy with autobahn and twisted
Question: I am trying to write a proxy with autobahn and twisted. When a websocket
client connects I want to open a TCP connection to a server. What I can't seem
to figure out is how to pass data received via the TCP connection back to the
websocket client.
#!/usr/bin/env python
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import Int32StringReceiver
from twisted.internet import reactor
from twisted.python import log
from autobahn.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
import sys
class ServerClient(Int32StringReceiver):
structFormat = "!I"
def __init__(self):
self.filter = "{\"exporterip\": \"1.2.3.4\"}"
def connectionMade(self):
self.sendString(self.filter)
def stringReceived(self, string):
print "Received data %s" % (string)
class ServerClientFactory(ClientFactory):
protocol = ServerClient
def clientConnectionFailed(self, connector, reason):
print 'connection failed:', reason.getErrorMessage()
reactor.stop()
def clientConnectionLost(self, connector, reason):
print 'connection lost:', reason.getErrorMessage()
reactor.stop()
class WSServerProtocol(WebSocketServerProtocol):
def onOpen(self):
print "Websocket connection opened"
tcpfactory = ServerClientFactory()
reactor.connectTCP('localhost', 9876, tcpfactory)
def onClose(self):
print "Websocket connection closed"
def onMessage(self, msg, binary):
print "Websocket message received"
def main():
log.startLogging(sys.stdout)
wsfactory = WebSocketServerFactory("ws://localhost:9000", debug = False)
wsfactory.protocol = WSServerProtocol
listenWS(wsfactory)
reactor.run()
if __name__ == '__main__':
main()
Answer: in your WSServerProtocol class, in the onMessage thread :
def onMessage(self, msg, binary):
self.sendMessage(msg)
|
Python tkinter error messages
Question: I have an application spread across several modules that consists of a main
module, a UI, a processing function and a module to hold the global variables.
I'm having problems with tkinter throwing error messages, but I don't
understand why, and I think the route cause may be unrelated to tkinter
(possibly to do with threading?).
A simplification of the application that exhibits the same issues is as
follows:
**mymain.py**
import math
import random
from Tkinter import *
from ttk import *
import tkMessageBox
import myui
import myfunction
import myglobals
root = Tk()
myglobals.ui = myui.UI(root)
root.mainloop()
**myfunction.py**
import thread
import random
import myglobals
import myui
def myfunc():
multiprint(str(random.random()))
thread.start_new_thread(myfunc,())
def multiprint(*args):
msg = ' '.join([str(arg) for arg in args])
print msg
if myglobals.ui:
myglobals.ui.writeToLog(msg)
**myui.py**
from Tkinter import *
from ttk import *
import tkMessageBox
import types
import time
import random
import myfunction
class UI:
def __init__(self, master):
self.master = master
#top frame
self.topframe = Frame(self.master)
self.topframe.pack(fill=X)
self.button = Button(self.topframe, text="Start", command=self.startgame)
self.button.pack(side=LEFT)
#event frame
self.logframe = Frame(self.master)
self.logframe.pack(fill=X)
self.logframetitle = Label(self.logframe, text="Event log:")
self.logframetitle.pack(fill=X)
self.scrollbar = Scrollbar(self.master)
self.scrollbar.pack(side=RIGHT, fill=Y)
self.log = Text(self.master, state='disabled', height=24, wrap='none', yscrollcommand=self.scrollbar.set)
self.log.pack(fill=X)
self.scrollbar.config(command=self.log.yview)
def startgame(self):
myfunction.myfunc()
def writeToLog(self,msg):
numlines = self.log.index('end').split('.')[0] #self.log.index('end - 1 line') gives the start of the last line of text
print 'The log is', numlines, 'long'
self.log['state'] = 'normal'
if self.log.index('end-1c')!='1.0':
self.log.insert('end', '\n')
time.sleep(0.1)
self.log.insert('end', msg)
self.log['state'] = 'disabled'
self.log.see('end')
def main():
root = Tk()
ui = UI(root)
root.mainloop()
if __name__ == '__main__':
main()
**myglobals.py** is a blank file that holds the variables.
The error messages I'm getting include the following:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2860, in set
self.tk.call((self._w, 'set') + args)
TclError: invalid command name "512.14"
and
Unhandled exception in thread started by <function myfunc at 0x02940A30>
Traceback (most recent call last):
File "C:\myfunction.py", line 20, in myfunc
multiprint(str(random.random()))
File "C:\myfunction.py", line 29, in multiprint
myglobals.ui.writeToLog(msg)
File "C:\myui.py", line 67, in writeToLog
self.log['state'] = 'disabled'
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1269, in __setitem__
self.configure({key: value})
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1262, in configure
return self._configure('configure', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1253, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".43240984"
I am bemused about how to understand these error messages. I've tried googling
the message codes, but haven't found anything helpful so far.
Really grateful for any assistance.
Answer: The error message mentions threads. In the stack trace it looks like you are
altering the state of a variable. If that is true, and you're trying to alter
the state of a widget from a thread other than the one that created the
widget, that's the problem. You cannot call widget methods from any thread
except the one that created the widget.
|
How do I access wity python ctypes to array values returned with a pointer from a dll coded in Delphi?
Question: I have a Delphi library that is exposing a results with a procedure like this:
procedure Script_GetFindedList(List : Pointer; out Len : Cardinal); stdcall;
var X : TArray<Cardinal>;
begin
TScriptMethod.Create(SCGetFindedList).SendExecMethod.Free;
NamedPipe.WaitForReply(Pipe_WaitDelay);
if not ResultReady then ExitProcess(0);
SetLength(X,FuncResultStream.Size div 4);
FuncResultStream.Read(X[0],FuncResultStream.Size);
Len := Length(X) * 4;
if Assigned(List) then
Move(X[0],PByteArray(List)^[0],Len);
end;
And I am able to call it from normal delphi Code like this:
function TFindEngine.GetFindedList : TArray<Cardinal>;
var BufLen : Cardinal;
begin
Script_GetFindedList(nil, BufLen);
if BufLen = 0 then Exit;
SetLength(Result,BufLen div 4);
Script_GetFindedList(PByteArray(Result), BufLen);
end;
I would like to wrap the code in Python using the ctypes library and I have
some code like this:
from ctypes import *
my_dll = windll.Script
def GetFindedList():
my_dll.Script_GetFindedList.argtypes = [POINTER(c_uint), POINTER(c_uint)]
my_dll.Script_GetFindedList.restype = None
BufLen = c_uint()
my_dll.Script_GetFindedList(None, byref(BufLen))
if BufLen.value > 0:
print("BufLen.value : {}".format(BufLen.value))
##################################################################
# alternate solution that just leaks memory while doing nothind
# buf = array('I', range(BufLen.value))
# addr, count = buf.buffer_info()
# Result = cast(addr, POINTER( (c_uint * BufLen.value) ))
Result = (c_uint * BufLen.value)()
print("Result before: {}".format(list(Result)))
my_dll.Script_GetFindedList(byref(Result), byref(BufLen))
print("Result after: {}".format(list(Result)))
return Result
else:
return []
But this is not working: I just get the correct BufLen.value but then, with
the second call to dll I am not able to populate my array. I did many similar
tries, but with no luck. Is there someone that can advise me?
Thank you.
Answer: I'd call it like this:
from ctypes import *
my_dll = windll.Script
my_dll.Script_GetFindedList.restype = None
size = c_uint()
my_dll.Script_GetFindedList(None, byref(size))
result = (c_uint*(size.value//4))()
my_dll.Script_GetFindedList(result, byref(size))
result = list(result)
This function would be much better if you return buffer length rather than
size.
I tested this using the following code:
**Delphi**
library TestDLL;
procedure Script_GetFindedList(List : Pointer; out Len : Cardinal); stdcall;
var
X: TArray<Cardinal>;
begin
X := TArray<Cardinal>.Create(1, 2, 3, 4, 5);
Len := Length(X) * 4;
if Assigned(List) then
Move(Pointer(X)^, List^, Len);
end;
exports
Script_GetFindedList;
begin
end.
**Python**
from ctypes import *
my_dll = WinDLL(r'full/path/to/TestDLL.dll')
my_dll.Script_GetFindedList.restype = None
size = c_uint()
my_dll.Script_GetFindedList(None, byref(size))
result = (c_uint*(size.value//4))()
my_dll.Script_GetFindedList(result, byref(size))
result = list(result)
print result
**Output**
[1L, 2L, 3L, 4L, 5L]
|
open file named with two digit year-Python
Question: I'm opening a file named in the following format :
ex130626.log
exYYMMDD.log
following code wants 4-digit year. How to get the two digit year like 13?
today = datetime.date.today()
filename = 'ex{0}{1:02d}{2:02d}.log'.format(today.year, today.month, today.day)
Answer: Just take the modulus of the year:
>>> import datetime
>>> today = datetime.date.today()
>>> filename = 'ex{:02}{:02}{:02}.log'.format(today.year%100, today.month, today.day)
>>> filename
'ex130625.log'
But an easier way is `strftime`:
>>> today.strftime('ex%y%m%d.log')
'ex130625.log'
|
parallel installion of Python 2.7 and 3.3 via Homebrew - pip3 fails
Question: I would like to make the jump and get acquainted with Python 3. I followed the
instructions found [here](https://github.com/mxcl/homebrew/wiki/Homebrew-and-
Python#python-2x-or-python-3x) with the installation working flawlessly.
I'm also able to use the provided virtualenv to create enviroments for Python
2 and Python 3 (Followed the instuctions
[here](http://stackoverflow.com/questions/12566064/virtualenv-with-
python2-and-python3-via-homebrew).). Unfortunalty pip3 fails when no
virtualenv is activated. I need to use it to install global modules for
python3.
This is the error message:
± |master ✓| → pip3
Traceback (most recent call last):
File "/usr/local/bin/pip3", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/local/lib/python2.7/site-packages/distribute-0.6.45-py2.7.egg/pkg_resources.py", line 51
def _bypass_ensure_directory(name, mode=0777):
^
SyntaxError: invalid token
It looks like pip3 is trying to access distribute of python2. Is there any
workaround for this?
Answer: I was having the same problem as you were and I had
export PYTHONPATH="/usr/local/lib/python2.7/site-packages:$PYTHONPATH"
in my ~/.bash_profile. Removing that line solved the problem for me. If you
have that or something like it in your ~/.bashrc or ~/.bash_profile, try
removing it.
|
python walk directory tree with excluding certain directories
Question: i am trying to walk a directory tree and exclude certain directories. Now,
according to [os.walk exclude .svn
folders](http://stackoverflow.com/questions/4276255/os-walk-exclude-svn-
folders) for example i should be able to modify the 'dirs' list which would
then let me prune the tree. I tried the following:
import sys
import os
if __name__ == "__main__":
for root, dirs, files in os.walk("/usr/lib"):
print root
dirs = []
I would have expected to not enter ANY subdirectories but i do:
/usr/lib
/usr/lib/akonadi
/usr/lib/akonadi/contact
/usr/lib/akonadi/contact/editorpageplugins
/usr/lib/os-prober
/usr/lib/gnome-settings-daemon-3.0
/usr/lib/gnome-settings-daemon-3.0/gtk-modules
/usr/lib/git-core
/usr/lib/git-core/mergetools
/usr/lib/gold-ld
/usr/lib/webkitgtk-3.0-0
/usr/lib/webkitgtk-3.0-0/libexec
What am i missing?
Answer: Try one of following
dirs[:] = []
OR
del dirs[:]
|
reading v 7.3 mat file in python
Question: I am trying to read a matlab file with the following code
import scipy.io
mat = scipy.io.loadmat('test.mat')
and it gives me the following error
raise NotImplementedError('Please use HDF reader for matlab v7.3 files')
NotImplementedError: Please use HDF reader for matlab v7.3 files
so could anyone please had the same problem and could please any sample code
thanks
Answer: Try using [`h5py`](http://www.h5py.org/) module
import h5py
f = h5py.File('test.mat')
f.keys()
|
Detect from a running python script if the optimize flag is -O or -OO
Question: Sometime I'd like to spawn a child process with the same optimization flags
used to start the parent.
I can use something like:
`optimize = not __debug__`
But this way I match both `-O` and `-OO` flags.
Is there some python internal status that contains that info?
Answer: After some digging in the documentation I've found that the `sys.flags` struct
sequence (<http://docs.python.org/dev/library/sys#sys.flags>) that has an
`optimize` attribute containing the information I was searching for.
`python -c "import sys; print sys.flags.optimize"` -> `0`
`python -O -c "import sys; print sys.flags.optimize"` -> `1`
`python -OO -c "import sys; print sys.flags.optimize"` -> `2`
|
python subprocess reading terminal output and reply using PyQt4 message pop up
Question: Hi im making a program to check adb devices in python
I cant make a pop up window please correct my code.
import sys import subprocess from PyQt4 import QtGui, QtCore
ad = subprocess.check_output(["adb", "devices"])
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
btn = QtGui.QPushButton('Check Device', checkadb(ad))
btn.resize(135, 30)
btn.move(50, 10)
self.setGeometry(250, 250, 400, 400)
self.setWindowTitle('Tooltips')
self.show()
def clicked(*args):
QtGui.QMessageBox.about(QtGui, "No Device Found")
def clicked2(*args):
QtGui.QMessageBox.about(QtGui, "Device Found")
def checkadb(ad):
if len(ad) <= 27:
clicked()
elif len(ad) > 27:
clicked2()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Answer: Might you be looking for
[`subprocess.check_output()`](http://docs.python.org/2/library/subprocess.html#subprocess.check_output)?
Your use of `subprocess.call()` will give you the return code of the command
executed (a `0` indicates normal exit status).
If your result was in fact the string `"List of devices attached\n\n0"` then
you should use `.splitlines()` to split the string by each line into a list,
which would be `["List of devices attached", "", "0"]`. This would be in the
case that despite what I am lead to believe by the code in your question, you
are returning the correct result, i.e. `0`.
|
python strings to int/float in an efficient way
Question: I have an array (in numpy, or in pandas) containing (non-unique) strings. Some
of them are ints written as strings, some comprise of both digits and letters.
What I would like to do is to map these strings onto (some) int or float
values, in order to process them further.
I don't mean simple int(string,base). I mean a procedure that would, say go
through all the strings, and then say "Aha, so lets's assign to this string
such and such 'int/float-key'".
What's the most efficient way of doing that?
Answer: It sounds like you have a pandas DataFrame with various strings that you want
to convert to indexed values such that each unique string has a unique integer
value.
`numpy.unique` does what you need. (You already mentioned that you were using
numpy, so I'm going to post a numpy solution.)
For example:
import numpy as np
import pandas
df = pandas.DataFrame(dict(x=['1', 'a5', 'cde9', '1', 'cde9']))
unique_vals, df['keys'] = np.unique(df.x, return_inverse=True)
print df
|
OpenCV VideoWriter with python gives 5.54kb file
Question: I am trying to create a TimeLapse creator in python using OpenCV, and have the
following code:
import cv2
import os
import string
directory = (r"C:\Users\Josh\Desktop\20130216")
video = cv2.VideoWriter(r"C:\Users\Josh\Desktop\video.avi", cv2.cv.CV_FOURCC('F','M','P', '4'), 15, (1536, 1536), 1)
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
video.write(cv2.imread(filename))
cv2.destroyAllWindows()
video.release()
The folder has 1,440 pictures in it, yet video.avi is only 5.54kb in size, and
has an empty output when played. Can anyone see any flaws in my code, and give
me any help?
Answer: It seems to be that, you have windows without ffmpeg support. I had the same
problem and [OpenCV 2.4 VideoCapture not working on
Windows](http://stackoverflow.com/questions/11699298/opencv-2-4-videocapture-
not-working-on-windows) helped me on that.
The opencv246\opencv\3rdparty\ffmpeg\opencv_ffmpeg.dll should be copied to
c:\Python27\opencv_ffmpeg246.dll
Your frame size defined in your code as 1536x1536, so all of your .jpg files
should match that size.
video = cv2.VideoWriter(r"C:\Users\Josh\Desktop\video.avi",
cv2.cv.CV_FOURCC('F','M','P', '4'), 15, (1536, 1536), 1)
|
Python script for ip to hostname lookup
Question: I have never attempted to create a script in my entire life but I've come
across an issue where I would require a script (preferably Python) to perform
lookups. I have a system that actively monitors web and ftp traffic and I'm
able to get the sender IP address (typically the web proxy) but the proxies
are not passing credentials at this time.
I'd like to create a script that takes the sender-ip address, queries our
internal DNS server, and provides me with the hostname of the machine real
time. At that point, I would be able to take the response from DNS and perform
a secondary LDAP query to return additional attributes but I'm stuck on step
one.
I apologize if this is a very simple script but I've been looking and
unfortunately my background is not in scripting, so this is all very new to
me. Please let me know if you require any additional info.
Thanks!
Answer:
Python 3.3.1 (default, Apr 17 2013, 22:30:32)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> socket.gethostbyaddr('74.125.225.35')
('ord08s06-in-f3.1e100.net', [], ['74.125.225.35'])
>>> socket.gethostbyaddr('74.125.225.35')[0]
'ord08s06-in-f3.1e100.net'
Call the python script from whatever app you have that acquires the connecting
IP address and pass the IP as a command line parameter.
|
How to get Python to look at Sub-Folders?
Question: I am trying to create a python script that will look in a series of sub-
folders and delete empty shapefiles. I have successfully created the part of
the script that will delete the empty files in one folder, but there are a
total of 70 folders within the "Project" folder. While I could just copy and
paste the code 69 times I'm sure must be a way to get it to look at each sub-
folder and run the code for each of those sub-folders. Below is the what I
have so far. Any ideas? I'm very new to this and I have simply edited an
existing code to get this far. Thanks!
import os
# Set the working directory
os.chdir ("C:/Naview/Platypus/Project")
# Get the list of only files in the current directory
file = filter(os.path.isfile, os.listdir('C:/Naview/Platypus/Project'))
# For each file in directory
for shp in file:
# Get only the files that end in ".shp"
if shp.endswith(".shp"):
# Get the size of the ".shp" file.
# NOTE: The ".dbf" file can vary is size whereas
# the shp & shx are always the same when "empty".
size = os.path.getsize(shp)
print "\nChecking " + shp + "'s file size..."
#If the file size is greater than 100 bytes, leave it alone.
if size > 100:
print "File is " + str(size) + " bytes"
print shp + " will NOT be deleted \n"
#If the file size is equal to 100 bytes, delete it.
if size == 100:
# Convert the int output from (size) to a string.
print "File is " + str(size) + " bytes"
# Get the filename without the extention
base = shp[:-4]
# Remove entire shapefile
print "Removing " + base + ".* \n"
if os.path.exists(base + ".shp"):
os.remove(base + ".shp")
if os.path.exists(base + ".shx"):
os.remove(base + ".shx")
if os.path.exists(base + ".dbf"):
os.remove(base + ".dbf")
if os.path.exists(base + ".prj"):
os.remove(base + ".prj")
if os.path.exists(base + ".sbn"):
os.remove(base + ".sbn")
if os.path.exists(base + ".sbx"):
os.remove(base + ".sbx")
if os.path.exists(base + ".shp.xml"):
os.remove(base + ".shp.xml")
Answer: There are several ways to do this. I'm a fan of
[`glob`](http://docs.python.org/2/library/glob.html)
for shp in glob.glob('C:/Naview/Platypus/Project/**/*.shp'):
size = os.path.getsize(shp)
print "\nChecking " + shp + "'s file size..."
#If the file size is greater than 100 bytes, leave it alone.
if size > 100:
print "File is " + str(size) + " bytes"
print shp + " will NOT be deleted \n"
continue
print "Removing", shp, "files"
for file in glob.glob(shp[:-3] + '*'):
print " removing", file
os.remove(file)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.