text
stringlengths 226
34.5k
|
---|
CSV import with Python; incorrect "," delimiter behavior
Question: I am using the csv module in the following manner
header = '"Id","IsDeleted","MasterRecordId","Salutation","FirstName","LastName","Name","Type","RecordTypeId","ParentId","BillingStreet","BillingCity","BillingState","BillingPostalCode","BillingCountry","BillingLatitude"'
header_c = csv.reader(header, delimiter=',', quotechar='"')
names = []
for row in header_c:
names.append(row)
Inspecting names returns:
[['Id'], ['', ''], ['IsDeleted'], ['', ''], ['MasterRecordId'], ['', ''], ['Salutation'], ['', ''], ['FirstName'], ['', ''], ['LastName'], ['', ''], ['Name'], ['', ''], ['Type'], ['', ''], ['RecordTypeId'], ['', ''], ['ParentId'], ['', ''], ['BillingStreet'], ['', ''], ['BillingCity'], ['', ''], ['BillingState'], ['', ''], ['BillingPostalCode'], ['', ''], ['BillingCountry'], ['', ''], ['BillingLatitude']]
I could ignore all the odd entries, keeping 0, 2, 4, ...., but I don't
understand what I am doing wrong and why the commas are being kept as entries.
What do I have to change in order for the comma's to be dropped. 'IsDeleted'
should be the second entry (names[1])
Thanks in advance.
Answer: You should pass a file-like object (or any other iterable) to
[csv.reader](http://docs.python.org/2/library/csv.html#csv.reader) as a first
parameter.
> csv.reader(csvfile, dialect='excel', **fmtparams)
>
> Return a reader object which will iterate over lines in the given csvfile.
> csvfile can be any object which supports the iterator protocol and returns a
> string each time its next() method is called — file objects and list objects
> are both suitable.
One option is to read the string into the `StringIO` buffer:
from StringIO import StringIO
header_c = csv.reader(StringIO(header), delimiter=',', quotechar='"')
Then, in names, you'll get:
[['Id', 'IsDeleted', 'MasterRecordId', 'Salutation', 'FirstName', 'LastName', 'Name', 'Type', 'RecordTypeId', 'ParentId', 'BillingStreet', 'BillingCity', 'BillingState', 'BillingPostalCode', 'BillingCountry', 'BillingLatitude']]
|
Issue executing updatetool glassfish in Debian
Question: I have installed glassfish 4 and it works pretty well but few minutes ago I
tried to execute `updatetool` but I get this error:
./updatetool: 283: ./updatetool: /home/mazzy/glassfish4/updatetool/bin/../../pkg/python2.4-minimal/bin/python: not found
---------------------------------------------------------------
There was an error running
/home/mazzy/glassfish4/updatetool/bin/../../pkg/python2.4-minimal/bin/python
You are running on a 64 bit Linux distribution and the 32 bit Linux
compatibility libraries do not appear to be installed. In order to use
the Update Center tools you must install the 32 bit compatibility libraries.
On Ubuntu (and possibly other Debian based systems) please install the
ia32-libs package. On RedHat 4 (and other RPM based systems), you may
need to add multiple 'compat' runtime library packages. Please see the
Update Center Release Notes for more information
---------------------------------------------------------------
My system is Debian 7.1.0 Wheezy 64 bit.
What do you suggest to do? Please don't say to install `ia32-libs` package
because I have already tried to install it bit it could not be installed in my
sistem.
**EDIT**
This is the next error I get after having installed ia32-libs for i386
architecture:
GlassFish Update Tool does not support running in "it_IT.utf" locale.
Attempting to use English locale.
WX import error. Verify the WX widgets are in the PYTHONPATH.
The following can be reported to GlassFish Update Tool 2.3.5 Development Team <[email protected]>.
Traceback (innermost last):
File "/home/mazzy/glassfish4/updatetool/vendor-packages/updatetool/common/boot.py", line 283, in init_app_locale
import wx
File "wx/__init__.py", line 45, in ?
File "wx/_core.py", line 4, in ?
ImportError: libgtk-x11-2.0.so.0: impossibile aprire il file oggetto condiviso: File o directory non esistente
Answer: I just wrote a reference on installing the updatetool on glassfish 4, [How to
install Updatetool on Glassfish 4 64bit -
Reference](http://stackoverflow.com/questions/21060532/how-to-install-
updatetool-on-glassfish-4-64bit-reference) I haven't run into the issues with
the libraries you mentioned (rather then some others), so feel free to
complete.
|
How to create a psd layered file from multiple image in python
Question: I need to create a psd file to merge several images into a single layered one.
I saw that the _gimp command line_ seems to be the only way to be able to do,
but I would like to make this tool-independent.
_Would there be another solution ?_
For info I already looked into _psd-tools_ , _psdparse_ , _pypsd_ that allows
extracting layers from a psd to make a separate image with it but not the
other way around.
o/
Answer: I had looked into that issue myself some time ago for a client who was adamant
on building an online-photo editor using Django.
For proper results you will likely have to rely on a native compiled library
in some form or another. As most Python modules will wrap these libraries, you
could stick to `import os; os.system("gimp ...")` or `from subprocess import
call; call(["gimp", "-i -b '(mygimpscript "test.psd" 2000 2000)'..."])` using
the [GIMP command line](http://stackoverflow.com/questions/1168614/how-to-
create-a-layered-psd-file-from-command-line?rq=1) for instance.
From an Adobe
[blogger](http://blogs.adobe.com/jnack/2009/05/some_thoughts_about_the_psd_format.html):
> If you’re a developer, PSD’s complexity makes writing a file format
> reader/writer more difficult. Of course, PSD was never designed as or
> intended to be an interchange format.
The _[Readme](https://github.com/kmike/psd-tools)_ from the current-work-in-
progress [psd-tools](https://github.com/kmike/psd-tools), also suggests that
good psd-writers are still hard or even elusive to come by.
* * *
Despite that introduction,
* [GIMP and Python](http://www.gimp.org/docs/python/index.html) would be a good combination.
* [Pillow 2](https://pypi.python.org/pypi/Pillow/2.0.0) has some useful features as well.
For full compatibility with _alpha blending_ , and _metadata_ , the only
option you got is using the proprietary COM32 based psd library from Adobe.
[Here](http://techarttiki.blogspot.co.at/2008/08/photoshop-scripting-with-
python.html) is an example, and
[here](http://peterhanshawart.blogspot.co.at/2012/05/python-and-photoshop-
code-snippets.html) another.
The advantage is a decent level of documentation. The disadvantage is that you
will likely be platform bound.
Unfortunately the answer still appears to be:
**_No, there still is currently no way to write psd files in pure Python in a
manner that would satisfy a productive level_.**
|
how to input a respond to prompt of a command by python?
Question: I ma running a Python code utilizing from prompt commands. It sometimes
conflicts with the existing files and says
File 'outputs/g/Charlotte_s_Web_2006_-_Trailer.avi' already exists. Overwrite ? [y/N]
where the file name is changing.
Is it possible to capture that question and input `N` as an answer constantly
on Python?
Answer: If you're running on some UNIX variant, you can do
yes N | <program>
which feeds a never-ending stream of "N"s to the program.
If you want to control a console-driven program from Python, consider using
`pexpect`. This library enables very simple interaction:
import pexpect
pexpect.spawn("<cmd>")
while 1:
child.expect(r'\[y/N\]')
child.sendline('N')
|
export data from sqlite to Excel file in multiple tabs in python
Question:
......
......
ofile = open('test.csv', "wb")
writer = csv.writer(ofile)
conn=sqlite3.connect('test.sqlite')
c=conn.cursor()
c.execute("select * from emp")
mysel=c.execute("select * from emp")
for row in mysel:
print row
writer.writerow(row)
ofile.close()
.....
.....
above code is working fine and i am getting results as csv.
Problem starts when i want to write data in csv in mulitple tabs. i checked on
this site and people are saying there is no option. i have to use Excel.
to get data populated in different tabs, am trying the below code with
import xlsxwriter
ofile = xlsxwriter.Workbook('mac.xlsx')
worksheet1 = ofile.add_worksheet()
conn=sqlite3.connect('test.sqlite')
c=conn.cursor()
c.execute("select * from emp")
mysel=c.execute("select * from emp ")
for row in mysel:
print row
worksheet1.write("A1",row)
#worksheet1.write(" ",row)
#worksheet1.write(row)
ofile.close()
no success, please help me to sort the issue, i hope my goal (**write data in
to excel from sqlite3 using python in multiple tabs**) is clear. please share
your experienced thoughts
1) can i do this using xlsxwriter 2) should i use any other library 3) is
there any simple way to do it
please help
Answer: Here's an example how to create an excel file with multiple sheets using
`xlsxwriter`:
from xlsxwriter.workbook import Workbook
workbook = Workbook('output.xlsx')
for i in range(10):
worksheet = workbook.add_worksheet()
worksheet.write(0, 0, "I'm sheet number %d" % (i + 1))
workbook.close()
|
Persistence of a large number of objects
Question: I have some code that I am working on that scrapes some data from a website,
and then extracts certain key information from that website and stores it in
an object. I create a couple hundred of these objects each day, each from
unique url's. This is working quite well, however, I'm inexperienced in what
options are available to me in Python for persistence and what would be best
suited for my needs.
Currently I am using pickle. To do so, I am keeping all of these webpage
objects and appending them in a list as new ones are created, then saving that
list to a pickle (then reloading it whenever the list is to be updated).
However, as i'm in the order of some GB of data, i'm finding pickle to be
somewhat slow. It's not unworkable, but I'm wondering if there is a more well
suited alternative. I don't really want to break apart the structure of my
objects and store it in a sql type database, as its important for me to keep
the methods and the data as a single object.
Shelve is one option I've been looking into, as my impression is then that I
wouldn't have to unpickle and pickle all the old entries (just the most recent
day that needs to be updated), but am unsure if this is how shelve works, and
how fast it is.
So to avoid rambling on, my question is: what is the preferred persistence
method for storing a large number of objects (all of the same type), to keep
read/write speed up as the collection grows?
Answer: Martijn's suggestion could be one of the alternatives.
You may consider to store the pickle objects directly in a sqlite database
which still can manage from the python standard library.
Use a StringIO object to convert between the database column and python
object.
You didn't mention the size of each object you are pickling now. I guess it
should stay well within sqlite's limit.
|
convert ascii to integer like '\x01' inputs
Question: I get data from network in bytearray and I need to get integer value in
bytearray[i]. It is ASCII and when I try to convert integer with int() I get
exception. How can I try to convert '\x01' to get 1 in python? Thanks.
Answer: Use [`ord`](http://docs.python.org/2/library/functions.html#ord):
>>> ord('\x01')
1
or
[`struct.unpack`](http://docs.python.org/2/library/struct.html#struct.unpack):
>>> import struct
>>> struct.unpack('B', '\x01')
(1,)
>>> struct.unpack('2B', '\x01\x02')
(1, 2)
|
Dictionary with tuples as values
Question: Is it possible to create a dictionary like this in Python?
{'string':[(a,b),(c,d),(e,f)], 'string2':[(a,b),(z,x)...]}
The first error was solved, thanks! But, i'm doing tuples in a for loop, so it
changes all the time. When i try to do:
d[key].append(c)
As c being a tuple.
I am getting another error now:
AttributeError: 'tuple' object has no attribute 'append'
Thanks for all the answers, i managed to get it working properly!
Answer: Is there a reason you need to construct the dictionary in that fashion? You
could simply define
d = {'string': [('a', 'b'), ('c', 'd'), ('e', 'f')], 'string2': [('a', 'b'), ('z', 'x')]}
And if you wanted a new entry:
d['string3'] = [('a', 'b'), ('k', 'l')]
And if you wish to append tuples to one of your lists:
d['string2'].append(('e', 'f'))
* * *
Now that your question is clearer, to simply construct a dictionary with a
loop, assuming you know the keys beforehand in some list `keys`:
d = {}
for k in keys:
d[k] = []
# Now you can append your tuples if you know them. For instance:
# d[k].append(('a', 'b'))
There is also a dictionary comprehension if you simply want to build the
dictionary first:
d = {k: [] for k in keys}
* * *
> Thanks for the answer. But, is there any way to do this using defaultdict?
from collections import defaultdict
d = defaultdict(list)
for i in 'string1','string2':
d[i].append(('a','b'))
Or you can use `setdefault`:
d = {}
for i in 'string1','string2':
d.setdefault(i, []).append(('a','b'))
|
Sublime Text accessing view file name error
Question: I am new to Python, and Sublime Text plugin development, and I don't know what
I'm doing wrong here. I am using Sublime Text 3. I'm trying to create a plugin
that will copy the file name to the clipboard. Can anyone help me understand
this python error and/or offer a solution?
import sublime, sublime_plugin
class Filename_to_clipboardCommand(sublime_plugin.TextCommand):
def run(self, edit):
sublime.set_clipboard(sublime.View.file_name())
sublime.message_dialog("The full file path was copied to the clipboard")
and the error, when I call the plugin from the console, is:
>>> view.run_command('filename_to_clipboard')
Traceback (most recent call last):
File "/Applications/Sublime Text.app/Contents/MacOS/sublime_plugin.py", line 549, in run_
return self.run(edit)
File "/Users/ivan/Library/Application Support/Sublime Text 3/Packages/Filename_to_clipboard/filename_to_clipboard.py", line 5, in run
sublime.set_clipboard(sublime.View.file_name())
TypeError: file_name() missing 1 required positional argument: 'self'
When I do:
sublime.set_clipboard(view.file_name())
from the conosole, it works! Why?
Answer: Try `self.view.file_name()` rather than `sublime.View.file_name()`. You have a
reference to an instance of the view for your TextCommand. It was written for
ST2, but you may want to take a look at this tutorial
<http://net.tutsplus.com/tutorials/python-tutorials/how-to-create-a-sublime-
text-2-plugin/>
|
why Popen can't exec python cmd?
Question: I want to exec command using Popen, see my code below:
import subprocess
p = subprocess.Popen('/usr/bin/python a.py')
p2 = subprocess.Popen('ls', stdout = subprocess.PIPE)
print p2.stdout.readlines()
while I exec this script, I get the error below:
File "demo.py", line 4, in <module>
p0 = subprocess.Popen('/usr/bin/python a.py')
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
What's the problem? Another question is what if a.py is a 'while-True-loop'
can p2 return?
Thanks!
Answer: Check your python and your "a.py" script path and make sure they exist!
After that try this :
import subprocess
p = subprocess.Popen(["/usr/bin/python" , "a.py"], stdout=subprocess.PIPE)
out, err = p.communicate()
good luck!
|
Opencv Python display raw image
Question: I can't figure out how to display a raw image wich conatains 640x480 pixel
information, each pixel 8 bit. (Gray image)
I need to go from an np array to Mat format to be able to display the image.
#!/usr/bin/python
import numpy as np
import cv2
import sys
# Load image as string from file/database
fd = open('flight0000.raw')
img_str = fd.read()
fd.close()
img_array = np.asarray(bytearray(img_str), dtype=np.uint8)
img = ... Conversion to Mat graycolor
cv2.imshow('rawgrayimage', img)
cv2.waitKey(0)
It so confusing with the cv ,cv2. I have been trying for a while now, but i
can't find the solution.
Answer: .RAW files are not supported in OpenCV [see
imread](http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#imread),
But the file can be opened with Python and parsed with Numpy
import numpy as np
fd = open('flight0000.raw', 'rb')
rows = 480
cols = 640
f = np.fromfile(fd, dtype=np.uint8,count=rows*cols)
im = f.reshape((rows, cols)) #notice row, column format
fd.close()
This makes a numpy array that can be directly manipulated by OpenCV
import cv2
cv2.imshow('', im)
cv2.waitKey()
cv2.destroyAllWindows()
|
Newbie Python Script - read()
Question: I am trying to learn more about python and wrote a simple script but I can't
get the read() function to work. What am I missing? The error message I am
getting is:
Traceback (most recent call last): File "ex16demo.py", line 28, in print
glist.read() IOError: File not open for reading
I file should be open and assigned to the glist variable.
from sys import argv
script, filename = argv
print "We are creating a new grocery list!"
print "Opening %r..." % filename
glist = open(filename, 'w')
print "Deleting previous content from %r......" % filename
glist.truncate()
print "Add your items now:"
item1 = raw_input("item 1:")
item2 = raw_input("item 2:")
item3 = raw_input("item 3:")
print "Adding your items to the list...."
glist.write(item1)
glist.write("\n")
glist.write(item2)
glist.write("\n")
glist.write(item3)
glist.write("\n")
print "Here are the items in your grocery list:"
print glist.read()
Thanks!
Answer: The file was opened for writing (see `open(filename, 'w')`).
Close the file, open it for reading and then call `read()`:
glist.close()
glist = open(filename, 'r')
print glist.read()
Or, you can open file in `r+` mode to read and write without reopening (thanks
to @sberry's comment).
Also, consider using `with` context manager instead of manually closing the
opened file:
with open(filename, 'r+'):
print "Deleting previous content from %r......" % filename
glist.truncate()
...
print glist.read()
Also see:
* [documentation](http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) on `open()` modes
* [python open built-in function: difference between modes a, a+, w, w+, and r+?](http://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r)
|
Opening a JPEG Image in Python
Question: I am running into a problem opening jpeg images in Python 2.7 using the
following code.
import Tkinter as tk
from PIL import ImageTk, Image
path = 'C:/Python27/chart.jpg'
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
The jpeg opens just fine but then the code stops running. I want to open the
jpeg in the middle of the program but once the image opens none of the
remaining code gets executed.
I also tried opening the jpeg using the code below but just get the error "No
module named Image". I have installed PIL and it was the correct 2.7 version.
import Image
image = Image.open('File.jpg')
image.show()
Any help would be appreciated.
Answer: Tkinter is single threaded. The `root.mainloop` call enters the GUI loop
responsible for displaying and updating all graphical elements, handling user
events, and so on, blocking until the graphical application exits. After the
mainloop has exited, you are no longer able to update anything graphically.
Therefore, you likely need to rethink the design of your program. You have two
options for running your own code alongside the mainloop:
**Option 1: Run your code in a separate thread**
Before entering the main loop, spawn a thread that will run your own code.
...
def my_code(message):
time.sleep(5)
print "My code is running"
print message
my_code_thread = threading.Thread(target= my_code, args=("From another thread!"))
my_code_thread.start()
root.mainloop()
**Option 2: Run your code within the mainloop with`Tk.after`**
root.after_idle(my_code) #will run my_code as soon as it can
root.mainloop()
**Warning** The mainloop is responsible for everything related to making the
GUI usable. While your code is running within the mainloop thread (scheduled
with root.after_idle or root.after), the GUI will be completely unresponsive
(frozen), so make sure you aren't loading the mainloop with long-running
operations. Run those in a separate thread as in Option 1.
Basically, the main thread **must** run the main loop, and your code can run
concurrently only using the methods outlined above, so you unfortunately
probably have to restructure your entire program.
|
How to make an executable with cx_freeze?
Question: I making an executable with python 2.6. I made the setup code.
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(
name = "Aimball",
version = "2.6",
description = "Aimball Game",
executables = [Executable("aimball.py", base = base)])
Then what do I do? I have read the cx_freeze documentation and other answers
but not sure what they exactly mean. Could someone explain it clearer as I
just started programming in Python a few weeks ago. Just in case I'm running
Windows 7 and version 4.3.1 of cx_freeze with Python 2.6.
Answer: Save that file in the same folder as your `aimball.py` script, as something
like `setup.py`. Then open up a command prompt in that directory (you can use
the `cd` command to Change Directory). Then run `python setup.py build`. If it
works, it should create a `build/exe...` folder containing your executable and
some other files it needs to run.
|
Accessing passed data through ajax call in my python script
Question: I've been breaking my head since morning over this, but can't get it work.
Basically, what I want to do is that upon clicking 'Send' in an html page, the
account number (it's value in a textfield) should be sent to my python script.
Now, how can I access the passed account number in my python script. I'm using
django.
This is the ajax call from the html page:
$('#b2').click(function() {
$.ajax({
url : "../../cgi-bin/testjson.py",
type : "post",
datatype : "json",
data : {
ac_number : $("#account_number").val()
},
success : function(response) {
var handle = document.getElementById("displaytext");
handle.innerHTML += '<p> Button clicked</p>';
handle.innerHTML += '<p> Value received is: </p>' + response.data[0];
}
});
});
Answer: Inside your python file:
import sys
import cgi
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n")
sys.stdout.write("\n")
form = cgi.FieldStorage()
sys.stdout.write(json.dumps({ 'data': form.getvalue('ac_number')}))
|
stanford corenlp not working
Question: I'm using Windows 8, and running python in eclipse with pyDev.
I installed Stanford coreNLP (python version) from the site:
<https://github.com/relwell/stanford-corenlp-python>
When I try to import corenlp, I get the following error message.
Traceback (most recent call last):
File "C:\Users\Ghantauke\workspace\PythonTest2\test.py", line 1, in <module>
import corenlp
File "C:\Python27\lib\site-packages\corenlp\__init__.py", line 13, in <module>
from corenlp import StanfordCoreNLP, ParserError, TimeoutError, ProcessError
File "C:\Python27\lib\site-packages\corenlp\corenlp.py", line 28, in <module>
import pexpect
File "C:\Python27\lib\site-packages\pexpect.py", line 85, in <module>
support it. Pexpect is intended for UNIX-like operating systems.""")
ImportError: No module named resource
A critical module was not found. Probably this operating system does not
support it. Pexpect is intended for UNIX-like operating systems.
Does that mean the python fork of it doesn't work in windows? Is there any way
I can make it work in windows?
If not then could you suggest other alternatives that I could use in windows.
I just need the parser.
Answer: This is a record of my attempts to get `corenlp-python`, the python wrapper
for [CoreNLP](http://nlp.stanford.edu/downloads/corenlp.shtml) running on
Windows Server 2012, as-is.
> **Disclaimer:** should you only need to run an executable, check
> [this](http://stackoverflow.com/a/11320816) first. Consider `subprocess`.
### Starting out
Since `corenlp-python` uses `pexpect` fairly heavily, and that library works
on UNIX only, my first thought was to find a Windows port.
[wexpect.py](http://mediarealm.com.au/articles/2014/01/python-pexpect-windows-
wexpect/) was fairly easy to find and claims to be a drop-in replacement for
Pexpect (emphasis mine):
> In order to use WExpect, you must install CygWin, and then install the
> WExpect script into your system **(dropping the py file into your working
> directory is usually good enough)**. I’ve found the functionality is pretty
> much the same, so you should be able to use the PExpect manual and examples
> and apply them to this Microsoft Windows variant.
So I did just that, downloading and installing CygWin, then copying
`wexpect.py` into `C:\Python27\lib\` where all the other libraries were. I
tried to `import wexpect` from a Python shell and got an error similar to when
I first tried Pexpect on Windows:
ImportError: No module named pywintypes
This module requires the win32 python packages.
A critical module was not found. Probably this operating system does not
support it. Pexpect is intended for UNIX-like systems.
### Et tu, wexpect?
No matter, this is standard frustration for finding equivalents. Press on.
I opened `wexpect.py` and saw that it would only try `pywintypes` on a Windows
system. Logical, so I tried:
$ pip install -U pywintypes
...which failed, and led me to Google for the name of the python Win32
packages ([this
answer](http://stackoverflow.com/questions/18907889/importerror-no-module-
named-pywintypes) helped):
$ pip install -U pywin32
...which prompts for `--allow-external` and then `--allow-unverified`, both of
which expect the package name, ergo:
$ pip install --allow-external pywin32 --allow-unverified pywin32 pywin32
Which, of course, does not work. No such package is found.
### sf.net
So I head off to search for [pywin32 on
PyPI](https://pypi.python.org/pypi?%3Aaction=search&term=pywin32&submit=search)
and realise that [only a readme is
left](https://pypi.python.org/pypi/pywin32/214) and I have to jump through
four MORE hoops to get to [something more
substantial](http://sourceforge.net/projects/pywin32/files/), then two more to
find [this
list](http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/).
I downloaded [Build 219 for Python 2.7
32-bit](http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/pywin32-219.win32-py2.7.exe/download).
At least now `import wexpect` doesn't puke.
### What did you expect?
So I run the `corenlp-python` command again, and this time it's missing
`unidecode`. This was easier to fix, and finally I got to a usable state - an
error, no less, but familiar - where the path to the JARs was not correct.
### OK.
When you run `corenlp.py`, since `pexpect` is invoked, remember to `import
wexpect as pexpect` near the top and comment out the real `import pexpect`
line, or you will get a `NameError`:
#import pexpect
import wexpect as pexpect
Even with Java installed, this does not seem to work, regardless of path.
$ python lib\corenlp\corenlp.py
It returns an `ExceptionPexpect`.
|
Python: urwid: trying to handle different views
Question: I try to program with different views.
Therefor, i tried to make a class which handles different views with urwid,
also to separate the view code from the rest.
After a lot of different tries i don't know where to start anymore.
Which urwid objects do i need for a clean erasing and redraw of the screen,
and how do they need to be encapsulated so i can switch views after user
input?
Answer: From the [Urwid documentation](http://urwid.org/manual/mainloop.html#widgets-
displayed):
> The topmost widget displayed by MainLoop must be passed as the first
> parameter to the constructor. **If you want to change the topmost widget
> while running, you can assign a new widget to the MainLoop object’s
> MainLoop.widget attribute. This is useful for applications that have a
> number of different modes or views.**
Now for some code:
import urwid
# This function handles input not handled by widgets.
# It's passed into the MainLoop constructor at the bottom.
def unhandled_input(key):
if key in ('q','Q'):
raise urwid.ExitMainLoop()
if key == 'enter':
try:
## This is the part you're probably asking about
loop.widget = views.next().build()
except StopIteration:
raise urwid.ExitMainLoop()
# A class that is used to create new views, which are
# two text widgets, piled, and made into a box widget with
# urwid filler
class MainView(object):
def __init__(self,title_text,body_text):
self.title_text = title_text
self.body_text = body_text
def build(self):
title = urwid.Text(self.title_text)
body = urwid.Text(self.body_text)
body = urwid.Pile([title,body])
fill = urwid.Filler(body)
return fill
# An iterator consisting of 3 instantiated MainView objects.
# When a user presses Enter, since that particular key sequence
# isn't handled by a widget, it gets passed into unhandled_input.
views = iter([ MainView(title_text='Page One',body_text='Lorem ipsum dolor sit amet...'),
MainView(title_text='Page Two',body_text='consectetur adipiscing elit.'),
MainView(title_text='Page Three',body_text='Etiam id hendrerit neque.')
])
initial_view = views.next().build()
loop = urwid.MainLoop(initial_view,unhandled_input=unhandled_input)
loop.run()
In short, I've used a global key handling function to listen for a certain
sequence pressed by the user and on receiving that sequence, my key handling
function builds a new view object with the MainView class and replaces
`loop.widget` with that object. Of course, in an actual application, you're
going to want to create a signal handler on a particular widget in your view
class rather than use the global unhandled_input function for all user input.
You can read about the connect_signal function
[here](http://urwid.org/reference/signals.html?highlight=closure#signal-
functions).
Note the part about garbage collection in Signal Functions documentation: if
you're intending to write something with many views, they will remain in
memory even after you've replaced them due to the fact that the signal_handler
is a closure, which retains a reference to that widget implicitly, so you need
to pass the `weak_args` named argument into the `urwid.connect_signal`
function to tell Urwid to let it go once its not actively being used in the
event loop.
|
Python - strptime ValueError: time data does not match format '%Y/%m/%d'
Question: I believe I am missing something trivial. After reading all the questions
about `strptime ValueError` yet I feel the format seems right, Here is the
below error I get
Traceback (most recent call last):
File "loadScrip.py", line 18, in <module>
nextDate = datetime.datetime.strptime(date, "%Y/%m/%d")
File "/usr/lib64/python2.6/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '20l2/08/25' does not match format '%Y/%m/%d'
I am using Python 2.6.6 under Linux x86_64. Any help will be much appreciated.
Answer: Your error indicates you have data with the letter `l` (lowercase L) instead
of the number `1` in the year:
ValueError: time data '20l2/08/25' does not match format '%Y/%m/%d'
That is not a valid date that'll fit the requested format; replacing the `l`
with `1` and the input date works just fine:
>>> import datetime
>>> datetime.datetime.strptime('20l2/08/25', "%Y/%m/%d")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '20l2/08/25' does not match format '%Y/%m/%d'
>>> datetime.datetime.strptime('2012/08/25', "%Y/%m/%d")
datetime.datetime(2012, 8, 25, 0, 0)
Fix your input, the format is correct.
|
Python - need help looping a list through functions using 4 different ranges (0-25, 0-100, 0-1000, 0-10000)
Question: Python Version - 3.3.2
I am writing a Python program that sets a list equal to a range of numbers
(0-25), shuffles these numbers randomly and then sorts these numbers using
four different sorting functions: bubble sort, selection sort, python sort,
and insertion sort. There is also a timer function at the end of the program
that times how long each function takes to sort the range of random numbers.
I need a way to change the range from (0-25) to (0-100) then (0-1000) and
finally (0-10000). Each time it loops through a range of numbers and outputs
how much time it takes to sort the list for each sorting function.
Here is an example of the code:
import random
import time
# Sets myList equal to a range with a range from 0-25
myList = list(range(0,25))
# Randomly shuffles the list of numbers between 0-25
random.shuffle(myList)
# Bubble Sort
def bubbleSort(myList):
...(insert code)...
# Selection Sort
def selectionSort(myList):
...(insert code)...
# Python Sort
def pythonSort(myList):
...(insert code)...
# Insertion Sort
def insertionSort(myList):
...(insert code)...
# Timer
def timer(array, func):
...(insert code)...
print("Time needed for", func.__name__, 'to sort',len(array),'items: ',diff)
timer(myList, selectionSort)
timer(myList, bubbleSort)
timer(myList, pythonSort)
timer(myList, insertionSort)
So again, my question is, how do I set the list equal to (0-25) loop through
all of the sorting functions, output the time for each sorting function to
complete, then change the list to equal (0-100), loop through all of the
functions, output the time for each function and so on for (0-1000) and
(0-100000)?
Answer: As wjl suggests
for length in [25, 100, 1000, 10000]:
myList = range(length) # range(25) is equal to range(0,25)
timer(myList, selectionSort) #assuming that selectionSort doesn't alter myList
timer(myList, bubbleSort)
timer(myList, pythonSort)
timer(myList, insertionSort)
|
Python Tkinter: Embed a matplotlib plot in a widget
Question: I have already search for this, for example [Python Tkinter Embed Matplotlib
in GUI](http://stackoverflow.com/questions/4073660/python-tkinter-embed-
matplotlib-in-gui) but still can't figure it out. Basically i am trying to
plot a fancy graph for a player abilities for a basketball game inside the
player window made up with tkinter
self.fig = Figure(figsize=(1.5,1.5))
self.ax = self.fig.add_axes([0.025,0.025,0.95,0.95],polar=True)
self.plot_widget = FigureCanvasTkAgg(self.fig, master=self.top)
self.ax.grid(False)
N = 5
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii = [self.thisPlayer.rebounds,self.thisPlayer.freeThrows,self.thisPlayer.steal,self.thisPlayer.underRim,self.thisPlayer.distance]
width = [2*np.pi/(N),2*np.pi/(N),2*np.pi/(N),2*np.pi/(N),2*np.pi/(N)]
bars = pl.bar(0 , 20,width=2*np.pi, linewidth = 0) + pl.bar(theta, radii, width=width, bottom=0.2)
for r,bar in zip(radii, bars):
bar.set_facecolor( cm.jet(r/20.))
bar.set_alpha(0.5)
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
self.plot_widget.show()
self.plot_widget.get_tk_widget().pack()
what happens is that the player window has now the plot widget but the plot is
not shown. On the other side, just plotting the abilities not embedded in
tkinter works fine. Sorry for my english. thanks in advance
Answer: After you setup `self.ax`, you need to call `self.ax.bar`, not `pl.bar` to
plot the bars in `self.fig`. Here's a runnable example:
import matplotlib.pyplot as plt
import numpy as np
import Tkinter as tk
import matplotlib.figure as mplfig
import matplotlib.backends.backend_tkagg as tkagg
pi = np.pi
class App(object):
def __init__(self, master):
self.master = master
self.thisPlayer = Bunch(
rebounds=20.0,
freeThrows=5.0,
steal=5.0,
underRim=10,
distance=10)
self.fig = mplfig.Figure(figsize=(1.5, 1.5))
self.ax = self.fig.add_axes([0.025, 0.025, 0.95, 0.95], polar=True)
self.canvas = tkagg.FigureCanvasTkAgg(self.fig, master=master)
self.ax.grid(False)
N = 5
theta = np.arange(0.0, 2 * pi, 2 * pi / N)
radii = [self.thisPlayer.rebounds, self.thisPlayer.freeThrows,
self.thisPlayer.steal, self.thisPlayer.underRim,
self.thisPlayer.distance]
width = [2 * pi / (N)] * 5
bars = (
# self.ax.bar(0, 20, width=2 * pi, linewidth=0) +
self.ax.bar(theta, radii, width=width, bottom=0.2))
cmap = plt.get_cmap('jet')
for r, bar in zip(radii, bars):
bar.set_facecolor(cmap(r / 20.))
bar.set_alpha(0.5)
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
self.canvas.get_tk_widget().pack()
self.canvas.draw()
class Bunch(object):
"""
http://code.activestate.com/recipes/52308
foo=Bunch(a=1,b=2)
"""
def __init__(self, **kwds):
self.__dict__.update(kwds)
def main():
root = tk.Tk()
app = App(root)
tk.mainloop()
if __name__ == '__main__':
main()
|
How to run python program as a daemon?
Question: I write the following program to run my program as a daemon but it is not
getting run; when i run the program from python debugger it works.
I am using Mac os x.
`/User/Library/LaunchDaemons/com.bobbob.osx.test.plist`:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd >
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.bobbob.osx.test</string>
<key>Program</key>
<string>/Users/vivekbhintade/Desktop/test.py</string>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
`/Users/vivekbhintade/Desktop/test.py`:
import urllib2
from datetime import datetime
import smtplib
from smtplib import SMTPException
import threading
def checkerror():
#my code which works fine individually, which sends mail after 5 seconds to recipients.
checkerror()
And also i run the program from terminal with following command.
launchctl load /Library/LaunchDaemons/com.bobbob.osx.test.plist
This does not result in any errors.
Answer: You have almost certainly realised this in the intervening 3 months since
posting, but there seems to be some confusion here between **Launch Daemons**
and **Launch Agents** which I though it would be worth clearing up -
especially since Agents are often referred to as Daemons.
Paraphrasing the [Apple Developer
library:](https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/DesigningDaemons.html#//apple_ref/doc/uid/10000172i-SW4-BBCBHBFB)
* Daemons run as root at startup, are unable to present UI elements, and are located in `/Library/LaunchDaemons/`.
* Agents run in a user context at login, and are able to present UI elements to the user. These are located in `/Users/username/Library/LaunchAgents/`.
Your program will not run as it's located in `/User/Library` \- it needs to go
into one or another of the paths mentioned above, depending on how you plan to
use it.
|
Proxy Selenium Python Firefox
Question: How can I redirect the traffic of Firefox launched by Selenium in Python to a
proxy? I have used the solutions suggested on the web but they doesn't work!
I have tried:
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", "54.213.66.208")
profile.set_preference("network.proxy.http_port", 80)
profile.update_preferences()
driver = webdriver.Firefox(profile)
Answer: You need to import the following:
from selenium.webdriver.common.proxy import *
Then setup the proxies:
myProxy = "xx.xx.xx.xx:xxxx"
proxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': myProxy,
'ftpProxy': myProxy,
'sslProxy': myProxy,
'noProxy': '' # set this value as desired
})
Then call the webdriver.Firefox() function as follows:
driver = webdriver.Firefox(proxy=proxy)
driver.get("http://www.google.com")
Dont remember where exactly I found this solution, but its out there
somewhere. Will surely provide a link if I find it again. Just took this part
out from my code.
|
Play a part of a .wav file in python
Question: Is it possible to play a certain part of a .wav file in Python?
I'd like to have a function `play(file, start, length)` that plays the
audiofile `file` from `start` seconds and stops playing after `length`
seconds. Is this possible, and if so, what library do I need?
Answer: this is possible and can be easy in python.
[Pyaudio](http://people.csail.mit.edu/hubert/pyaudio/) is a nice library and
you can use to play your audio!
First do you need decode the audio file (wav, mp3, etc) this step convert
audio data in numbers(short int or float32).
Do you need convert the seconds in equivalent position point to cut the signal
in the position of interest, to do this multiply your frame rate by what
seconds do you want !
Here one simple example for wav files:
import pyaudio
import sys
import numpy as np
import wave
import struct
File='ederwander.wav'
start = 12
length=7
chunk = 1024
spf = wave.open(File, 'rb')
signal = spf.readframes(-1)
signal = np.fromstring(signal, 'Int16')
p = pyaudio.PyAudio()
stream = p.open(format =
p.get_format_from_width(spf.getsampwidth()),
channels = spf.getnchannels(),
rate = spf.getframerate(),
output = True)
pos=spf.getframerate()*length
signal =signal[start*spf.getframerate():(start*spf.getframerate()) + pos]
sig=signal[1:chunk]
inc = 0;
data=0;
#play
while data != '':
data = struct.pack("%dh"%(len(sig)), *list(sig))
stream.write(data)
inc=inc+chunk
sig=signal[inc:inc+chunk]
stream.close()
p.terminate()
|
Socket programming in python counter not working
Question: I am making a client and a sever relation ship using python. The client has a
button in which I click the button it will connect to the server and count the
clicked button by the client.
But in my situation, the server only count once and the client button is not
working anymore. does anybody has an idea about my case? any help will be
appreciated, thanks in advance.
this is my code
client.py
import socket
from Tkinter import*
root = Tk()
root.title("ADKOO")
root.geometry("150x80")
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12340
s.connect((host, port))
def counterPlus():
s.send('sent by '+host)
app = Frame(root)
app.grid()
button1 = Button(app, text="+", width=15, command=counterPlus)
button1.grid()
root.mainloop()
server.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 12340
s.bind((host, port))
s.listen(5)
pressed = 0
while True:
c, addr = s.accept()
pressed = pressed + 1
print 'Got connection from', addr
print c.recv(1024), 'pressed count', pressed
#c.close()
Answer: `server.py` accept a client, then receive only once, and accept another
client....
You need loop to continuous receive data from client.
Try following code:
import socket
s = socket.socket()
host = socket.gethostname()
port = 12340
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
pressed = 0
while True:
print 'Got connection from', addr
data = c.recv(1024)
if not data:
break
pressed = pressed + 1
print data, 'pressed count', pressed
**NOTE**
Your code and this code does handle one client at a time.
To handle multiple client, you need multiprocess / multithreading / select /
...
|
python: rstrip one exact string, respecting order
Question: Is it possible to use the python command `rstrip` so that it does only remove
one exact string and does not take all letters separately?
I was confused when this happened:
>>>"Boat.txt".rstrip(".txt")
>>>'Boa'
What I expected was:
>>>"Boat.txt".rstrip(".txt")
>>>'Boat'
Can I somehow use rstrip and respect the order, so that I get the second
outcome?
Answer: You're using wrong method. Use
[`str.replace`](http://docs.python.org/2/library/stdtypes#std.replace)
instead:
>>> "Boat.txt".replace(".txt", "")
'Boat'
**NOTE** : `str.replace` will replace anywhere in the string.
>>> "Boat.txt.txt".replace(".txt", "")
'Boat'
To remove the last trailing `.txt` only, you can use [_regular
expression_](http://docs.python.org/2/library/re.html):
>>> import re
>>> re.sub(r"\.txt$", "", "Boat.txt.txt")
'Boat.txt'
If you want filename without extension,
[`os.path.splitext`](http://docs.python.org/2/library/os.path.html#os.path.splitext)
is more appropriate:
>>> os.path.splitext("Boat.txt")
('Boat', '.txt')
|
Uploading images - Google App Engine + Python
Question: I'm using this link as an example to uploading images:
<https://gist.github.com/jdstanhope/5079277>
My HTML code:
<form action="/upload_image" method="post" id="form1" runat="server">
<div class="fileButtons">
<input type='file' id="imgInp" name="imgInput" accept="image/*"/><br><br>
<input type='button' id='remove' value='Remove' />
</div></form>
main.py:
class SetImage(webapp2.RequestHandler):
def post(self):
logging.debug("test")
id = str(self.request.get('id'))
image = self.request.get('imgInput')
app = webapp2.WSGIApplication([('/upload_image', SetImage),
('/', MainPage)], debug=True)
But when I add an image, nothing is being done, and the log console doesn't
print:
logging.debug("test")
Answer: The recommended way of uploading images to GAE is by using
[blobstore](https://developers.google.com/appengine/docs/python/blobstore/).
Here is a quick breakdown of the doc to help you achieve this fast:
Imports:
import os
import urllib
import webapp2
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
Serve the form HTML. this form performs the POST to GAE with the selected
files data:
class MainHandler(webapp2.RequestHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload')
self.response.out.write('<html><body>')
self.response.out.write('<form action="%s" method="POST"
enctype="multipart/form-data">' % upload_url)
self.response.out.write("""Upload File:
<input type="file" name="file"><br> <input type="submit"
name="submit" value="Submit"> </form></body></html>""")
Add a handler for receiving the POST data (binary content of the file). the
last line in this function is to redirect the response to the location from
where the file could be downloaded:
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
# 'file' is file upload field in the form
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
self.redirect('/serve/%s' % blob_info.key())
Add handler to serve the image that you uploaded using the UploadHandler
described above:
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, resource):
resource = str(urllib.unquote(resource))
blob_info = blobstore.BlobInfo.get(resource)
self.send_blob(blob_info)
And finally, define the routes for the app:
app = webapp2.WSGIApplication([('/', MainHandler),
('/upload', UploadHandler),
('/serve/([^/]+)?', ServeHandler)],
debug=True)
|
In admin I see "App_name object" but not actual object name
Question: So, I learning django by this <http://mherman.org/blog/2012/12/30/django-
basics/> tutorial and I have one problem.
I added couple books to database but in admin site I see only "App_name
object". In my case I see only list of words "Books object", "Books object",
"Books object" when actually I should see "War and Peace", "Brave New World",
"To Kill a Mockingbird".
So, do you know what's wrong with my app?
Thank you ;)
edited: add my models.py code
from django.db import models
class Books(models.Model):
title = models.CharField(max_length=150)
author = models.CharField(max_length=100)
read = models.CharField(max_length=3)
def __unicode__(self):
return self.title + " / " + self.author + " / " + self.read
I found answer:
> Django 1.5 has experimental support for Python 3, but the Django 1.5
> tutorial is written for Python 2.X:
>
> This tutorial is written for Django 1.5 and Python 2.x. If the Django
> version doesn’t match, you can refer to the tutorial for your version of
> Django or update Django to the newest version. If you are using Python 3.x,
> be aware that your code may need to differ from what is in the tutorial and
> you should continue using the tutorial only if you know what you are doing
> with Python 3.x.
>
> In Python 3, you should define a **str** method instead of a **unicode**
> method. There is a decorator python_2_unicode_compatible which helps you to
> write code which works in Python 2 and 3.
>
> @python_2_unicode_compatible class Poll(models.Model): question =
> models.CharField(max_length=200) pub_date = models.DateTimeField('date
> published')
>
>
> def __str__(self):
> return self.question For more information see the section str and
> unicode methods in the Porting to Python 3 docs.
>
Answer: You haven't defined (or did it incorrectly) `__unicode__()` method of your
`Books` model:
> 5\. Next, open up your models.py file and add these two lines of code-
>
>
> def __unicode__(self):
> return self.title + " / " + self.author + " / " + self.read
>
FYI, quote from
[docs](https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.__unicode__):
> The `__unicode__()` method is called whenever you call unicode() on an
> object. Django uses `unicode(obj)` (or the related function, `str(obj)`) in
> a number of places. **Most notably, to display an object in the Django admin
> site** and as the value inserted into a template when it displays an object.
> Thus, you should always return a nice, human-readable representation of the
> model from the `__unicode__()` method.
|
How to find what time is it in another country from local
Question: this time, i have questions on timezones in Python
How do i , say from anywhere in the world, convert that local time into say,
New york time? first of, I think datetime module is the one to use. Should I
use utcfromtimestamp() , then use some other functions to convert to New york
time? How do i actually do that. thanks
Answer: It sounds like you want to use the `pytz` module. The docs are very
comprehensive and have some nice examples for you.
<http://pytz.sourceforge.net/>
From the docs:
>>> from datetime import datetime, timedelta
>>> from pytz import timezone
>>> import pytz
>>> utc = pytz.utc
>>> utc.zone
'UTC'
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = timezone('Europe/Amsterdam')
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print(loc_dt.strftime(fmt))
2002-10-27 06:00:00 EST-0500
>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'
|
Installing numpy on Amazon EC2
Question: I am having trouble installing numpy on an Amazon EC2 server. I have tried
using easy_install, pip, pip inside a virtual env, pip inside another virtual
env using python 2.7...
Every time I try, it fails with the error: `gcc: internal compiler error:
Killed (program cc1)`, and then further down the line I get a bunch of python
errors, with easy_install I get: `ImportError: No module named
numpy.distutils`, and with pip I get: `UnicodeDecodeError: 'ascii' codec can't
decode byte 0xe2 in position 72: ordinal not in range(128)`.
The EC2 instance is running kernel 3.4.43-43.43.amzn1.x86_64. Has anybody
solved this problem? Numpy has always been hard for me to install, but I can
usually figure it out... at this point I don't care whether it is in it's own
virtualenv, I just want to get it installed.
Answer: Requirements for installing Numpy
* c compiler (gcc)
* fortran compiler (gfortran)
* python header files (2.4.x - 3.2.x)
* Strongly recommended BLAS or LAPACK
I wrote a script to [install virtualenv and scikit-
learn](https://gist.github.com/dacamo76/4780765) along with all the
dependencies. You can follow up to the numpy install, which is pretty straight
forward. I copied the relevant code below.
sudo yum -y install gcc-c++ python27-devel atlas-sse3-devel lapack-devel
wget https://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.11.2.tar.gz
tar xzf virtualenv-1.11.2.tar.gz
python27 virtualenv-1.11.2/virtualenv.py sk-learn
. sk-learn/bin/activate
pip install numpy
Just copy/paste, hit enter, (get a cup of coffee) and you're ready to go with
virtualenv and numpy on EC2.
If you want to verify that numpy found the optimized linear algebra libraries,
run:
(sk-learn)[ec2-user@ip-10-99-17-223 ~]$ python -c "import numpy; numpy.show_config()"
if you see something similar to the following you're all set.
atlas_threads_info:
libraries = ['lapack', 'ptf77blas', 'ptcblas', 'atlas']
library_dirs = ['/usr/lib64/atlas-sse3']
define_macros = [('ATLAS_INFO', '"\\"3.8.4\\""')]
language = f77
include_dirs = ['/usr/include']
blas_opt_info:
libraries = ['ptf77blas', 'ptcblas', 'atlas']
library_dirs = ['/usr/lib64/atlas-sse3']
define_macros = [('ATLAS_INFO', '"\\"3.8.4\\""')]
language = c
include_dirs = ['/usr/include']
atlas_blas_threads_info:
libraries = ['ptf77blas', 'ptcblas', 'atlas']
library_dirs = ['/usr/lib64/atlas-sse3']
define_macros = [('ATLAS_INFO', '"\\"3.8.4\\""')]
language = c
include_dirs = ['/usr/include']
lapack_opt_info:
libraries = ['lapack', 'ptf77blas', 'ptcblas', 'atlas']
library_dirs = ['/usr/lib64/atlas-sse3']
define_macros = [('ATLAS_INFO', '"\\"3.8.4\\""')]
language = f77
include_dirs = ['/usr/include']
lapack_mkl_info:
NOT AVAILABLE
blas_mkl_info:
NOT AVAILABLE
mkl_info:
NOT AVAILABLE
For a more detailed explanation, you can read [installing-scikit-learn-on-
amazon-ec2](http://dacamo76.com/blog/2012/12/07/installing-scikit-learn-on-
amazon-ec2/). I wrote the blog post specifically to remember the installation
steps and have a short how-to guide. I try to keep the post and the install
script up to date.
|
django.contrib.comments.moderation.AlreadyModerated error in zinnia django
Question: I had a django app in which i am using `django-zinnia-blog` for my blog
functionality.
**Issue One**
And now i updated `zinnia` with latest `github` version and i am getting the
below wierd error
Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x941554c>>
Traceback (most recent call last):
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 92, in inner_run
self.validate(display_num_errors=True)
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/core/management/base.py", line 280, in validate
num_errors = get_validation_errors(s, app)
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/core/management/validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/db/models/loading.py", line 166, in get_app_errors
self._populate()
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/db/models/loading.py", line 72, in _populate
self.load_app(app_name, True)
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/db/models/loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/user/name/virtualenvironment/apps/proname/proname/apps/zinnia/models/__init__.py", line 19, in <module>
moderator.register(Entry, EntryCommentModerator)
File "/home/user/Envs/zinnia/local/lib/python2.7/site-packages/django/contrib/comments/moderation.py", line 305, in register
raise AlreadyModerated("The model '%s' is already being moderated" % model._meta.module_name)
django.contrib.comments.moderation.AlreadyModerated: The model 'entry' is already being moderated
`django version -- 1.5.3`
So why it is displaying `AlreadyModerated` error when trying to update the
`zinnia` witj latest version ?
**Issue Two**
Below are my `specs/setings`
**settings.py**
ZINNIA_ENTRY_BASE_MODEL = 'proname.apps.app_name.models.EntryBase'
ZINNIA_SAVE_PING_DIRECTORIES = False
ZINNIA_PING_EXTERNAL_URLS = False
Actually i am trying to extend the `Entry` model as below
from zinnia.models_bases.entry import AbstractEntry
class EntryBase(AbstractEntry):
pass
class Meta(AbstractEntry.Meta):
abstract = True
verbose_name_plural = _("Entry")
verbose_name_plural = _("Entries")
def __unicode__(self):
return u'Entry %s' % self.title
`django version -- 1.4.5`
When i used above django version i am getting an extra error along with above
one
raise ImproperlyConfigured('%s cannot be imported' % model_path)
django.core.exceptions.ImproperlyConfigured: zinnia.models_bases.entry.AbstractEntry cannot be imported
So can anyone please let me know to solve the above issues like
`AlreadyModerated` when updating to latest github zinnia code
Trying to extend the `Entry` model ?
and made the zinnia work correctly ?
Answer: I had the same problem and I figure out the problem changing version of zinnia
to 0.14.3
> Zinnia 0.15 only works with django 1.7
>
> Use v0.14.3 instead.
>
> (_<https://github.com/Fantomas42/django-blog-zinnia/issues/388>_)
|
python manage.py syncdb errors
Question: I guys when run the command python manage.py syncdb i have the following
errors:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 469, in execute_manager
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 77, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/syncdb.py", line 8, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/usr/local/lib/python2.7/dist-packages/django/core/management/sql.py", line 9, in <module>
from django.db import models
File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 11, in <module>
if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 48, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 152, in __init__
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Someone can help me?
Thank you
Answer: I think it's all here: The SECRET_KEY setting must not be empty. [Django
docs](https://docs.djangoproject.com/en/dev/releases/1.4/#secret-key-setting-
is-required)
Set the value SECRET_KEY
|
Python console output gets overwritten in Debian 6
Question: I have a small script in python which automates installation of a few packages
like wget, git, using apt-get in Debian 6 (Python 2.6.6). the script then
installs `pip` and then using `pip`, installs _requests_ and _phpserialize_.
The following is the output got when the script is run:
root@ffVMdeb64:~# python test.py
Reading package lists... Done
mkdir: cannot create directory `/usr/local/src/forpip': File exists
Building dependency tree
Reading state information... Done
git is already the newest version.
wget is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Reading package lists... Done
Building dependency tree... 50%
Building dependency tree
Reading state information... Done
Requirement already satisfied (use --upgrade to upgrade): phpserialize in /usr/local/lib/python2.6/dist-packages
Cleaning up...
Requirement already satisfied (use --upgrade to upgrade): requests in /usr/local/lib/python2.6/dist-packages
Cleaning up...
git is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
At the end, there the script takes some input from the user. However, the
`raw_input` statement gets executed while the output for the install process
is still going on and hence gets overwritten. Notice the blank space between 2
blocks of output above - that is where the `raw_input` statement gets printed
and then overwritten.
The relevant parts of the script is as follows:
subprocess.call("pip install phpserialize &> /dev/null 2>&1", shell=True)
subprocess.call("pip install requests &> /dev/null 2>&1", shell=True)
subprocess.call("apt-get install git -y &> /dev/null 2>&1", shell=True)
import phpserialize
import requests
from phpserialize import serialize
from phpserialize import unserialize
def checktext():
text = raw_input("\n\n\nEnter your text:")
return text
itext = checktext()
I tested the exact same script in CentOS 6.3 and 6.4 and it worked as
expected. I guess it has something to do with the `Building dependency tree...
50%` part of `apt-get` but i am not sure.
How can I correct this?
Answer: This might not be the exact solution and I'm pretty sure there'll be a better
solution but i think if you try `sleep` after your last `apt-get` statement,
it might work.
As per your code:
import time
subprocess.call("pip install phpserialize &> /dev/null 2>&1", shell=True)
subprocess.call("pip install requests &> /dev/null 2>&1", shell=True)
subprocess.call("apt-get install git -y &> /dev/null 2>&1", shell=True)
time.sleep(5)
import phpserialize
import requests
from phpserialize import serialize
from phpserialize import unserialize
def checktext():
text = raw_input("\n\n\nEnter your text:")
return text
itext = checktext()
That causes the whole `apt-get` to execute first and then moves on to your
`text=...` statment.
Hope this helps
|
Live plotting using matplotlib without hault
Question: Here is a minimum working example of my code.
I am trying to plot a live graph using matplotlib by taking some inputs from
the user via gui. For building the gui, I used the library
[easygui](http://easygui.sourceforge.net/tutorial/)
However, there is one problem: the graph stops building while taking an update
from the user and I wish it to continue. Is there something that I'm missing
here.
#!/usr/bin/env python
from easygui import *
from matplotlib.pylab import *
import numpy
import random
n = 0
fig=plt.figure()
x=list()
y=list()
plt.title("live-plot generation")
plt.xlabel('Time(s)')
plt.ylabel('Power(mw)')
plt.ion()
plt.show()
calculated=[random.random() for a in range(40)]
recorded=[random.random() for a in range(40)]
possible=[random.random() for a in range(5)]
plt.axis([0,40,0,10000])
for a in range(0, len(recorded)):
temp_y= recorded[a]
x.append(a)
y.append(temp_y)
plt.scatter(a,temp_y)
plt.draw()
msg = "Change"
title = "knob"
choices = possible
if a>9:
b = (a/10) - numpy.fix(a/10)
if b==0:
choice = choicebox(msg, title, choices)
print "change:", choice
here is the download link for
[easygui](http://switch.dl.sourceforge.net/project/easygui/0.96/easygui-0.96.tar.gz)
sudo python setup.py install
based on your version of linux or OS. use the following
[link](http://easygui.sourceforge.net/download/version_0.96/index.html)
Answer: Thanks to `J.F. Sebastian`
import easygui
from Tkinter import Tk
from contextlib import contextmanager
@contextmanager
def tk(timeout=5):
root = Tk() # default root
root.withdraw() # remove from the screen
# destroy all widgets in `timeout` seconds
func_id = root.after(int(1000*timeout), root.quit)
try:
yield root
finally: # cleanup
root.after_cancel(func_id) # cancel callback
root.destroy()
with tk(timeout=1.5):
easygui.msgbox('message') # it blocks for at most `timeout` seconds
|
Efficient netCDF analysis when looping through data
Question: This is a follow up question related to [this
question](http://stackoverflow.com/questions/18665078/loop-through-netcdf-
files-and-run-calculations-python-or-r).
Thanks to previous help I have successfully imported a netCDF file (or files
with MFDataset) and am able to compare the different times to one another to
create another cumulative dataset. Here is a piece of the current code.
from numpy import *
import netCDF4
import os
f = netCDF4.MFDataset('air.2m.1979.nc')
atemp = f.variables['air']
ntimes, ny, nx = atemp.shape
cold_days = zeros((ntimes, ny, nx), dtype=int)
for i in range(ntimes):
for b in range(ny):
for c in range(nx):
if i == 1:
if atemp[i,b,c] < 0:
cold_days[i,b,c] = 1
else:
cold_days[i,b,c] = 0
else:
if atemp[i,b,c] < 0:
cold_days[i,b,c] = cold_days[i-1,b,c] + 1
else:
cold_days[i,b,c] = 0
This seems like a brute force way to get the job done, and though it works it
takes a very long time. I'm not sure if it takes such a long time because I'm
dealing with 365 349x277 matrices (35,285,645 pixels) or if my old school
brute force way is simply slow in comparison to some built in python methods.
Below is an example of what I believe the code is doing. It looks at Time and
increments cold days if temp < 0\. If temp >= 0 than cold days resets to 0. In
the below image you will see that the cell at row 2, column 1 increments each
Time that passes but the cell at row 2, column 2 increments at Time 1 but
resets to zero on Time 2.
Is there a more efficient way to rip through this netCDF dataset to perform
this type of operation? 
Answer: Seems like this is a minor modification -- just write the data out at each
time step. Something close to this should work:
from pylab import *
import netCDF4
# open NetCDF input files
f = netCDF4.MFDataset('/usgs/data2/rsignell/models/ncep/narr/air.2m.19??.nc')
# print variables
f.variables.keys()
atemp = f.variables['air']
print atemp
ntimes, ny, nx = shape(atemp)
cold_days = zeros((ny,nx),dtype=int)
# create output NetCDF file
nco = netCDF4.Dataset('/usgs/data2/notebook/cold_days.nc','w',clobber=True)
nco.createDimension('x',nx)
nco.createDimension('y',ny)
nco.createDimension('time',ntimes)
cold_days_v = nco.createVariable('cold_days', 'i4', ( 'time', 'y', 'x'))
cold_days_v.units='days'
cold_days_v.long_name='total number of days below 0 degC'
cold_days_v.grid_mapping = 'Lambert_Conformal'
timeo = nco.createVariable('time','f8',('time'))
lono = nco.createVariable('lon','f4',('y','x'))
lato = nco.createVariable('lat','f4',('y','x'))
xo = nco.createVariable('x','f4',('x'))
yo = nco.createVariable('y','f4',('y'))
lco = nco.createVariable('Lambert_Conformal','i4')
# copy all the variable attributes from original file
for var in ['time','lon','lat','x','y','Lambert_Conformal']:
for att in f.variables[var].ncattrs():
setattr(nco.variables[var],att,getattr(f.variables[var],att))
# copy variable data for time, lon,lat,x and y
timeo[:] = f.variables['time'][:]
lato[:] = f.variables['lat'][:]
xo[:] = f.variables['x'][:]
yo[:] = f.variables['y'][:]
for i in xrange(ntimes):
cold_days += atemp[i,:,:].data-273.15 < 0
# write the cold_days data
cold_days_v[i,:,:]=cold_days
# copy Global attributes from original file
for att in f.ncattrs():
setattr(nco,att,getattr(f,att))
nco.Conventions='CF-1.6'
nco.close()
|
Python SST tests never fail
Question: I've just started looking at [SST](http://testutils.org/sst/index.html) this
morning. I've written this simple test case, which always passes:
from sst.actions import *
from sst import cases
class RootTest(cases.SSTTestCase):
def test_root_page(self):
go_to('http://localhost:8888/')
assert_title_contains('Booga')
assert_button("file_select")
assert_button("upload")
return self
class LoginTest(cases.SSTTestCase):
def login(self):
go_to('http://localhost:8888/login')
assert_element(id="Email")
assert_element(id="Passwd")
assert_element(id="booga")
return self
There are no 'booga's in my code.
When I do sst-run sst_test I get the following:
Tests running...
DEBUG:SST:Starting browser (attempt: 1)
DEBUG:SST:Cannot connect to process 5392 with port: 32773, count 1
DEBUG:SST:Cannot connect to process 5392 with port: 32773, count 2
DEBUG:SST:Browser started: firefox
DEBUG:SST:Stopping browser
sst_test ... OK (2.317 secs)
Ran 1 test in 2.317s
OK
It's an ubuntu 12.04 system with py 2.7.3. Why aren't the tests failing?
Answer: you need to use your own runner. `sst-run` is for running SST's script-based
tests only.
see: <http://testutils.org/sst/#using-sst-in-unittest-test-suites>
|
ssh.exec_command("shutdown -h 17:00 &")
Question: I have a Python Paramiko script that sends commands to remote hosts on out
intranet. There are times when I would like to send the shutdown command to
several hosts at once. The issue is that the shutdown command simply sits and
waits unless you background it. I have tried using the ampersand (bare as
above, or escaped: \&). Here is a small test program. My os is RHEL Linux 5.9
(Python 2.4.3). Note that the sudoers disables requiretty for some users.
#!/usr/bin/python
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("<hostname>",username="<my username>", password="<mypassword>")
stdin, stdout, stderr = ssh.exec_command("sudo /sbin/shutdown -h 17:00 \&")
stdin.write('\n')stdin.flush()
data = stdout.read().splitlines()
for line in data:
print line
Answer: I have solved the issue using the shutdown command as it is intended. First do
not escape the ampersand (\&). Since the shutdown command does not return
anything to stdout, I just eliminate those lines dealing with the output. The
reason for wanting to use shutdown with a time is for user notification.
#!/usr/bin/python
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("<hostname>",username="<my username>", password="<mypassword>")
stdin, stdout, stderr = ssh.exec_command("sudo /sbin/shutdown -h 17:00 &")]
ssh.close()
|
Strange Python Module issue, just on a mac
Question: I have psutil installed, I can import it fine and use it to pull information,
if I show all the modules, I can see it is installed. However if I run the
code below
try:
imp.find_module('psutil')
pass
except ImportError:
print 'This program needs psutil to work, as this is not installed the script will now exit'
sys.exit()`
It says it's not installed. I have this bit of code in a script and it works,
on Windows, Solaris, Linux just not my Mac.
Any help is appreciated
Answer: I have now resolved the issue. It's very strange, as I mentioned if I load
python from the terminal, it loads the module and I can use it. I can also see
it if I see all the modules installed.
I done a search on the drive and I found
psutil-1.0.1-py2.7-macosx-10.7-intel.egg, I have created a softlink to the
file
cd /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
sudo ln -s /Library/Python/2.7/site-packages/psutil-1.0.1-py2.7-macosx-10.7-intel.egg psutil.py
Once this was done, everything is working fine, I can still call it
interactively but now the above snippet of code works
Thanks to everyone's help
|
Python module organization to make import statement cleaner
Question: I have a directory B inside directory A, which resides in a directory included
in `PYTHONPATH`.
Now lets say that within directory B i have files - B_file_1.py, B_file_2.py,
with each file defining a single function (i.e. B_file_1.py defines
`B_file_1`).
I want to use this collection of files as a python package. But now when I
want to use the method `B_file_1`, I have to write this long statement:
from A.B.B_file_1 import B_file_1
What I would like is to have the convenience of simply writing this instead,
(while maintaing the directory and file setup I currently have):
from A.B import B_file_1
Is there any python module hack to do this?
Answer: Add this code in `A/B/__init__.py`:
from B_file_1 import B_file_1
|
Python Index out of range on Cash flow
Question: Having trouble with a code that should read comma separated values out of .txt
file, sort into arrays based on negativity, and then plot data. Here is the
code, followed by 2 .txt files, the first one works, but the second one
doesn't
#check python is working
print "hello world"
#import ability to plot and use matrices
import matplotlib.pylab as plt
import numpy as np
#declare variables
posdata=[]
negdata=[]
postime=[]
negtime=[]
interestrate=.025
#open file
f= open('/Users/zacharygastony/Desktop/CashFlow_2.txt','r')
data = f.readlines()
#split data into arrays
for y in data:
w= y.split(",")
if float(w[1])>0:
postime.append(int(w[0]))
posdata.append(float(w[1]))
else:
negtime.append(int(w[0]))
negdata.append(float(w[1]))
print "Inflow Total: ", posdata
print "Inflow Time: ", postime
print "Outflow Total: ", negdata
print "Outflow Time: ", negtime
#plot the data
N=len(postime)
M=len(negtime)
ind = np.arange(N+M) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, posdata+negdata, width, color='r')
# add some
ax.set_ylabel('Cash Amount')
ax.set_title('Cash Flow Diagram')
ax.set_xlabel('Time')
plt.plot(xrange(0,M+N))
plt.show()'
.txt 1_**___ ____**
0,3761.97
1,-1000
2,-1000
3,-1000
4,-1000
.txt 2_**___ _____ _**
0,1000
1,-1000
2,1000
3,-1000
My error is as follows:
>>> runfile('/Users/zacharygastony/cashflow.py', wdir=r'/Users/zacharygastony')
hello world
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/zacharygastony/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "/Users/zacharygastony/cashflow.py", line 24, in <module>
if float(w[1])>0:
IndexError: list index out of range
Answer: One error that I can spot is with " if float(w[1])>0:" -- it shoudl take into
account that the w[1] would be a set of two values separated by a space. Here
is how w would look like for the second file: "['0', '1000 1', '-1000 2',
'1000 3', '-1000\n']". So, w[1] would be "1000 1" and taking a float for this
value would be an error. So, if you really want to access the second element,
then one way is to split it using the default space delimiter and pick the
first one (or the second one). Something like: "if
float((w[1].split())[0])>0:".
|
Reading Serial Data from Arduino with Python
Question: I'm working on a little project using the [MaxSonar EZ1 ultrasonic range
sensor](http://www.maxbotix.com/Ultrasonic_Sensors/MB1010.htm) and Arduino
Diecimila.
Using the [MaxSonar playground
code](http://playground.arduino.cc/Main/MaxSonar), I have Arduino writing the
number of inches to serial every .5 seconds, along with a delimiter. When
monitoring the serial data, the output looks similar to:
5.13.15.12.123.39.345...
On the Python side, I have a basic Flask app with a /distance route that
returns a JSON object with the serial value:
from flask import Flask
from flask import render_template
import serial
import json
import random
app = Flask(__name__,
static_folder="public",
template_folder="templates")
port = "/dev/tty.usbserial-A6004amR"
ser = serial.Serial(port,9600)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/distance")
def distance():
distance = read_distance_from_serial()
return json.dumps({'distance': distance})
def read_distance_from_serial():
x = ser.read();
a = '';
while x is not '.':
a += x;
x = ser.read()
print(a)
return a
# return random.randint(1, 100)
if __name__ == "__main__":
app.debug = True
app.run()
And index.html is a basic site with some JS that polls /distance every half
second for a new reading. With the value, I should be able to build an
interesting UI that changes based on how close/far I am from the sonar.
$(document).ready(function() {
window.GO = function() {
this.frequency = 500; // .5 seconds
this.init = function() {
window.setInterval(this.update_distance, 500);
}
this.update_distance = function() {
$.get('/distance', function(response) {
var d = response.distance;
$('#container').animate({"width": d + "%"});
}, 'json')
}
}
go = new GO();
go.init();
});
**The Question**
The issue I'm running into is that there is no guarantee that when python
reads from serial, that there will be a value. Often times, when it polls, I
get either an empty value or a partial value, while other times it is spot on.
How can I change my technique such that I am able to consistently poll the
serial data and receive the last good reading from the Arduino serial output?
Answer: You want to set your serial reading to happen in the background and not on
demand. You can use
[threading](http://docs.python.org/2/library/threading.html) and
[Queue](http://docs.python.org/2/library/queue.html). You add your serial
values to the Queue once you determine you have a valid value, and then your
socket call simply pulls from the Queue. It'll be something like this:
from flask import Flask
from flask import render_template
import serial
import json
import random
import threading, Queue
import logging
logging.basicConfig(filename=__file__.replace('.py','.log'),level=logging.DEBUG,format='%(asctime)s [%(name)s.%(funcName)s] %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filemode='a')
class maxSonarSerialThread(threading.Thread):
def __init__(self, dataQ, errQ, port=None, baudrate=None):
self.logger = logging.getLogger('sonarSerialThread')
self.logger.debug('initializing')
threading.Thread.__init__(self)
self.ser = serial.Serial()
self.ser.timeout = 1
if port is None:
self.ser.port = "/dev/tty.usbserial-A6004amR"
else:
self.ser.port = port
if baudrate is None:
self.baudrate = 115200
else:
self.baudrate = baudrate
#self.ser.flushInput()
self.readCount = 0
self.sleepDurSec = 5
self.waitMaxSec = self.sleepDurSec * self.ser.baudrate / 10
self.dataQ = dataQ
self.errQ = errQ
self.keepAlive = True
self.stoprequest = threading.Event()
self.setDaemon(True)
self.dat = None
self.inputStarted = False
self.ver = ver
def run(self):
self.logger.debug('running')
dataIn = False
while not self.stoprequest.isSet():
if not self.isOpen():
self.connectForStream()
while self.keepAlive:
dat = self.ser.readline()
//some data validation goes here before adding to Queue...
self.dataQ.put(dat)
if not self.inputStarted:
self.logger.debug('reading')
self.inputStarted = True
self.dat.close()
self.close()
self.join_fin()
def join_fin(self):
self.logger.debug('stopping')
self.stoprequest.set()
def connectForStream(self, debug=True):
'''Attempt to connect to the serial port and fail after waitMaxSec seconds'''
self.logger.debug('connecting')
if not self.isOpen():
self.logger.debug('not open, trying to open')
try:
self.open()
except serial.serialutil.SerialException:
self.logger.debug('Unable to use port ' + str(self.ser.port) + ', please verify and try again')
return
while self.readline() == '' and self.readCount < self.waitMaxSec and self.keepAlive:
self.logger.debug('reading initial')
self.readCount += self.sleepDurSec
if not self.readCount % (self.ser.baudrate / 100):
self.logger.debug("Verifying MaxSonar data..")
//some sanity check
if self.readCount >= self.waitMaxSec:
self.logger.debug('Unable to read from MaxSonar...')
self.close()
return False
else:
self.logger.debug('MaxSonar data is streaming...')
return True
def isOpen(self):
self.logger.debug('Open? ' + str(self.ser.isOpen()))
return self.ser.isOpen()
def open(self):
self.ser.open()
def stopDataAquisition(self):
self.logger.debug('Falsifying keepAlive')
self.keepAlive = False
def close(self):
self.logger.debug('closing')
self.stopDataAquisition()
self.ser.close()
def write(self, msg):
self.ser.write(msg)
def readline(self):
return self.ser.readline()
app = Flask(__name__,
static_folder="public",
template_folder="templates")
port = "/dev/tty.usbserial-A6004amR"
dataQ = Queue.Queue()
errQ = Queue.Queue()
ser = maxSonarSerialThread(dataQ, errQ, port=port, ver=self.hwVersion)
ser.daemon = True
ser.start()
@app.route("/")
def index():
return render_template('index.html')
@app.route("/distance")
def distance():
distance = read_distance_from_serial()
return json.dumps({'distance': distance})
def read_distance_from_serial():
a = dataQ.get()
print str(a)
return a
You'll need to add a method to join the thread for a graceful exit, but that
should get you going
|
Deploying Django app on Heroku: Can I manually set environment variables in the .env file? Do I need to install tools like autoenv, heroku-config...?
Question: ## My goal:
I intend to follow "The Twelve-Factor App" methodology for building my Django
app on Heroku.
## Introduction:
I'm following the "Getting Started with Django on Heroku" quick start guide.
At the moment I have the following directory structure:
~/Projects/
hellodjango_rep/
.env (empty)
.git
.gitignore
Procfile
requirements.txt
hellodjango/
manage.py
hellodjango/
__init__.py
settings/
urls.py
wsgi.py
I installed django-toolbelt, created my simple Django application, started the
process in my Procfile... Everything seemed to be working fine, but the
problems started when I configured the application for the Heroku environment
and added:
import dj_database_url
DATABASES['default'] = dj_database_url.config()
to the bottom of my settings.py file.
I pushed my application’s repository to Heroku, visited the app in my browser
with `$ heroku open` successfully, but locally: `dj_database_url.config()`
**returned an empty dictionary**.
## **Locally:**
OS X 10.8.4
pip==1.4.1
virtualenv==1.10.1
virtualenvwrapper==4.1.1
wsgiref==0.1.2
Postgres.app running on Port 5432
Environment variables:
mac-pol:hellodjango_rep oubiga$ python
>>> import os
>>> os.environ
{
'PROJECT_HOME': '/Users/oubiga/Projects'...
'PATH': '/usr/local/heroku/bin:/usr/local/share/python:/usr/local/bin:/Applications/Postgres.app/Contents/MacOS/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin'...
'HOME': '/Users/oubiga'...
'WORKON_HOME': '/Users/oubiga/Envs'...
'VIRTUALENVWRAPPER_HOOK_DIR': '/Users/oubiga/Envs'...
'PWD': '/Users/oubiga/Projects/hellodjango_rep'
}
## hellodjango_venv:
Django==1.5.2
dj-database-url==0.2.2
dj-static==0.0.5
django-toolbelt==0.0.1
gunicorn==18.0
psycopg2==2.5.1
static==0.4
This is what I have in my wsgi.py file:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hellodjango.hellodjango.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
This is what I have in my manage.py file:
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hellodjango.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
This is what I have in my Procfile:
web: gunicorn hellodjango.hellodjango.wsgi
Environment variables:
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ python hellodjango/manage.py shell
>>> import os
>>> os.environ
{
'PROJECT_HOME': '/Users/oubiga/Projects'...
'PATH': '/Users/oubiga/Envs/hellodjango_venv/bin:/usr/local/heroku/bin:/usr/local/share/python:/usr/local/bin:/Applications/Postgres.app/Contents/MacOS/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin',
'HOME': '/Users/oubiga'...
'WORKON_HOME': '/Users/oubiga/Envs'...
'VIRTUAL_ENV': '/Users/oubiga/Envs/hellodjango_venv'...
'VIRTUALENVWRAPPER_HOOK_DIR': '/Users/oubiga/Envs'...
'PWD': '/Users/oubiga/Projects/hellodjango_rep'...
'DJANGO_SETTINGS_MODULE': 'hellodjango.settings'
}
## On Heroku:
Environment variables:
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ heroku run python hellodjango/manage.py shell
>>> import os
>>> os.environ
{
'DATABASE_URL': 'postgres://dbuser:[email protected]:5432/dbname',
'HEROKU_POSTGRESQL_ORANGE_URL': 'postgres://dbuser:[email protected]:5432/dbname',
'LIBRARY_PATH': '/app/.heroku/vendor/lib', 'PWD': '/app'...
'DJANGO_SETTINGS_MODULE': 'hellodjango.settings',
'PYTHONHOME': '/app/.heroku/python'...
'PYTHONPATH': '/app/'...
'DYNO': 'run.9068',
'LD_LIBRARY_PATH': '/app/.heroku/vendor/lib'...
'HOME': '/app', '_': '/app/.heroku/python/bin/python',
'PATH': '/app/.heroku/python/bin:/usr/local/bin:/usr/bin:/bin'...
}
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ heroku config
=== damp-dusk-5382 Config Vars
DATABASE_URL: postgres://dbuser:[email protected]:5432/dbname
HEROKU_POSTGRESQL_ORANGE_URL: postgres://dbuser:[email protected]:5432/dbname
## Research:
**_Store config in the environment:_** from The Twelve-Factor App
@adamwiggins wrote:
> **The twelve-factor app stores config in environment variables**... Env vars
> are easy to change between deploys without changing any code; unlike config
> files.
**_`dj_database_url.config()` is returning an empty object:_** from Heroku
Forums
@chrisantonick replied:
> ... dj_database_url.config() gets the Postgres credentials from the Heroku
> environment variables. **But, on your local machine, those variables aren't
> there**. You have to put them in your /venv/bin/activate shell script... put
> the variables in there. something like
> DATABASE_URL = "xxx"
> export DATABASE_URL
> For each thing it needs. Then... "deactivate"... and ..."activate" again to
> restart it.
**_Getting Started with Django and Heroku instructions raised
ImproperlyConfigured error:_** from Heroku Forums
@jwpe replied:
> ... dj-database-url is a great utility, as it allows you to use exactly the
> same settings.py code in your development and production environments, as
> recommended in the "12 factor app principles"... what
> dj_database_url.config() is doing is looking for the DATABASE_URL
> environment variable, and then parsing it into Django's preferred format...
> if you haven't manually created and promoted a postgres DB on Heroku,
> DATABASE_URL will not be present and the ImproperlyConfigured error will be
> raised. Setting the default for dj_database_url.config() as your local DB
> URL is one way to make sure that your application will work in a development
> environment. However, it is not necessarily the only way. Perhaps **a better
> alternative is to manually set DATABASE_URL in your local .env file. Then,
> when running your app locally using Foreman, it will be loaded as an
> environment variable and dj_database_url will find it.** So your .env would
> contain:
`DATABASE_URL=postgres://user:pass@localhost/dbname`
> Meaning that in `settings.py` you would only need to have:
>
`DATABASES['default']= dj_database_url.config()`
> ...The advantage of using a local environment variable instead of a single,
> hard-coded default is that your code will run in any environment where the
> DATABASE_URL is set. **If you change the name of your local DB, or want to
> run your code on a different dev machine, you only need to update your .env
> file instead of tinkering with settings.py**.
**_How to manage production/staging/dev Django settings?:_** from Heroku
Forums
@rdegges replied:
> ... trying to get your application to behave in a way such that:
>
> * When you're running the app on your laptop, it uses your local Postgres
> server.
> * When you're running the app on your staging Heroku app, it uses the
> Postgres server addon.
> * When you're running the app on your production Heroku app, it uses the
> Postgres server addon.
>
>
> The best way to accomplish this is by using environment variables!…
> Environment variables are the most elegant (and scalable) way to handle
> application configuration between different environments… Instead of having
> many settings files, define a single file: settings.py, and have it make use
> of environment variables to pull service information and credentials... On
> Heroku, you can set environment variables manually by running:
>
>
> $ heroku config:set SOME_VARIABLE=some_value
>
>
> ... there's always Kenneth Reitz's great autoenv tool. This lets you define
> a simple .env file in your project directory… And each time you enter your
> project directory, those environment variables will be automatically set so
> that you don't have to do anything special! Just run your project and
> everything will work as expected: `python manage.py runserver`
## As a First Attempt:
I manually set `DATABASE_URL` in my .env file:
`DATABASE_URL=postgres://dbuser:[email protected]:5432/dbname`
But when I run `$ foreman start` command:
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ foreman start
17:25:39 web.1 | started with pid 319
17:25:39 web.1 | 2013-09-11 17:25:39 [319] [INFO] Starting gunicorn 18.0
17:25:39 web.1 | 2013-09-11 17:25:39 [319] [INFO] Listening at: http://0.0.0.0:5000 (319)
17:25:39 web.1 | 2013-09-11 17:25:39 [319] [INFO] Using worker: sync
17:25:39 web.1 | 2013-09-11 17:25:39 [322] [INFO] Booting worker with pid: 322
and tried to open my app in the browser `http://0.0.0.0:5000`:
17:26:59 web.1 | 2013-09-11 10:26:59 [322] [ERROR] Error handling request
17:26:59 web.1 | Traceback (most recent call last):
17:26:59 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 131, in handle_request
17:26:59 web.1 | respiter = self.wsgi(environ, resp.start_response)
17:26:59 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/dj_static.py", line 59, in __call__
17:26:59 web.1 | return self.application(environ, start_response)
17:26:59 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 236, in __call__
17:26:59 web.1 | self.load_middleware()
17:26:59 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 53, in load_middleware
17:26:59 web.1 | raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
17:26:59 web.1 | ImproperlyConfigured: Error importing middleware django.contrib.auth.middleware: "dlopen(/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @loader_path/../lib/libssl.1.0.0.dylib
17:26:59 web.1 | Referenced from: /Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/psycopg2/_psycopg.so
17:26:59 web.1 | Reason: image not found"
However, `dj_database_url.config()` returned:
{
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'HOST': 'ec2-23-21-196-147.compute-1.amazonaws.com',
'USER': 'dbuser',
'PASSWORD': 'dbpassword',
'PORT': 5432
}
## As a Second Attempt:
I manually set `DATABASE_URL` in my .env file changing the host. I replaced
"ec2-184-73-162-34.compute-1.amazonaws.com:5432" by "localhost:5000". `$
deactivate` and then `$ workon hellodjango_venv` again.
`DATABASE_URL=postgres://dbuser:dbpassword@localhost:5000/dbname`
But, when I run `$ foreman start` command:
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ foreman start
17:38:41 web.1 | started with pid 687
17:38:41 web.1 | 2013-09-11 17:38:41 [687] [INFO] Starting gunicorn 18.0
17:38:41 web.1 | 2013-09-11 17:38:41 [687] [INFO] Listening at: http://0.0.0.0:5000 (687)
17:38:41 web.1 | 2013-09-11 17:38:41 [687] [INFO] Using worker: sync
17:38:41 web.1 | 2013-09-11 17:38:41 [690] [INFO] Booting worker with pid: 690
and tried to open my app in the browser `http://0.0.0.0:5000`:
17:38:46 web.1 | 2013-09-11 10:38:46 [690] [ERROR] Error handling request
17:38:46 web.1 | Traceback (most recent call last):
17:38:46 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 131, in handle_request
17:38:46 web.1 | respiter = self.wsgi(environ, resp.start_response)
17:38:46 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/dj_static.py", line 59, in __call__
17:38:46 web.1 | return self.application(environ, start_response)
17:38:46 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 236, in __call__
17:38:46 web.1 | self.load_middleware()
17:38:46 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 53, in load_middleware
17:38:46 web.1 | raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
17:38:46 web.1 | ImproperlyConfigured: Error importing middleware django.contrib.auth.middleware: "dlopen(/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @loader_path/../lib/libssl.1.0.0.dylib
17:38:46 web.1 | Referenced from: /Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/psycopg2/_psycopg.so
17:38:46 web.1 | Reason: image not found"
This time, `dj_database_url.config()` returned:
{
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'HOST': 'localhost',
'USER': 'dbuser',
'PASSWORD': 'dbpassword',
'PORT': 5000
}
## As a Third Attempt:
I installed autoenv `mac-pol:~ oubiga$ pip install autoenv`
From this [Cookbook](https://github.com/kennethreitz/autoenv/wiki/Cookbook)
Kenneth Reitz wrote, I put:
use_env() {
typeset venv
venv="$1"
if [[ "${VIRTUAL_ENV:t}" != "$venv" ]]; then
if workon | grep -q "$venv"; then
workon "$venv"
else
echo -n "Create virtualenv $venv now? (Yn) "
read answer
if [[ "$answer" == "Y" ]]; then
mkvirtualenv "$venv"
fi
fi
fi
}
in my .bashrc file.
I run `$ foreman start` command:
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ foreman start
18:11:57 web.1 | started with pid 1104
18:11:57 web.1 | 2013-09-11 18:11:57 [1104] [INFO] Starting gunicorn 18.0
18:11:57 web.1 | 2013-09-11 18:11:57 [1104] [INFO] Listening at: http://0.0.0.0:5000 (1104)
18:11:57 web.1 | 2013-09-11 18:11:57 [1104] [INFO] Using worker: sync
18:11:57 web.1 | 2013-09-11 18:11:57 [1107] [INFO] Booting worker with pid: 1107
and tried to open my app in the browser `http://0.0.0.0:5000`: It worked!
^CSIGINT received
18:12:06 system | sending SIGTERM to all processes
18:12:06 web.1 | 2013-09-11 11:12:06 [1107] [INFO] Worker exiting (pid: 1107)
SIGTERM received
18:12:06 web.1 | 2013-09-11 18:12:06 [1104] [INFO] Handling signal: int
18:12:06 web.1 | 2013-09-11 18:12:06 [1104] [INFO] Shutting down: Master
18:12:06 web.1 | exited with code 0
**But,`dj_database_url.config()` again returns an empty dictionary.**
## As a Final Attempt:
I was curious about the `python manage.py runserver` command and I checked it
out.
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ foreman run python hellodjango/manage.py runserver
Validating models...
0 errors found
September 11, 2013 - 18:42:37
Django version 1.5.2, using settings 'hellodjango.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
and tried to open my app in the browser `http://127.0.0.1:8000/`: It didn't
work!
An `ImportError: No module named hellodjango.urls` was raised.
I replaced `ROOT_URLCONF = 'hellodjango.hellodjango.urls'` in my settings.py
file by `ROOT_URLCONF = 'hellodjango.urls'` and it finally worked.
**As expected,`dj_database_url.config()` returned an empty dictionary.**
## So:
Now, I feel a little overwhelmed. I'm afraid I'm misunderstanding some core
concept here.
* **What's the point to use gunicorn instead of the Django development server?**
* **Why does`dj_database_url.config()` sometimes return a fully populated dictionary, and sometimes an empty one?**
* **Can I manually set environment variables in the .env file? Do I need to install tools like autoenv, heroku-config...?**
Thank you in advance.
Answer: I got stuck with the postgres as well, here's what I did in the settings.py to
add local settings:
DATABASES = {
'default': dj_database_url.config(default='postgres://<user>:<password>@<host>/<dbname>')
}
Of course you have to have created the database following postgres steps.
Solution was from <https://discussion.heroku.com/t/dj-database-url-config-is-
returning-an-empty-object/55/9>
|
pyxb UnrecognizedDOMRootNodeError
Question: i've got the following xml schema:
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="DataPackage">
<xsd:sequence>
<xsd:element name="timestamp" type="xsd:float" default="0.0"/>
<xsd:element name="type" type="xsd:string" default="None"/>
<xsd:element name="host" type="xsd:string" default="None"/>
<xsd:element name="data" type="Data" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Data">
<xsd:sequence>
<xsd:element name="item" type="Item" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Item">
<xsd:sequence>
<xsd:element name="key" type="xsd:string"/>
<xsd:element name="val" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
I used `pyxbgen -u DataPackage.xsd -m DataPackage` to generate the
corresponding python classes and used these to generate the following xml
code:
<?xml version="1.0" encoding="utf-8"?>
<DataPackage>
<timestamp>1378970933.29</timestamp>
<type>None</type>
<host>Client 1</host>
<data>
<item>
<key>KEY1</key>
<val>value1</val>
</item>
</data>
</DataPackage>
If i try to read this using the following in python interpreter:
import DataPackage
xml = file("dataPackage-Test.xml").read()
data = DataPackage.CreateFromDocument(xml)
I get the exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "DataPackage.py", line 54, in CreateFromDocument
instance = handler.rootObject()
File "/usr/local/lib/python2.7/dist-packages/pyxb/binding/saxer.py", line 274, in rootObject
raise pyxb.UnrecognizedDOMRootNodeError(self.__rootObject)
pyxb.exceptions_.UnrecognizedDOMRootNodeError: <pyxb.utils.saxdom.Element object at 0x9c7c76c>
Anyone an idea what's wrong?
Answer: Your schema defines a top-level complex type named DataPackage, but does not
define any top-level elements. Thus the DOM element DataPackage has no
corresponding element that PyXB can use to process it.
You need to add something like:
<element name="DataPackage" type="DataPackage"/>
Note that in XML Schema the namespaces for elements and types are distinct,
but in Python they are not, so PyXB will rename one of them (the complex type
in this case) to avoid the conflict. See
<http://pyxb.sourceforge.net/arch_binding.html?highlight=conflict#deconflicting-
names>
|
Reading lines in captured stdout in python
Question: I am trying to capture stdout and then parse it after calling a function. I am
doing so by means of a cStringIO.StringIO object but the readline call yields
nothing. I have created below test to show you what's happening:
import cStringIO, sys
def readstream(s):
c = s.getvalue()
for i in c.split('\n'):
yield i
old_stdout = sys.stdout
stream = cStringIO.StringIO()
sys.stdout = stream
print ('testing this stuff')
print ('more testing of this')
sys.stdout = old_stdout
print 'getvalue:'
print stream.getvalue()
print 'readlines:'
for line in stream.readlines():
print line
print 'readstream:'
for line in readstream(stream):
print line
The generated output is:
getvalue:
testing this stuff
more testing of this
readlines:
readstream:
testing this stuff
more testing of this
How is it that the stream.readlines() is yielding nothing?
thanks
Answer: You've just finished writing into `stream`, so its file pointer is at the end
of the file.
`readlines` returns all lines from the current file pointer until the end of
the file. Since there are no lines from the end of the file to the end of the
file, it returns no lines.
If you want to move the file pointer back to the start of the file, use the
[`seek`](http://docs.python.org/2/library/stdtypes.html#file.seek) method:
print 'readlines:' # will print nothing
stream.seek(0)
for line in stream.readlines():
print line
* * *
A few side notes:
First, [there is almost never a good reason to use
`readlines()`](http://stupidpythonideas.blogspot.com/2013/06/readlines-
considered-silly.html), and especially not in this case. A file is _already_
an iterable of the lines in the file; there's no reason to create a list of
the same lines just to iterate it. This will give you the exact same result:
stream.seek(0)
for line in stream:
print line
… but simpler, faster, and without wasting memory.
Second, your `readstream` function is more complicated than it needs to be.
Normally, generators yielding values have advantages over lists—they let your
caller start working on the values as soon as each one is available instead of
waiting until they're all done, they don't waste memory building a list just
to iterate over it, etc. But in this case, you're already building a list by
calling `split`, so you might as well just return it:
def readstream(s):
c = s.getvalue()
return c.split('\n')
|
Unable to send notification to errbit
Question: I am using Python's <https://github.com/pulseenergy/airbrakepy> Which is a
synonym to Ruby's Airbrake gem. Now, i have installed
<https://github.com/errbit/errbit> at my end. Now, i want to send all error
notices to errbit. I have something similar to,
import logging
import ConfigParser
import os
import time
from airbrakepy.logging.handlers import AirbrakeHandler
def method_three():
raise StandardError('bam, pow')
def method_two():
method_three()
def method_one():
method_two()
if __name__=='__main__':
configFilePath = os.path.join(os.path.expanduser("~"), ".airbrakepy")
print(configFilePath)
parser = ConfigParser.SafeConfigParser()
parser.read(configFilePath)
api_key = parser.get("airbrake", "api_key")
url = parser.get("airbrake", "app_url")
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger("test-logger")
handler = AirbrakeHandler(api_key, environment='dev', component_name='integration-test', node_name='server', airbrake_url=url, use_ssl=False, timeout_in_ms=10000000)
logger.addHandler(handler)
logger.error("before exception")
try:
method_one()
except StandardError:
logger.error("test with exception", exc_info=True)
logger.error("test without exception", exc_info=False)
logger.error("after exception")
logging.shutdown()
I also have .airbrakepy which has api_key and errbit_url.
Anybody knows where am i making mistake.
I am not able to send notices to errbit through this method.
Answer: Please use <https://github.com/aashish-pathak/airbrakepy>
There is some issue with airbrakepy. I'll soon send pull request to main
airbrakepy repo.
|
Filter strings into list depending on position - Python
Question: For example, this is my string:
myString = "<html><body><p>Hello World!</p><p>Hello Dennis!</p></body></html>"
and what i am trying to achieve is:
myList = ['Hello World!','Hello Dennis!']
Using regular expressions or another method, how can i filter out paragraph
text out of `myString` while ignoring the html tags to achieve `myList`?
I have tried:
import re
a="<body><p>Hello world!</p><p>Hello Denniss!</p></body>"
result=re.search('<p>(.*)</p>', a)
print result.group(1)
Which resulted in: `Hello world!</p><p>Hello Denniss!` and when i tried
`(.*)(.*)` i got `Hello World!`
This string is just an example. The string may also be
`<garbage>abcdefghijk<gar<bage>` depending on how the web developer coded the
website.
It may be a complex regex, but i need to learn this as it is for a cyber
security competition i will be participating in later this year and i think my
best bet is to develop an algorithm which searches for text between a `>` and
a `<`.
How would i go about this?
Sorry if my question is not formatted properly, i have a bit of learning
problems.
Answer: Do you want to get rid of all tags in a `html` text? I won't choose regular
expression, better _the other method_ , for example with `BeautifulSoup` and
you will surprise all in that hacking meeting:
from bs4 import BeautifulSoup
myString = "<html><body><p>Hello World!</p><p>Hello Dennis!</p></body></html>"
myList = list(BeautifulSoup(myString).strings))
It yields:
['Hello World!', 'Hello Dennis!']
|
triangulation without long triangles
Question: In python, for a set of points, With
import matplotlib.tri as tri
triang = tri.Triangulation(x, y)
How I can make a mask for eliminate the triangles with long edges ?
Answer: finally I solved with this :
import matplotlib.tri as tri
def long_edges(x, y, triangles, radio=22):
out = []
for points in triangles:
#print points
a,b,c = points
d0 = np.sqrt( (x[a] - x[b]) **2 + (y[a] - y[b])**2 )
d1 = np.sqrt( (x[b] - x[c]) **2 + (y[b] - y[c])**2 )
d2 = np.sqrt( (x[c] - x[a]) **2 + (y[c] - y[a])**2 )
max_edge = max([d0, d1, d2])
#print points, max_edge
if max_edge > radio:
out.append(True)
else:
out.append(False)
return out
triang = tri.Triangulation(x, y)
mask = long_edges(x,y, triang.triangles)
triang.set_mask(mask)
plt.triplot(triang)
|
Stuck colored filled area in bar chart, python
Question: everyone,
I want to create a bar chart but with a filled background.
For example: for 0 to 1 in y axis the background must be black for >1 to <2 in
y axis the background must be red.
In other words, i want to create bar plot with background different colored
categories in yy axis
(i sorry, my rep points dont allow me to upload a pic) Ty
**It might be closed but i think someone will find this useful: Horizontal
Colored Areas**
import matplotlib.pylab as plt
plt.axhspan(0, 1, facecolor='0.5', alpha=0.5,color ='b',linewidth = True,label ="Category 1")
plt.axhspan(0, -0.8, facecolor='0.5', alpha=0.5,color ='yellow',linewidth = True,label ="Category 2")
plt.axhspan(-0.8, -1.3, facecolor='0.5', alpha=0.5,color ='orange',linewidth = True,label ="Category 3")
plt.axhspan(-1.3, -1.6, facecolor='0.5', alpha=0.5,color = 'orangered',linewidth = True,label ="Category 4")
plt.axhspan(-1.6, -2, facecolor='0.5', alpha=0.5,color ='red',linewidth = True,label ="Category 5")
plt.axhspan(-2, -3, facecolor='0.5', alpha=0.5,color ='maroon',linewidth = True,label ="Category 6")
plt.xlabel("Categories")
plt.ylabel("Units")
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
fancybox=False, shadow=False, ncol=8)
plt.show()
Answer: Like this?
fig, ax = plt.subplots(1, 1)
ax.bar([0, 1, 2], [1, 2, 3], color='b', align='center')
ax.axvspan(0, 1, color='k', alpha=.75, zorder=-1)
ax.axvspan(1, 2, color='r', alpha=.75, zorder=-1)
ax.set_ylim([0, 5])
ax.set_xlabel('fake x')
ax.set_ylabel('fake y')

|
How do I put lines into a list from CSV using python
Question: I am new to Python (coming from PHP background) and I have a hard time
figuring out how do I put each line of CSV into a list. I wrote this:
import csv
data=[]
reader = csv.reader(open("file.csv", "r"), delimiter=',')
for line in reader:
if "DEFAULT" not in line:
data+=line
print(data)
But when I print out data, I see that it's treated as one string. I want a
list. I want to be able to loop and append every line that does not have
"DEFAULT" in a given line. Then write to a new file.
Answer: How about this?
import csv
reader = csv.reader(open("file.csv", "r"), delimiter=',')
print([line for line in reader if 'DEFAULT' not in line])
or if it's easier to understand:
import csv
reader = csv.reader(open("file.csv", "r"), delimiter=',')
data = [line for line in reader if 'DEFAULT' not in line]
print(data)
and of course the _ultimate_ one-liner:
import csv
print([l for l in csv.reader(open("file.csv"), delimiter=',') if 'DEFAULT' not in l])
|
matplotlib + wxpython not sizing correctly with legend
Question: I have a matplotlib figure embedded in a wxpython frame with a few sizers.
Everything works fine until I include a legend but then the sizers don't seem
to be working with the legend.
Even when I resize the window by dragging at the corner, the main figure
changes size, but only the edge of the legend is ever shown.

That is, note that the legend is not visible in the wxFrame.
import wx
import matplotlib as mpl
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas
from random import shuffle
class PlotFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, title="Plot", size=(-1, -1))
self.main_panel = wx.Panel(self, -1)
self.plot_panel = PlotPanel(self.main_panel)
s0 = wx.BoxSizer(wx.VERTICAL)
s0.Add(self.main_panel, 1, wx.EXPAND)
self.SetSizer(s0)
self.s0 = s0
self.main_sizer = wx.BoxSizer(wx.VERTICAL)
self.main_sizer.Add(self.plot_panel, 1, wx.EXPAND)
self.main_panel.SetSizer(self.main_sizer)
class PlotPanel(wx.Panel):
def __init__(self, parent, id = -1, dpi = None, **kwargs):
wx.Panel.__init__(self, parent, id=id, **kwargs)
self.figure = mpl.figure.Figure(dpi=dpi, figsize=(2,2))
self.canvas = Canvas(self, -1, self.figure)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas,1,wx.EXPAND)
self.SetSizer(sizer)
sizer.SetMinSize((600, 500))
self.sizer = sizer
def test(plot_panel):
axes = plot_panel.figure.gca()
for c in ['r', 'b', 'k']:
vals = [20, 30, 40, 50, 80, 20, 50, 60, 70, 70, 80]
shuffle(vals)
axes.plot(range(len(vals)), vals, "-o", color=c, label=c*10)
legend = axes.legend(loc='center left', bbox_to_anchor=(1.05, 0.5))
return legend
if __name__=="__main__":
app = wx.PySimpleApp()
frame = PlotFrame()
legend = test(frame.plot_panel)
frame.Fit()
print "legend frame pre show: ", legend.get_frame()
frame.Show(True)
print "legend frame post show:", legend.get_frame()
frame.Fit()
app.MainLoop()
**Edit:**
For a solution to be useful to me, I would like it to look good when the
figure is automatically drawn by the program, so adjustment parameters can be
hard coded in the program, or, for example, on a window resize event, but not
adjusted by hand for each plot. The main things that I expect to change here
are: **1)** the lengths of the labels (from, say, 1 to 25 characters), **2)**
the windows size (usually by the user dragging around the corner, and **3)**
the number of points and lines. (Also, if it matters, eventually, I'll want to
have dates on the bottom axis.)
I've put the legend outside of the axes so that it won't cover any data
points, and I'd prefer that it stay to the right of the axes.
I'm using Python 2.6.6, wxPython 2.8.12.1, and matplotlib 1.1.0 and am stuck
with these for now.
Answer: It is re-sizing correctly, you just didn't tell it to do what you want it to
do.
The problem is this line:
axes.legend(loc='center left', bbox_to_anchor=(1.05, 0.5))
Pretty sure the `bbox_to_anchor` kwarg is over-ridding the `loc` kwarg and you
are pegging the bottom left of the legend to (1.05, 0.5) in axes units. If the
axes expands to fill your window, the left edge of the legend will always be
5% of the width axes to the right of the right edge of you axes, hence always
out of view.
You either need to put your legend someplace else or shrink your axes (in
figure fraction).
## option 1 move the legend:
axes.legend(bbox_to_anchor=(0.5, 0.5)) #find a better place this is in the center
## option 2 move the axes + resize the figure:
axes.set_position([.1, .1, .5, .8]) # units are in figure fraction
[`set_position`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_position)
fig = figure()
axes = fig.add_subplot(111)
for c in ['r', 'b', 'k']:
vals = [20, 30, 40, 50, 80, 20, 50, 60, 70, 70, 80]
shuffle(vals)
axes.plot(range(len(vals)), vals, "-o", color=c, label=c*10)
legend = axes.legend(loc='center left', bbox_to_anchor=(1.05, 0.5))

# adjust the figure size (in inches)
fig.set_size_inches(fig.get_size_inches() * np.array([1.5, 1]), forward=True)
# and the axes size (in figure fraction)
# to (more-or-less) preserve the aspect ratio of the original axes
# and show the legend
pos = np.array(axes.get_position().bounds)
pos[2] = .66
axes.set_position(pos)

## option 3: automate option 2
fig = figure() # use plt to set this up for demo purposes
axes = fig.add_subplot(111) # add a subplot
# control paramters
left_pad = .05
right_pad = .05
# plot data
for c in ['r', 'b', 'k']:
vals = [20, 30, 40, 50, 80, 20, 50, 60, 70, 70, 80]
shuffle(vals)
axes.plot(range(len(vals)), vals, "-o", color=c, label=c*10)
# set axes labels
axes.set_xlabel('test x')
axes.set_ylabel('test y')
# make the legend
legend = axes.legend(loc='center left', bbox_to_anchor=(1 + left_pad, 0.5))
# function to 'squeeze' the legend into place
def squeeze_legend(event):
fig.tight_layout()
right_frac = 1 - legend.get_window_extent().width / fig.get_window_extent().width - left_pad - right_pad
fig.subplots_adjust(right=right_frac)
fig.canvas.draw()
# call it so the first draw is right
squeeze_legend()
# use the resize event call-back to make sure it works even if the window is re-sized
fig.canvas.mpl_connect('resize_event', squeeze_legend)
|
How to use named colors in wxpython?
Question: I get named colours in `wx` this way:
import wx.lib.colourdb as wb
wb.getColourList()
Although "ORANGE" is in `wx.lib.colourdb`, i cannot set a grid cell's color to
`wx.ORANGE` because it says:
AttributeError: 'module' object has no attribute 'ORANGE'
How do I use the colors defined in `wx.lib.colourdb.getColourList()` ?
Answer:
color = wx.NamedColour("orange")
some_window.SetForegroundColour("orange")
(make sure you start your app first)
in order to load some of the colours into `wx.TheColourDatabase` you will need
to run
wx.lib.colourdb.updateColourDB() #adds ALOT more named colours to wx.TheColourDatabase
c1 = wx.NamedColour("light coral")
c2 = wx.NamedColour("peachpuff2")
|
Right-to-left Support in Python Networkx and matplotlib
Question: I have tried to draw lexicographic graphs with python33 networkx and
matplotlib running on Linux Fedora 19 KDE, 64 bits. When feeding English
script as input data, the graphs are drawn well. However, when providing
Arabic script as input data, all I get is squares queued in juxtaposition.
This is an example of a simple graph in English script:

and here is a simple graph of Arabic words written in Arabic script, (which is
written from Right-to-left).

The question is: how can I show Arabic script in the graphs that I generate
using python networkx and matplotlib.pyplot? I really appreciate your kind
help!
Edit: after Chronial suggested selecting the the proper font, I executed these
commands in the python33 shell:
>>> import matplotlib.pyplot
>>> matplotlib.rcParams.update({font.family' : 'TraditionalArabic'})
Then I constructed the graph with Arabic words. However, drawing the graph did
not show Arabic script. It showed jsut squares. I do not know whether the
matplotlib.pyplot uses the system fonts or it has its own font packages.
Assuming that the matplotlib.pyplot uses the system font, then it should have
shown Arabic scripts. It seems that Arabic fonts needs to be installed to the
matplotlib.pyplot. But I don't know how to do that. Your help is highly
appreciated!
Edit # 3: After installing Arabic fonts into the system, I could generate
graphs with Arabic script but the script appears from left-to-right. A good
progress towards the final stage: which is Arabic script appearing from Right
to left. Below is a shot of the graph:

Yours,
Mohammed
Answer: For **Arabic** in matplotlib you need `bidi.algorithm.get_display` and
[`arabic_reshaper`](https://github.com/mpcabd/python-arabic-reshaper) modules:
from bidi.algorithm import get_display
import matplotlib.pyplot as plt
import arabic_reshaper
import networkx as nx
# Arabic text preprocessing
reshaped_text = arabic_reshaper.reshape(u'لغةٌ عربيّة')
artext = get_display(reshaped_text)
# constructing the sample graph
G=nx.Graph()
G.add_edge('a', artext ,weight=0.6)
pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos,node_size=700)
nx.draw_networkx_edges(G,pos,edgelist=G.edges(data=True),width=6)
# Drawing Arabic text
# Just Make sure your version of the font 'Times New Roman' has Arabic in it.
# You can use any Arabic font here.
nx.draw_networkx_labels(G,pos,font_size=20,font_family='Times New Roman')
# showing the graph
plt.axis('off')
plt.show()

|
Pycurl won't import on Raspberry Pi
Question: I'm trying to use pycurl on the Raspberry Pi. I've successfully installed
pycurl using `apt-get install python-pycurl` and I've found a little script to
use to see if it's working correctly:
import pycurl
c = pycurl.Curl()
c.setopt(c.URL, 'http://news.ycombinator.com')
c.perform()
When I run this script using `sudo ./pycurltest.py` I get an error:
./pycurltest.py: 1: ./pycurltest.py: import: not found
./pycurltest.py: 2: ./pycurltest.py: Syntax error: "(" unexpected
However, if use the python interpreter and use `help(modules)` I can see that
pycurl is installed. When I try to run the same script in the interpreter it
works and I get:
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>
What am I missing here?
Answer: The first line is misleading.
./pycurltest.py: 1: ./pycurltest.py: import: not found
It looks like the interpreter is suggesting that a blank import cannot be
found, or it's finding:
import Pycurses#<---something else is here
Check that your .py script does not have any weird characters at the end of
the line and that it has a proper newline character:
import pycurl
From the python
[docs](http://docs.python.org/2/reference/lexical_analysis.html%20docs):
> A physical line is a sequence of characters terminated by an end-of-line
> sequence. In source files, any of the standard platform line termination
> sequences can be used - the Unix form using ASCII LF (linefeed), the Windows
> form using the ASCII sequence CR LF (return followed by linefeed), or the
> old Macintosh form using the ASCII CR (return) character. All of these forms
> can be used equally, regardless of platform. When embedding Python, source
> code strings should be passed to Python APIs using the standard C
> conventions for newline characters (the \n character, representing ASCII LF,
> is the line terminator).
|
Converting a csv file into a list of tuples with python
Question: I am to take a csv with 4 columns: brand, price, weight, and type.
The types are orange, apple, pear, plum.
Parameters: I need to select the most possible weight, but by selecting 1
orange, 2 pears, 3 apples, and 1 plum by not exceeding as $20 budget. I cannot
repeat brands of the same fruit (like selecting the same brand of apple 3
times, etc).
I can open and read the csv file through Python, but I'm not sure how to
create a dictionary or list of tuples from the csv file?
For more clarity, here's an idea of the data.
Brand, Price, Weight, Type
brand1, 6.05, 3.2, orange
brand2, 8.05, 5.2, orange
brand3, 6.54, 4.2, orange
brand1, 6.05, 3.2, pear
brand2, 7.05, 3.6, pear
brand3, 7.45, 3.9, pear
brand1, 5.45, 2.7, apple
brand2, 6.05, 3.2, apple
brand3, 6.43, 3.5, apple
brand4, 7.05, 3.9, apple
brand1, 8.05, 4.2, plum
brand2, 3.05, 2.2, plum
Here's all I have right now:
import csv
test_file = 'testallpos.csv'
csv_file = csv.DictReader(open(test_file, 'rb'), ["brand"], ["price"], ["weight"], ["type"])
Answer: You can ponder this:
import csv
def fitem(item):
item=item.strip()
try:
item=float(item)
except ValueError:
pass
return item
with open('/tmp/test.csv', 'r') as csvin:
reader=csv.DictReader(csvin)
data={k.strip():[fitem(v)] for k,v in reader.next().items()}
for line in reader:
for k,v in line.items():
k=k.strip()
data[k].append(fitem(v))
print data
Prints:
{'Price': [6.05, 8.05, 6.54, 6.05, 7.05, 7.45, 5.45, 6.05, 6.43, 7.05, 8.05, 3.05],
'Type': ['orange', 'orange', 'orange', 'pear', 'pear', 'pear', 'apple', 'apple', 'apple', 'apple', 'plum', 'plum'],
'Brand': ['brand1', 'brand2', 'brand3', 'brand1', 'brand2', 'brand3', 'brand1', 'brand2', 'brand3', 'brand4', 'brand1', 'brand2'],
'Weight': [3.2, 5.2, 4.2, 3.2, 3.6, 3.9, 2.7, 3.2, 3.5, 3.9, 4.2, 2.2]}
If you want the csv file literally as tuples by rows:
import csv
with open('/tmp/test.csv') as f:
data=[tuple(line) for line in csv.reader(f)]
print data
# [('Brand', ' Price', ' Weight', ' Type'), ('brand1', ' 6.05', ' 3.2', ' orange'), ('brand2', ' 8.05', ' 5.2', ' orange'), ('brand3', ' 6.54', ' 4.2', ' orange'), ('brand1', ' 6.05', ' 3.2', ' pear'), ('brand2', ' 7.05', ' 3.6', ' pear'), ('brand3', ' 7.45', ' 3.9', ' pear'), ('brand1', ' 5.45', ' 2.7', ' apple'), ('brand2', ' 6.05', ' 3.2', ' apple'), ('brand3', ' 6.43', ' 3.5', ' apple'), ('brand4', ' 7.05', ' 3.9', ' apple'), ('brand1', ' 8.05', ' 4.2', ' plum'), ('brand2', ' 3.05', ' 2.2', ' plum')]
|
Data from a Python script to URL as JSON
Question: I've spent a lot of time on this but still can't seem to get it to work. The
task is - I have to send system stats to a URL and the script is supposed to
pull it, convert the namedtuple of each cpu stats of a machine and then send
them all in 1 single POST request as JSON. The connection must close once the
data has been sent.
For the '1 single POST request' functionality, I added the latter function
(senddata_to_server) in the script. Without it (with the connection details
simply listed there without a function) , when I ran it on Mac/Windows/Linux,
it used to return all the namedtuples 1 by 1 and then a '200 OK' and then go
on printing 'Connection refused' forever. Now when I run it, it just hangs
there without returning anything.
(I have asked this question earlier ( [HTTP Post request with Python
JSON](http://stackoverflow.com/questions/18754405/http-post-request-with-
python-json) ) but I need to have the 'params' inside the loop and the
connection details outside it.
import psutil
import socket
import time
import sample
import json
import httplib
import urllib
serverHost = sample.host
port = sample.port
thisClient = socket.gethostname()
currentTime = int(time.time())
s = socket.socket()
s.connect((serverHost, port))
cpuStats = psutil.cpu_times_percent(percpu=True)
def loop_thru_cpus():
while True:
global cpuStats
cpuStats = "/n".join([json.dumps(stats._asdict()) for stats in cpuStats])
try:
command = 'put cpu.usr ' + str(currentTime) + " " + str(cpuStats[0]) + "host ="+thisClient+ "/n"
s.sendall(command)
command = 'put cpu.nice ' + str(currentTime) + " " + str(cpuStats[1]) + "host ="+ thisClient+ "/n"
s.sendall(command)
command = 'put cpu.sys ' + str(currentTime) + " " + str(cpuStats[2]) + "host ="+ thisClient+ "/n"
s.sendall(command)
command = 'put cpu.idle ' + str(currentTime) + " " + str(cpuStats[3]) + "host ="+ thisClient+ "/n"
s.sendall(command)
params = urllib.urlencode({'cpuStats': cpuStats, 'deviceKey': 1234, 'timeStamp': str(currentTime)})
return params
print cpuStats
except IndexError:
continue
except socket.error:
print "Connection refused"
continue
finally:
s.close()
def senddata_to_server():
x = loop_thru_cpus()
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
conn = httplib.HTTPConnection(serverHost, port)
conn.request = ("POST", "", x.params, headers)
response = conn.response()
print response.status, response. reason
print x.cpuStats
conn.close()
loop_thru_cpus()
senddata_to_server()
Answer: > > Given the task and the code/logic here, what am I doing wrong?
I can't quite tell what your task is, but here are some things you may be
doing wrong:
* You are connecting to the server directly (via `socket.connect()`) and through the framework (via `HTTPlib.connect()`)
* You misspelled newline: it should be `'\n'`, not `'/n'`
* You have a while loop that can only execute once (because you `return` in the middle of it).
* You have a print statement after your return statement
* You are sending malformed `put` commands to the web server
* You call `loop_thru_cpus()` twice
* You set the content-type incorrectly to `application/json` \-- you aren't sending well-formed json.
* You aren't sending a url to `HTTPlib.HTTPConnection.request()` (may be allowed in practice, disallowed in the documentation)
* You aren't invoking `conn.request()` correctly -- get rid of `=`
* In [the documentation](http://docs.python.org/2/library/httplib.html) it says to call `conn.getresponse()`, not `conn.response()`
Here is a program that hopefully does what you ask for:
import psutil
import socket
import time
import json
import httplib
import urllib
# httpbin provides an echo service at http://httpbin.org/post
serverHost = 'httpbin.org'
port = 80
url = 'http://httpbin.org/post'
# My psutil only has cpu_times, not cpu_times_percent
cpuStats = psutil.cpu_times(percpu=True)
# Convert each namedTuple to a json string
cpuStats = [json.dumps(stats._asdict()) for stats in cpuStats]
# Convert each json string to the form required by the assignment
cpuStats = [urllib.urlencode({'cpuStats':stats, 'deviceKey':1234}) for stats in cpuStats]
# Join stats together, one per line
cpuStats = '\n'.join(cpuStats)
# Send the data ...
# connect
conn = httplib.HTTPConnection(serverHost, port)
# Send the data
conn.request("POST", url, cpuStats)
# Check the response, should be 200
response = conn.getresponse()
print response.status, response.reason
# httpbin.org provides an echo service -- what did we send?
print response.read()
conn.close()
|
How to access Mac-specific file metadata?
Question: According to this page, different operating systems can return different
information from the os.stat function.
<http://docs.python.org/2/library/os.html>
I am interested in getting the type and creator.
import os
from stat import *
print(os.stat('filename').st_ino)
print(os.stat('filename').st_creator)
This code works for the inode (st_ino) but gives an error for the creator:
> AttributeError: 'posix.stat_result' object has no attribute 'st_creator'
Same for st_type and st_rsize.
Do I have to do anything special to get these to work?
(This is Mac OS X 10.5 and 10.8 with Python 2. I'm new to Python.)
Answer: "Mac OS" in the docs here means Mac OS Classic, i.e., before the X. For OSX,
the unix and FreeBSD comments are relevant.
|
Python. I get an error on Multiple inheritance
Question: All I am trying to do is inherit from two different classes.
from traits.api import HasTraits
from PyQt4 import QtCore, QtGui, uic
class Main_Excel_Class(HasTraits,QtGui.QMainWindow):
pass
I had the "metaclass conflict: the metaclass of a derived class must be a
(non-strict) subclass of the metaclasses of all its bases"
error initially. But I resolved it by putting in a **___metaclass_ __**
attribute:
from traits.api import HasTraits
from PyQt4 import QtCore, QtGui, uic
class Main_Excel_Class_Meta(type(HasTraits), type(QtGui.QMainWindow)):
pass
class Main_Excel_Class(HasTraits,QtGui.QMainWindow):
__metaclass__ = Main_Excel_Class_Meta
But now I end up getting the
"TypeError: Error when calling the metaclass bases
multiple bases have instance lay-out conflict"
error. I tried looking into other similar questions but i honestly did not
understand much.Any insights as to how to approach to solve this problem would
be very much appreciated. Thankyou
Answer: I finally resolved it with a little research. Apparently the error had to do
something with the **___slots_ __** attribute's conflicts which is used when
allocating heap memory for the new type.Here are the changes I made :
from traits.api import HasTraits
from PyQt4 import QtCore, QtGui, uic
class Main_Excel_Class_Meta(type(HasTraits), type(QtGui.QMainWindow)):
pass
class HasTraits(QtGui.QMainWindow):
pass
class Main_Excel_Class(HasTraits):
__metaclass__ = Main_Excel_Class_Meta
For a better understanding of the working I had suggest you check this post
<http://mcjeff.blogspot.in/2009/05/odd-python-errors.html>
|
Passing a C++ std::Vector to numpy array in Python
Question: I am trying a pass a vector of doubles that I generate in my `C++` code to a
`python` numpy array. I am looking to do some downstream processing in
`Python` and want to use some python facilities, once I populate the numpy
array. One of the biggest things I want to do is to be able to plot things,
and C++ is a bit clumsy when it comes to that. Also I want to be able to
leverage Python's statistical power.
Though I am not very clear as to how to do it. I spent a lot of time going
through the Python C API documentation. I came across a function
PyArray_SimpleNewFromData that apparently can do the trick. I still am very
unclear as far as the overall set up of the code is concerned. I am building
certain very simple test cases to help me understand this process. I generated
the following code as a standlone Empty project in Visual Studio express 2012.
I call this file Project1
#include <Python.h>
#include "C:/Python27/Lib/site-packages/numpy/core/include/numpy/arrayobject.h"
PyObject * testCreatArray()
{
float fArray[5] = {0,1,2,3,4};
npy_intp m = 5;
PyObject * c = PyArray_SimpleNewFromData(1,&m,PyArray_FLOAT,fArray);
return c;
}
My goal is to be able to read the PyObject in Python. I am stuck because I
don't know how to reference this module in Python. In particular how do I
import this Project from Python, I tried to do a import Project1, from the
project path in python, but failed. Once I understand this base case, my goal
is to figure out a way to pass the vector container that I compute in my main
function to Python. I am not sure how to do that either.
Any experts who can help me with this, or maybe post a simple well contained
example of some code that reads in and populates a numpy array from a simple
c++ vector, I will be grateful. Many thanks in advance.
Answer: I came across your post when trying to do something very similar. I was able
to cobble together a solution, the entirety of which is [on my
Github](https://github.com/Frogee/PythonCAPI_testing). It makes two C++
vectors, converts them to Python tuples, passes them to Python, converts them
to NumPy arrays, then plots them using Matplotlib.
Much of this code is from the Python Documentation.
Here are some of the important bits from the .cpp file :
//Make some vectors containing the data
static const double xarr[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14};
std::vector<double> xvec (xarr, xarr + sizeof(xarr) / sizeof(xarr[0]) );
static const double yarr[] = {0,0,1,1,0,0,2,2,0,0,1,1,0,0};
std::vector<double> yvec (yarr, yarr + sizeof(yarr) / sizeof(yarr[0]) );
//Transfer the C++ vector to a python tuple
pXVec = PyTuple_New(xvec.size());
for (i = 0; i < xvec.size(); ++i) {
pValue = PyFloat_FromDouble(xvec[i]);
if (!pValue) {
Py_DECREF(pXVec);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert array value\n");
return 1;
}
PyTuple_SetItem(pXVec, i, pValue);
}
//Transfer the other C++ vector to a python tuple
pYVec = PyTuple_New(yvec.size());
for (i = 0; i < yvec.size(); ++i) {
pValue = PyFloat_FromDouble(yvec[i]);
if (!pValue) {
Py_DECREF(pYVec);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert array value\n");
return 1;
}
PyTuple_SetItem(pYVec, i, pValue); //
}
//Set the argument tuple to contain the two input tuples
PyTuple_SetItem(pArgTuple, 0, pXVec);
PyTuple_SetItem(pArgTuple, 1, pYVec);
//Call the python function
pValue = PyObject_CallObject(pFunc, pArgTuple);
And the Python code:
def plotStdVectors(x, y):
import numpy as np
import matplotlib.pyplot as plt
print "Printing from Python in plotStdVectors()"
print x
print y
x = np.fromiter(x, dtype = np.float)
y = np.fromiter(y, dtype = np.float)
print x
print y
plt.plot(x, y)
plt.show()
return 0
Which results in the plot that I can't post here due to my reputation, but is
[posted on my blog post
here](http://codextechnicanum.blogspot.com/2013/12/embedding-python-in-c-
converting-c.html).
|
learnpython.org modules exercise
Question: # Hello community,
**[ Preamble ] :**
I come from a BASH scripting background _(still learning there as well)_ and
decided it might benefit my learning process by venturing into another
language. The natural choice for me seemed to be Python. I began studying a
bit and have been going through the exercises found on www.learnpython.org.
Particularly, [Modules and
Packages](http://www.learnpython.org/Modules%20and%20Packages).
**[ Problem ] :**
`Import` the module **re** and `print` out alphabetically **sorted** , all
functions in the module that contain the word `find`.
**[ Tried ] :**
# import the module.
import re
# store output of dir(re) in reLST as string list.
''' I believe that's what happens, correct? '''
reLST = dir(re)
# iterate over reLST and assign m strings matching word containing find.
for element in reLST:
m = re.match("(find\w+)", element)
# Here it prints out the matches, but only using the function .groups()
''' Won't work using print sorted(m) ---why? '''
# Found tutorial online, but no real understanding of .groups() function use.
if m:
print sorted(m.groups())
**[ Expected Output ] :**
['findall', 'finditer']
**[ My Output ] :**
['findall']
['finditer']
**[ Question ] :**
Technically, the code works and does output all _strings_ grabbed from
`dir(re)`, but on a new line. I'm guessing this is done as part of the
`.groups()` function? What would be a good way of getting the desired output
in the correct format?
Answer: You should collect the results in a list, and then sort them:
import re
results = []
for element in dir(re):
m = re.match("(find\w+)", element)
if m:
results.append(m.group(1))
print sorted(results)
Also, instead of `re`, you can use `startswith()`:
import re
results = []
for element in dir(re):
if element.startswith('find'):
results.append(element)
print sorted(results)
or, the same thing in one line using `list comprehension`:
import re
print sorted([element for element in dir(re) if element.startswith('find')])
If the word `find` can be anywhere in the string, you should use `in` instead
of `startswith()`:
import re
print sorted([element for element in dir(re) if 'find' in element])
|
Regex match when spaces are removed, how to delete the matched chars from the original string with spaces?
Question: (disclaimer: this is my first stackoverflow question so forgive me in advance
if I'm not too clear)
**Expected results:**
My task is to find company legal identifiers in a string representing a
company name, then separate them from it and save them in a separate string.
The company names have already been cleaned so that they only contain
alphanumeric lowercase characters.
Example:
company_1 = 'uber wien abcd gmbh'
company_2 = 'uber wien abcd g m b h'
company_3 = 'uber wien abcd ges mbh'
should result in
company_1_name = 'uber wien abcd'
company_1_legal = 'gmbh'
company_2_name = 'uber wien abcd'
company_2_legal = 'gmbh'
company_3_name = 'uber wien abcd'
company_3_legal = 'gesmbh'
**Where I am right now:**
I load the list of all company ids up from a csv file. Austria provides a good
example. Two legal ids are:
gmbh
gesmbh
I use a regex expression that tells me **IF** the company name contains the
legal identifier. However, this regex removes _all_ spaces from the string in
order to identify the legal id.
company_1_nospace = 'uberwienabcdgmbh'
company_2_nospace = 'uberwienabcdgmbh'
company_3_nospace = 'uberwienabcdgesmbh'
since I look for the regex in the string without spaces, I am able to see that
all three companies have legal ids inside their name.
**Where I am stuck:**
I can say whether there is a legal id in `company_1`, `company_2`, and
`company_3` but I can only remove it from `company_1`. In fact, I cannot
remove `g m b h` because it does not match, but I can say that it is a legal
id. The only way I could remove it is to also remove spaces in the rest of the
company name, which I dont want to do (it would only be a last resort option)
Even if I were to insert spaces into `gmbh` to match it with `g m b h`, I
would then not pick up `ges mbh` or `ges m b h`. (Note that the same thing
happens for other countries)
**My code:**
import re
re_code = re.compile('^gmbh|gmbh$|^gesmbh|gesmbh$')
comp_id_re = re_code.search(re.sub('\s+', '', company_name))
if comp_id_re:
company_id = comp_id_re.group()
company_name = re.sub(re_code, '', company_name).strip()
else:
company_id = ''
Is there a way for python to _understand_ which characters to remove from the
original string? Or would it just be easier if somehow (that's another
problem) I find all possible alternatives for legal id spacing? ie from `gmbh`
I create `g mbh`, `gm bh`, `gmb h`, `g m bh`, etc... and use that for
matching/extraction?
I hope I have been clear enough with my explanation. Thinking about a title
for this was rather difficult.
**UPDATE 1:** company ids are usually at the end of the company name string.
They can occasionally be at the beginning in some countries.
**UPDATE 2:** I think this takes care of the company ids inside the company
name. It works for legal ids at the end of the company name, but it does not
work for company ids at the beginning
legal_regex = '^ltd|ltd$|^gmbh|gmbh$|^gesmbh|gesmbh$'
def foo(name, legal_regex):
#compile regex that matches company ids at beginning/end of string
re_code = re.compile(legal_regex)
#remove spaces
name_stream = name.replace(' ','')
#find regex matches for legal ids
comp_id_re = re_code.search(name_stream)
#save company_id, remove it from string
if comp_id_re:
company_id = comp_id_re.group()
name_stream = re.sub(re_code, '', name_stream).strip()
else:
company_id = ''
#restore spaced string (only works if id is at the end)
name_stream_it = iter(name_stream)
company_name = ''.join(next(name_stream_it) if e != ' ' else ' ' for e in name)
return (company_name, company_id)
Answer: Non-Regex solution would be easier here, and this is how, I would do it
legal_ids = """gmbh
gesmbh"""
def foo(name, legal_ids):
#Remove all spaces from the string
name_stream = name.replace(' ','')
#Now iterate through the legal_ids
for id in legal_ids:
#Remove the legal ID's from the string
name_stream = name_stream.replace(id, '')
#Now Create an iterator of the modified string
name_stream_it = iter(name_stream)
#Fill in the missing/removed spaces
return ''.join(next(name_stream_it) if e != ' ' else ' ' for e in name)
foo(company_1, legal_ids.splitlines())
'uber wien abcd '
foo(company_2, legal_ids.splitlines())
'uber wien abcd '
foo(company_3, legal_ids.splitlines())
'uber wien abcd '
|
Parsing two different html sources and combining the output
Question: I am parsing two different html sources (one spits out "data A,B,C,D, and E"
and the other spits out "data F") with two different scripts. I want to
combine the output of both of these scripts into a simple csv format.
I am trying to run a 3rd script that imports everything from the other two
scripts and prints out the data. This is what I am doing to try and make this
happen:
#!usr/bin/env python
from script1 import *
from script2 import *
for c in cities :
c.retrieveTemps()
print(c.name,c.high0,c.low0,c.high1,c.low1,c.weather0,c.weather1,c.wind0,c.wind1)
All the variables are defined in script1 and script2. Script1 finds every
variable except for c.wind1. However, when I run the above code, it will only
find the data for either script1 OR script2 (depending on which one I import
second), not both.
Any ideas on what I can do to get it to print out all the data from both
script1 and script2? Thanks!
**EDIT**
This is from script1:
#!usr/bin/env python
import re
import urllib
from datetime import datetime
from datetime import timedelta
date = datetime.now()
date1 = date + timedelta(days=1)
date2 = date + timedelta(days=2)
class city :
def __init__(self, city_name, link) :
self.name = city_name
self.url = link
self.wind1 = 0
def retrieveTemps(self) :
filehandle = urllib.urlopen(self.url)
# get lines from result into array
lines = filehandle.readlines()
# (for each) loop through each line in lines
line_number = 0 # a counter for line number
for line in lines:
line_number = line_number + 1 # increment counter
# find string, position otherwise position is -1
position2 = line.rfind('<ul class="stats">')
#String is found in line
if position2 > 0 :
self.wind0 = lines[line_number + 1].split('</strong>')[0].split('style="">')[-1]
break # done with loop, break out of it
return ('c.wind0')
filehandle.close()
m1 = city('Mexico City', 'http://www.accuweather.com/en/mx/mexico-city/242560/daily-weather-forecast/242560?day=2')
m3 = city('Veracruz', 'http://www.accuweather.com/en/mx/veracruz/236233/daily-weather-forecast/236233?day=2')
m5 = city('Tampico', 'http://www.accuweather.com/en/mx/tampico/235985/daily-weather-forecast/235985?day=2')
m7 = city('Nuevo Laredo', 'http://www.accuweather.com/en/mx/nuevo-laredo/235983/daily-weather-forecast/235983?day=2')
m9 = city('Monterrey', 'http://www.accuweather.com/en/mx/monterrey/244681/daily-weather-forecast/244681?day=2')
m11 = city('S. Luis Potosi', 'http://www.accuweather.com/en/mx/san-luis-potosi/245369/daily-weather-forecast/245369?day=2')
m13 = city('Queretaro', 'http://www.accuweather.com/en/mx/queretaro/245027/daily-weather-forecast/245027?day=2')
m15 = city('Laz. Cardenas', 'http://www.accuweather.com/en/mx/lazaro-cardenas/239054/daily-weather-forecast/239054?day=2')
cities = []
cities.append(m1)
cities.append(m3)
cities.append(m5)
cities.append(m7)
cities.append(m9)
cities.append(m11)
cities.append(m13))
cities.append(m15)
Answer: Don't do this. Importing the namespace of a module is the wrong way. The two
Python scripts don't 'spit out' data. Write methods, import them, call them,
use the result.
`script1.py`
def foo():
return (1, 2, 3)
`script2.py`
def bar():
return ('a', 'b', 'c')
`script3.py`
from script1 import foo
from script2 import bar
combinedResult = foo() + bar()
|
Django template's context variables scope?
Question: I'm looking for a solution how to "shadow" context variables in a Django's
template.
Let's have the following structure in one of templates:
{% block content %}
{# set context variables with a custom tag #}
{% paginator_ctx products %} {# sets `paginator' in context dict #}
{% for product in paginator.object_list %}
{# Render elements from _outer_ loop #}
{% paginator_ctx child_products %} {# !! replaces context !! #}
{% for cat in paginator.object_list %}
{# Render elements from _inner_ loop #}
{% endfor %}
{% include "paginator.html" %}
{% endfor %}
{# ?? how to restore the original context ?? #}
{% include "paginator.html" %} {# renders prev, next & current page number #}
{% endblock %}
I hope it's obvious from the example what I'd need to achieve. To have local
scope in a template similar how it does work in Python. Or am I taking it from
a wrong side ? To have generic templates relying on context variables instead
of passing values in arguments ?
Thanks.
**Update:** There is some a bit hackish solution to manually store context
variables:
{# outer block #}
{% with context_var as context_var_saved %}
{# inner/nested block overwriting context_var #}
{% with context_var_saved as context_var %}
{# process restored context_var #}
{% endwith %}
{# end of inner block #}
{% endwith %}
{# end of outer block #}
No cleaner solution available ? What if I'd need to store more variables or
the whole context ?
Answer: Having a similar issue, I decided to create a `global_scope` block in my
`base_site.html` template that wraps everything and to use it exclusively to
assign "multiple blocks" context variables.
It goes like this:
>> base_site.html
{% block global_scope %}
<!DOCTYPE html>
<html>
...
<more blocks here>
</html>
{% endblock global_scope %}
Then in a specialized template:
{% block global_scope %}
{# set context variables with a custom tag #}
{{ block.super }} {# <-- important! #}
{% endblock global_scope %}
{% block content %}
{# the context variable is available here #}
{% endblock %}
With this approach, though, you have to double check that you are not
overriding any variables that someone else set in the template hierarchy.
Furthermore, depending on the size of your variable, maybe there is a memory
overhead, being that the variable won't be popped out of the context until the
very end of the template.
|
Django, problems with overriding model in sites packages
Question: i got problems with overriding of model "Sites", that contains in Sites
framefork. I have a form with "Sites" on my site, i need to display names of
Sites, not Site.domain, i'm override model, route it to same DB table in
"Meta" class and get error, that i cant to understand, code here:
**Model:**
@python_2_unicode_compatible
class Site(models.Model):
domain = models.CharField(_('domain name'), max_length=100)
name = models.CharField(_('display name'), max_length=50)
objects = SiteManager()
class Meta:
db_table = 'django_site'
verbose_name = _('site')
verbose_name_plural = _('sites')
ordering = ('domain',)
def __str__(self):
return self.domain
def save(self, *args, **kwargs):
super(Site, self).save(*args, **kwargs)
# Cached information will likely be incorrect now.
if self.id in SITE_CACHE:
del SITE_CACHE[self.id]
def delete(self):
pk = self.pk
super(Site, self).delete()
try:
del SITE_CACHE[pk]
except KeyError:
pass
**My overrided model:**
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
class NamedSite(Site):
def __str__(self):
return self.name
class Meta:
db_table = 'django_site'
verbose_name = _('site')
verbose_name_plural = _('sites')
ordering = ('domain',)
**and Error**
DatabaseError at <my url>
ERROR: Column django_site.site_ptr_id doesn't exist
LINE 1: ...ROM "django_site" INNER JOIN "django_site" T2 ON ("django_si...
Answer: Subclassing the model is an example of [model
inheritance](https://docs.djangoproject.com/en/dev/topics/db/models/#multi-
table-inheritance). It is not possible to 'override the model and route to the
same db table'.
A better approach would be to subclass
[`ModelChoiceField`](https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield),
and override `label_from_instance` to display a site instance as you wish.
Then use your model choice field to select the site in your form.
|
How to continue he execution of python script after user change
Question: I want to execute following commands in sequence using a python script:
sudo su - postgres #login as postgres user
psql
I tried using :
import os
cmd = 'sudo su - postgres'
os.system(cmd)
cmd1='psql'
os.system(cmd1)
The problem with this is that the 2nd command gets executed only after I log
out from the postgres user, but I want to run it as postgres user. How can I
can I continue the execution of python script after the user change?
Thanks
Answer: You can use:
sudo su - postgres --command='cat … | psql …'
But you shouldn't. You should configure your database server to allow a user
running your python script access to your database without password. Or at
least use `.pg_pass` file in this user home directory to provide username and
password for this database.
If you use PGPASSWORD, as you indicated in a comment, then any other user in
your system can display it simply using `ps auxwww`.
|
Random string value generator from the given list in python
Question:
sports=['CRICKET','BADMINTON','TENNIS']
bollywood=['WAQT','GULAAL','MAQBOOL']
food=['RAVA DOSA','IDLI SAMBHAR','CENTURY EGG']
print """Choose Your Field
1. SPORTS
2. BOLLYWOOD
3. FOOD"""
field=raw_input('\n Enter Field :')
Now the user will enter the field then there should be some function which
will return random value from that given field(list).
Answer:
import random
myList = []
myList.append(['CRICKET','BADMINTON','TENNIS'])
myList.append(['WAQT','GULAAL','MAQBOOL'])
myList.append(['RAVA DOSA','IDLI SAMBHAR','CENTURY EGG'])
print """Choose Your Field
1. SPORTS
2. BOLLYWOOD
3. FOOD"""
field=raw_input('\n Enter Field :')
print random.choice(myList[int(field) - 1])
You should also error check your input to make sure it's actually a valid
entry
|
How to read the first line of a subprocess without buffers filling up in Python
Question: From Python in Linux, I want to start a sub-process, wait until it prints one
line on it's standard out, then continue with the rest of my Python script. If
I do:
from subprocess import *
proc = Popen(my_process, stdout=PIPE)
proc.readline()
# Now continue with the rest of my script
Will my process eventually block if it writes a lot to its stdout, because the
pipe fills up?
Ideally, I'd like the rest of the output to go to the standard output of my
script. Is there a way to change the stdout of the subprocess from PIPE to my
standard output after it starts?
I'm guessing I'll have to spawn a separate thread just to read from my
process's stdout and print to my own, but I'd like to avoid that if there's a
simpler solution.
Answer: Stop the process?
proc.terminate()
After the readline
|
Python Stringvar instance has no __trunc__method
Question: For fun (and to learn...), I'm trying to write a program that takes 3 inputs,
a, b and c, and returns the solution to the quadratic formula. Right now, I'm
getting an error saying StringVar instance has no attribute '**trunc** ' I
initially had my entry variables set up as IntVar and got the same type of
error, with IntVar instance not having the **trunc** attribute.
import Tkinter
from math import *
def quadprogram(a,b,c):
x1=((-1*int(b)+(sqrt((int(b)**2)-(4*int(a)*int(c))))/2*int(a)))
x2=((-1*int(b)-(sqrt((int(b)**2)-(4*int(a)*int(c))))/2*int(a)))
my_answer="(x+"+str(-1*x1)+")(x+"+str(-1*x2)+")"
xinputs= "x1= "+ str(x1) + " and x2= "+str(x2)
answers= my_answer+", "+ xinputs
return answers
class quadratic(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent=parent
self.initialize()
def initialize(self):
self.grid()
self.entryVariableA = Tkinter.StringVar()
self.entry= Tkinter.Entry(self, textvariable= self.entryVariableA)
self.entry.grid(column=0,row=2,sticky="W")
self.entry.bind("<Return>",self.OnPressEnter)
self.entryVariableA.set(u"a")
self.entryVariableB = Tkinter.StringVar()
self.entry= Tkinter.Entry(self, textvariable= self.entryVariableB)
self.entry.grid(column=0,row=3,sticky="W")
self.entry.bind("<Return>",self.OnPressEnter)
self.entryVariableB.set(u"b")
self.entryVariableC = Tkinter.StringVar()
self.entry= Tkinter.Entry(self, textvariable= self.entryVariableC)
self.entry.grid(column=0,row=4,sticky="W")
self.entry.bind("<Return>",self.OnPressEnter)
self.entryVariableC.set(u"c")
button = Tkinter.Button(self, text= u"Solve!", command=self.OnButtonClick)
button.grid(column=1,row=5)
self.labelVariable= Tkinter.StringVar()
self.Eq_labelVariable=Tkinter.StringVar()
self.Ans_labelVariable=Tkinter.StringVar()
label= Tkinter.Label(self, textvariable=self.labelVariable,anchor= 'w', fg='black',bg='blue')
label.grid(column=0,row=0, columnspan=2, sticky='EW')
self.labelVariable.set(u"Enter Equation Here...")
Eq_label=Tkinter.Label(self, textvariable=self.Eq_labelVariable,anchor='w', fg='white', bg='blue')
Eq_label.grid(column=0, row=1, columnspan=2, sticky='EW')
self.Eq_labelVariable.set(u"For A(x^2)+B(x)+C")
Ans_label=Tkinter.Label(self, textvariable=self.Ans_labelVariable,anchor='w', fg='black', bg='green')
Ans_label.grid(column=0, row=1, columnspan=2, sticky='EW')
self.Ans_labelVariable.set(u"Answer will show here")
self.grid_columnconfigure(0,weight=1)
self.resizable(True, False)
self.update()
self.geometry(self.geometry())
self.entry.focus_set()
self.entry.selection_range(0,Tkinter.END)
def OnButtonClick(self):
self.Ans_labelVariable.set(quadprogram(self.entryVariableA,self.entryVariableB,self.entryVariableC)+"(this program works?!)")
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)
def OnPressEnter(self,event):
self.labelVariable.set(self.entryVariableA.get())
if __name__=='__main__':
app=quadratic(None)
app.title("Quadratic Solver")
app.geometry("300x300")
app.mainloop()
Anyone have any thoughts on avoiding that? Thanks for the help...
Answer: Everything is being initialized when you create the class, including whichever
values are in your entry widgets. Make methods to retrieve the values in the
entry widgets, and keep those methods out of your initialization. I will
update answer with code in a few minutes.
|
Writing a method that I can call in a separate script in python
Question: I am trying to write a method that I can call in a different script, however,
I am not able to successfully call the script(s) with the way I have it
written. This is one of the scripts I am trying to call (the second is very
similar:
#!usr/bin/env python
import re
import urllib
from datetime import datetime
from datetime import timedelta
date = datetime.now()
date1 = date + timedelta(days=1)
date2 = date + timedelta(days=2)
class city :
def __init__(self, city_name, link) :
self.name = city_name
self.url = link
self.wind1 = 0
def retrieveTemps(self) :
filehandle = urllib.urlopen(self.url)
# get lines from result into array
lines = filehandle.readlines()
# (for each) loop through each line in lines
line_number = 0 # a counter for line number
for line in lines:
line_number = line_number + 1 # increment counter
# find string, position otherwise position is -1
position2 = line.rfind('<ul class="stats">')
#String is found in line
if position2 > 0 :
self.wind0 = lines[line_number + 1].split('</strong>')[0].split('style="">')[-1]
break # done with loop, break out of it
return ('c.wind0')
filehandle.close()
m1 = city('Mexico City', 'http://www.accuweather.com/en/mx/mexico-city/242560/daily-weather-forecast/242560?day=2')
m3 = city('Veracruz', 'http://www.accuweather.com/en/mx/veracruz/236233/daily-weather-forecast/236233?day=2')
m5 = city('Tampico', 'http://www.accuweather.com/en/mx/tampico/235985/daily-weather-forecast/235985?day=2')
m7 = city('Nuevo Laredo', 'http://www.accuweather.com/en/mx/nuevo-laredo/235983/daily-weather-forecast/235983?day=2')
m9 = city('Monterrey', 'http://www.accuweather.com/en/mx/monterrey/244681/daily-weather-forecast/244681?day=2')
m11 = city('S. Luis Potosi', 'http://www.accuweather.com/en/mx/san-luis-potosi/245369/daily-weather-forecast/245369?day=2')
m13 = city('Queretaro', 'http://www.accuweather.com/en/mx/queretaro/245027/daily-weather-forecast/245027?day=2')
m15 = city('Laz. Cardenas', 'http://www.accuweather.com/en/mx/lazaro-cardenas/239054/daily-weather-forecast/239054?day=2')
cities = []
cities.append(m1)
cities.append(m3)
cities.append(m5)
cities.append(m7)
cities.append(m9)
cities.append(m11)
cities.append(m13)
cities.append(m15)
I try to call this script and another script with this:
#!usr/bin/env python
from script import getCities
from script2 import getWind
cities = getCities()
wind = getWind()
for c in wind :
c.retrieveTemps()
for c in cities :
c.retrieveTemps()
print(c.name,c.high0,c.low0,c.high1,c.low1,c.weather0,c.weather1,c.wind0,c.wind1)
c.wind0 is found with script2, while all the other variables are found with
script1. If I import script1 second, I get the error: AttributeError: city
instance has no attribute 'wind1', which has no attribute with script2, it is
associated with script1. It seems to be ignoring the first script I import.
Any suggestions would be appreciated. Thanks!
UPDATE:
Using your suggestions, plus something else, I came up with this and it works
perfectly.
#!usr/bin/env python
import script1
import script2
wind = script2.getWind()
cities = script.getCities()
for c in cities :
c.retrieveTemps()
for w in wind :
w.retrieveWind()
# iterate over both lists in parallel, zip returns a tuple
for c, w in zip(cities, wind) :
print(c.name,c.high0,c.low0,c.high1,c.low1,c.weather0,c.weather1,c.wind0,w.wind1)
Thanks everyone for your help!
Answer: Make everything below the class a function that returns `cities`, import the
function, and call it, setting `cities` to a new local variable. Then you can
run your for loop.
Disclaimer: I didn't test this at all.
Step1:
def getCities():
m1 = city('Mexico City', 'http://www.accuweather.com/en/mx/mexico-city/242560/daily-weather-forecast/242560?day=2')
m3 = city('Veracruz', 'http://www.accuweather.com/en/mx/veracruz/236233/daily-weather-forecast/236233?day=2')
m5 = city('Tampico', 'http://www.accuweather.com/en/mx/tampico/235985/daily-weather-forecast/235985?day=2')
m7 = city('Nuevo Laredo', 'http://www.accuweather.com/en/mx/nuevo-laredo/235983/daily-weather-forecast/235983?day=2')
m9 = city('Monterrey', 'http://www.accuweather.com/en/mx/monterrey/244681/daily-weather-forecast/244681?day=2')
m11 = city('S. Luis Potosi', 'http://www.accuweather.com/en/mx/san-luis-potosi/245369/daily-weather-forecast/245369?day=2')
m13 = city('Queretaro', 'http://www.accuweather.com/en/mx/queretaro/245027/daily-weather-forecast/245027?day=2')
m15 = city('Laz. Cardenas', 'http://www.accuweather.com/en/mx/lazaro-cardenas/239054/daily-weather-forecast/239054?day=2')
cities = []
cities.append(m1)
cities.append(m3)
cities.append(m5)
cities.append(m7)
cities.append(m9)
cities.append(m11)
cities.append(m13)
cities.append(m15)
return cities
Step 2:
from script1 import getCities
Step 3:
cities = getCities()
for c in cities :
c.retrieveTemps()
print(c.name,c.high0,c.low0,c.high1,c.low1,c.weather0,c.weather1,c.wind0,c.wind1)
|
Python-ldap not able to bind successfully
Question: I am not having any luck finding answers on this, so here it goes.
When I attemtp to connect to an AD server using python-ldap, it appears to
work successfully for some functions, and not for others. My connection:
>>>import sys
>>>import ldap
>>>l = ldap.initialize("ldap://company.com:389")
>>>l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
>>>l.simple_bind_s("[email protected]","password")
(97, [], 1, [])
Some simple google searching indicated that the 97 meant success, although the
level of success is a bit wonky. But, for some reason, I cant find anything on
the status code 1. If I run some ldap functions on the connection, some of
them work and some do not.
>>>l.whoami_s()
'u:COMPANY.COM\\user'
Seems to return fine, but
>>> base_dn = 'dc=company,dc=com'
>>> retrieveAttributes = ["uniquemember"]
>>> searchFilter = "cn=user"
>>> l.search_s(base_dn, ldap.SCOPE_SUBTREE,searchFilter,retrieveAttributes)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/user/.envs/scoring/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 552, in search_s
return self.search_ext_s(base,scope,filterstr,attrlist,attrsonly,None,None,timeout=self.timeout)
File "/home/user/.envs/scoring/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 546, in search_ext_s
return self.result(msgid,all=1,timeout=timeout)[1]
File "/home/user/.envs/scoring/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 458, in result
resp_type, resp_data, resp_msgid = self.result2(msgid,all,timeout)
File "/home/user/.envs/scoring/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 462, in result2
resp_type, resp_data, resp_msgid, resp_ctrls = self.result3(msgid,all,timeout)
File "/home/user/.envs/scoring/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 469, in result3
resp_ctrl_classes=resp_ctrl_classes
File "/home/user/.envs/scoring/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 476, in result4
ldap_result = self._ldap_call(self._l.result4,msgid,all,timeout,add_ctrls,add_intermediates,add_extop)
File "/home/user/.envs/scoring/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 99, in _ldap_call
result = func(*args,**kwargs)
OPERATIONS_ERROR: {'info': '000004DC: LdapErr: DSID-0C0906E8, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1', 'desc': 'Operations error'}
I am stumped to why the whoami would work but the search would not. I am using
a domain admin for the user, so it shouldn't have anything to do with
permissions to the directory. Can anyone shed some light?
Answer: I was getting the exact same error as you, what I did was adding this line (as
suggested by Christopher), l.set_option(ldap.OPT_REFERRALS, 0) before doing
the binding, e.g.
conn.protocol_version = ldap.VERSION3
conn.set_option(ldap.OPT_REFERRALS, 0)
conn.simple_bind_s(user, pw)
And after that my connection to LDAP worked fine.
|
how to get the index of numpy.random.choice? - python
Question: Is it possible to modify the numpy.random.choice function in order to make it
return the index of the chosen element? Basically, I want to create a list and
select elements randomly without replacement
import numpy as np
>>> a = [1,4,1,3,3,2,1,4]
>>> np.random.choice(a)
>>> 4
>>> a
>>> [1,4,1,3,3,2,1,4]
`a.remove(np.random.choice(a))` will remove the first element of the list with
that value it encounters (`a[1]` in the example above), which may not be the
chosen element (eg, `a[7]`).
Answer:
numpy.random.choice(a, size=however_many, replace=False)
If you want a sample without replacement, just ask numpy to make you one.
Don't loop and draw items repeatedly. That'll produce bloated code and
horrible performance.
Example:
>>> a = numpy.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.random.choice(a, size=5, replace=False)
array([7, 5, 8, 6, 2])
|
Python Pyplot: How to scale x-axis independant from number of list-elements?
Question: Just want to plot a list with 50 (actually 51) elements: The list indices from
0 to 50 should represent meters from 0 to 10 meters on the x-axis, while the
index of every further element increases by 0.2 meters. Example:
list = [2.5, 3, 1.5, ... , 7, 9]
len(list)
>>50
I would like the x-axis plotted from 0 to 10 meters, i.e. (x,y)==(0, 2.5),
(0.2, 3), (0.4, 1.5), ..., (9.8, 7), (10, 9)
Instead, the list is obviously plotted on an x-scale from 0 to 50. Any idea
how to solve the problem? Thanks!
Answer: I would avoid naming a list object `list`. It confuses the namespace. But try
something like
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(0, 10, 0.2)
y = [2.5, 3, 1.5, ... , 7, 9]
ax.plot(x, y)
plt.show()
It creates a list of point on the x-axis, which occur at multiples of `0.2`
using `np.arange`, at which matplotlib will plot the y values. Numpy is a
library for easily creating and manipulating vectors, matrices, and arrays,
especially when they are very large.
Edit:
`fig.add_subplot(N_row,N_col,plot_number)` is the object oriented approach to
plotting with matplotlib. It's useful if you want to add multiple subplots to
the same figure. For example,
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
adds two subplots to the same figure `fig`. They will be arranged one above
the other in two rows. `ax2` is the bottom subplot. Check out this [relevant
post](http://stackoverflow.com/questions/3584805/in-matplotlib-what-
does-111-means-in-fig-add-subplot111) for more info.
To change the actual x ticks and tick labels, use something like
ax.set_xticks(np.arange(0, 10, 0.5))
ax.set_xticklabels(np.arange(0, 10, 0.5))
# This second line is kind of redundant but it's useful if you want
# to format the ticks different than just plain floats.
|
How to write program run matrix as below in python?
Question: Thanks for everyone's reply. I will explain here. Suppose there is a given
matrix
x y B = [5,-4,5,-6]
[[0,0,0,0], [[0,1,0,1],
[0,0,0,0], [0,0,0,0],
[0,0,0,0], [0,0,0,1],
[0,0,0,0]] [0,0,0,0]]
for example a feasible solution is [[0,4,0,1],[0,0,0,0],[0,0,0,5],[0,0,0,0]]
4+1-0 == 5 0-4 == -4 5-0 == 5 0 - 5-1 == -6
I want to update x to make sure:
(1) if y[i][j] == 0:
x[i][j] = 0
(2) x[0][0]+x[0][1]+x[0][2]+x[0][3]-x[0][0]-x[1][0]-x[2][0]-x[3][0] = B[0]
x[1][0]+x[1][1]+x[1][2]+x[1][3]-x[0][1]-x[1][1]-x[2][1]-x[3][1] = B[1]
...
How to program to find the feasible x?
Answer: answer updated, i wrote some code to parse variables.
B = [5,-4,5,-6]
y = [
[0,1,0,1],
[0,0,0,0],
[0,0,0,1],
[0,0,0,0],
]
x = []
for i, row in enumerate(y):
temp = []
for j, col in enumerate(row):
if col != 0:
temp.append(str(col) + '*x' + str(i) + str(j))
else:
temp.append(col)
x.append(temp)
#for one in x:
# print one
equ = []
for i in xrange(4):
temp1 = []
temp2 = []
for j in xrange(4):
temp1.append(x[i][j])
temp2.append(x[j][i])
temp2.append(B[i])
equ.append(tuple(temp1 + temp2))
equtions = []
for one in equ:
s = '%s + %s + %s + %s - %s - %s - %s - %s = %s' % one
equtions.append(s)
for one in equtions:
print one
import re
from copy import deepcopy
equ_bak = deepcopy(equtions)
p_var = re.compile(r'x\d\d')
vars = set([])
for one in equ_bak:
m = p_var.findall(one)
vars |= set(m)
vars = sorted(list(vars))
p_ef = re.compile(r'([+-]* *\d*)\*(x\d\d)')
effs = []
for one in equ_bak:
m = p_ef.findall(one)
#print m
temp = [0] * len(vars)
for num, var in m:
try:
temp[vars.index(var)] = float(num.replace(' ', ''))
except:
pass
effs.append(tuple(temp))
#for one in effs:
# print one
import numpy as np
A = np.array(effs)
x = np.linalg.lstsq(A,B)
print vars
print x[0]
|
Set attribute to Element in Python
Question: I am using ElementTree to build an xml. But I am getting an error at Line no:
5
AttributeError: **setattr**
1.import xml.etree.cElementTree as ET
2.summary = open(Summary.xml, 'w')
3.root = ET.Element('Summary')
4.ET.SubElement(root, 'TextSummary')
5.ET.SubElement(root,'TextSummary').__setattr__('Status','Completed')
6.tree = ET.ElementTree(root)
7.tree.write(summary)
8.summary.close()
After code execution, my xml should look like mentioned below.
< Summary>
< TextSummary Status = 'Completed'/>
< /Summary>
How to add attributes to Elements in xml using python
**_xml.etree.cElementTree_**
Answer: You should be doing:
ET.SubElement(root,'TextSummary').set('Status','Completed')
The [Etree documentation shows
usage](http://docs.python.org/2/library/xml.etree.elementtree.html#modifying-
an-xml-file).
|
Connection to other side was lost in a non-clean fashion
Question:
from scrapy.spider import BaseSpider
class dmozSpider(BaseSpider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
def parse(self, response):
filename = response.url.split("/")[-2]
open(filename, 'wb').write(response.body)
then I run "scrapy crawl dmoz" then I got this error:
> 2013-09-14 13:20:56+0700 [dmoz] DEBUG: Retrying
> http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/>
> (failed 1 times): Connection to other side was lost in a non-clean fashion.
Does anyone know how to fix this?
Answer: You need to check your internet connection or if you're using proxy, set your
environment variables for proxy authentication.
In windows, try these steps:
1. `Win`+`R` type 'systempropertiesadvanced' (without quote)
2. Click "Environment Variables..." button
3. Add 2 new variables (either user/system variable is fine):
name | value
------------+--------------------------------
HTTP_PROXY | http://username:password@host:port
HTTPS_PROXY | https://username:password@host:port
alternative way: [setting-proxy-env](http://superuser.com/questions/48813/how-
to-set-a-proxy-server-for-connecting-to-the-internet-in-lynx)
|
python: 500 error using json.load() in cherrypy
Question: My code runs fine locally but I get a 500 error with the webhost I'm using.
The problem seems to come from the line
js = json.load(data)
in the search method. Is there something in the cherrypy config that I'm
missing? Any thoughts?
#!/usr/local/bin/python3.2
import cherrypy
import json
import numpy as np
from urllib.request import urlopen
class Root(object):
@cherrypy.expose
def index(self):
a_query = Query()
text = a_query.search()
return '''<html>
Welcome to Spoti.py! %s
</html>''' %text
class Query():
def __init__(self):
self.qstring = '''if i can't'''
def space_to_plus(self):
self.qstring = self.qstring.replace(' ', '+')
def search(self):
self.space_to_plus()
url = 'http://ws.spotify.com/search/1/track.json?q=' + self.qstring
data = urlopen(url)
js = json.load(data)
return self.qstring
cherrypy.config.update({
'environment': 'production',
'log.screen': False,
'server.socket_host': '127.0.0.1',
'server.socket_port': 15083,
})
cherrypy.config.update({'tools.sessions.on': True})
cherrypy.quickstart(Root())
Answer: It seems json.loads() is expecting a unicode object when bytes are given. Try
this:
data = urlopen(url).read()
js = json.loads(data.decode('utf-8'))
|
Python import and reload misunderstanding
Question: The original title was: 'Numpy array: 'data type not understood''. Turns out,
the problem was my misunderstanding of Python as an interpreted language.
I have this very simple module 'rtm.py':
import numpy as np
def f():
A=np.array([[1.0,0.5],[0.0,1.0]])
But when I run it in IPython:
import rtm
rtm.f()
I get this error:
1 import numpy as np
2 def f():
----> 3 np.array([[1.0,0.5],[0.0,1.0]])
TypeError: data type not understood
Which part in the documentation didn't I understand?
Thanks in advance!
Answer: If you want to made external changes in modules visible inside interpreter
session you have to use reload instead import:
Python 2
import rtm
# some change in rtm.foo has been made
import rtm
rtm.foo() # Old version of rtm.foo is called
reload(rtm) # You have to reload module ([docs][1])
rtm.foo() # Now you can call new version of rtm.foo
Python 3
...
from imp import reload
reload(rtm)
|
Recursive sorting function for list in Python
Question: I want to take a list like the following:
groups = ["foo", "bar", "foo::fone", "foo::ftwo", "foo::ftwo::ffone"]
And convert it into a nested list, probably in the following format, but I'm
open to suggestions:
groups_sorted = [{
"name":"foo",
"children": [
{
"name": "foo::fone",
"children": [ ... ]
}, ...
]
}, ...
]
So that the list is sorted using a hierarchy split on `::`. I need each of the
`children` keys to be lists themselves as the original order of the list is
important.
I've played around for a few hours and been able to create a recursive
dictionary starting from a single top node, but I couldn't do the last bit.
Find my workings below:
def children_of(node, candidates):
children = []
remainder = []
for c in candidates:
sub = node + "::"
if c.startswith(sub):
try:
c[len(sub):].index("::") # any more separators = not a child
remainder.append(c)
except ValueError: # a child
children.append(c)
else: #not related
remainder.append(c)
return children, remainder
def sortit(l):
if l:
el = l.pop(0)
children, remainder = children_of(el,l)
if children:
return { "name": el,
"children": [sortit([c]+remainder) for c in children]
}
else:
return { "name": el }
**Edit** : @Thijs van Dien's solution is really good but I need 2.6
compatibility which prevents me some using OrderDicts.
Answer: How about something like this instead?
from collections import OrderedDict
dic = OrderedDict()
def insert(name):
current_dic = dic
current_name = ''
for name_elem in name.split('::'):
current_name += ('::' if current_name else '') + name_elem
if not current_name in current_dic:
current_dic[current_name] = OrderedDict()
current_dic = current_dic[current_name]
for group in ["foo", "bar", "foo::fone", "foo::ftwo", "foo::ftwo::ffone"]:
insert(group)
That gives you the following structure:
{'bar': {}, 'foo': {'foo::fone': {}, 'foo::ftwo': {'foo::ftwo::ffone': {}}}}
`OrderedDict` makes sure that order is preserved, so you don't need to use any
`list`. Also, you don't need to use recursion, as it is not recommended in
Python.
If you don't have `OrderedDict` in the standard library, because you're using
Python 2.6, you can install it:
pip install ordereddict
Then change the import:
from ordereddict import OrderedDict
Here's another solution that works only if you can assume that parents already
exist when you need them. Things go bad if you have duplicate groups, so you
need to adjust it for that yourself.
children_of_name = dict([('', list())]) # Access root with empty string
def insert(name):
parent_name = '::'.join(name.split('::')[:-1])
dic = dict([('name', name), ('children', list())])
children_of_name[parent_name].append(dic)
children_of_name[name] = dic['children']
for group in ["foo", "bar", "foo::fone", "foo::ftwo", "foo::ftwo::ffone"]:
insert(group)
It gives you the structure that you proposed:
[{'children': [{'children': [], 'name': 'foo::fone'},
{'children': [{'children': [], 'name': 'foo::ftwo::ffone'}],
'name': 'foo::ftwo'}],
'name': 'foo'},
{'children': [], 'name': 'bar'}]
|
Finding the Coordinates of Maxima in an Image
Question: **Background:**
I'm new to using Python's PIL for photo manipulation, and have very recently
found the need for a basic photo processing function within an existing
program. My program currently imports an image (effectively a high res shot of
the night sky) in which there is a large proportion of black space (obviously)
and several bright white maxima.
**Question:**
What is the best way of finding the coordinates (relative to the canvas
coordinates if possible) of _every_ maxima in the imported image?
I have looked through the PIL documentation, and have found ways to obtain the
number of pixels of a certain colour, but of course this doesn't fulfil my
requirements. As I say, I'm new to PIL/Photo-manipulation with Python, so any
help on this would be fantastic.
Thanks in advance! :)
Answer: There is a `getextrema()` method that returns the lowest and highest image
data used for every band. So in order to find the brightest pixels, you need a
grayscale copy of your image first. Then you can iterate over every pixel in
the image and check each pixel whether it has the highest grayscale value:
grayscale = image.convert('L')
minima, maxima = grayscale.getextrema()
for width in image.size[0]:
for height in image.size[1]:
if grayscale.getpixel((width, height)) == maxima:
# So here we have one pixel with the highest brightness.
However dependent on what you are actually try to achieve there might be
simpler and more efficient ways of doing it. For example when you want to
paste all the brightest pixels on a black background, you could do it like
that:
grayscale = image.convert('L')
minima, maxima = grayscale.getextrema()
mask = image.point([0] * maxima + [255] * (256 - maxima))
new_image = PIL.Image.new('RGB', image.size)
new_image.paste(image, mask=mask)
|
Python export csv data into file
Question: I have following code which works well but I am not able to trim and store a
data in a datafile:
import nltk
tweets = [
(['love', 'this', 'car']),
(['this', 'view', 'amazing']),
(['not', 'looking', 'forward', 'the', 'concert'])
]
def get_words_in_tweets(tweets):
all_words = []
for (words) in tweets:
all_words.extend(words)
return all_words
def get_word_features(wordlist):
wordlist = nltk.FreqDist(wordlist)
word_features = wordlist.keys()
return word_features
output = open('wordFeatures.csv','w')
word_features = get_word_features(get_words_in_tweets(tweets))
print (word_features)
output.write(word_features)
#print (wordlist)
output.close()
What it does is, it checks if words a double or triple etc and only adds one
word in the list. The output looks like this:
['this', 'amazing', 'car', 'concert', 'forward', 'looking', 'love', 'not', 'the', 'view']
Now as you can see I tried to save this data in a textfile but I get an
TypeError: expected a character buffer object
I want the data from the array in a textfile in the following format:
1:this
2:amazing
3:car
4:concert
5:forward
...
so one row for every word with an increasing integer.
Has someone an idea how to save my data in this way?
Answer: The reason for the error is that `output.write` accepts a string, not a
`list`. `word_features` is a `list`.
To write a list to a file, you will need to iterate over it:
for feature in word_features:
output.write("{0}\n".format(feature))
I don't understand the format you need because of the `car` and `concert`
coming together on the same line. I am assuming that is a typo and you
actually need them on separate lines. Then you can do this to obtain that
output:
for nfeature in enumerate(word_features):
output.write("{0}:{1}\n".format(nfeature[0] + 1, nfeature[1]))
|
SQLAlchemy/Pyramid tutorial: attempt to write to readonly database
Question: I am banging my head over this one. I have successfully completed the
SQLAlcemy + URL Dispatch tutorial in the past. Now whatever I do, the attempts
to write to the sqlite db file all fail, throwing:
OperationalError: (OperationalError) attempt to write a readonly database u'INSERT INTO pages (name, data) VALUES (?, ?)' (u'NewPage', u'A new page is dawning.')
The variations in my current configuration are:
* I am running through the tutorial under mod_wsgi, not the pserve.
* result is the same running under pserve
* this system is running python 2.6.5 vs 2.7.5
The datafile initializes fine. The ownership is the same as the wsgi process
owner. I'm baffled.
Here's the models.py:
from sqlalchemy import (
Column,
Index,
Integer,
Text,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Page(Base):
__tablename__ = 'pages'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
data = Column(Text)
def __init__(self, name, data):
self.name = name
self.data = data
Index('page_index', Page.name, unique=True, mysql_length=255)
Pretty straightforward out of the tutorial.
Any thoughts greatly appreciated.
Answer: Daemon process owner could not write to the file even though the same owner
created the file. WTF? Anyway, manually setting 666 on the sqlite file has
cleared this up.
|
Python Cookie Clicker: Auto Click Function?
Question: **My Background:** I have done quite a bit of programming with python, I would
say I am not bad at it. I am familiar with most of the modules, OOP
programming and stuff. You can check my pastebin profile to see what level I
am actually in: www.pastebin.com/u/GameNationRDF/
**The Code:**
from tkinter import *
import time
master = Tk()
def uiPrint():
info()
print ("")
print (click)
blankLine()
def info():
print ("Double click purchases need 750 clicks!")
info()
click = 0
mult = 1
dcp1 = 0
def blankLine():
for i in range(20):
print ("")
def purchaseDoubleClicksCommand():
global click
global mult
if click < 750:
print ("Not enough clicks!")
blankLine()
elif click >= 750:
mult = mult*2
click = click - 750
print ("Double Clicks Purchased!")
blankLine()
def buttonCommand():
global click
global mult
click += 1*(mult)
uiPrint()
if click == 100:
print ('''Achievement Unlocked: Junior Clicker!
BONUS 100!''')
click += 100
elif click == 400:
print ('''Achievement Unlocked: Little Ninja Clicks!
BONUS 200!''')
click += 300
elif click == 900:
print ('''Achievement Unlocked: Legit Ninja!
DOUBLE CLICKS!''')
mult = mult * 2
elif click == 1500:
print ('''Achievement Unlocked: Click Ninja Master!
QUAD CLICKS!''')
mult = mult * 4
elif click == 3000:
print ('''Achievement Unlocked: Jackie Chan Style!
8 TIMES THE CLICKS!''')
mainClickButton = Button(master, text="Click!", command=buttonCommand)
mainClickButton.pack()
purchaseDoubleClickButton = Button(master, text="Purchase Double Clicks", command = purchaseDoubleClicksCommand)
purchaseDoubleClickButton.pack()
master.title("Clicker! v0.0.6")
master.geometry("%sx%s+%s+%s" % (200,70,512,512))
mainloop()
I need a way to be able to add a auto-clicker that would add certain amount of
cookies in a given time. I want it to be purchased by a button. I couldnt get
it to work though :(
Any help? Thanks :)
Answer: The [PyUserInput project](https://github.com/SavinaRoja/PyUserInput) looks
promising and straightforward:
from pymouse import PyMouse
m = PyMouse()
x_dim, y_dim = m.screen_size()
m.click(x_dim/2, y_dim/2, 1)
Why do you `import *` by the way? It's bad practice to import more
dependencies than needed. Also if I were you I would move the following
section of code:
master = ()
info()
click = 0
mult = 1
dcp1 = 0
to reside above this line:
mainlickButton = Button(master, text="Click!", command=buttoncommand)
It's just cleaner to add declarations and functions. It doesn't make a
GINORMOUS difference now, but when your file gets bigger and you have a lot of
code it will be easier to read.
|
Python datetime add
Question: I have a datetime value in string format. How can I change the format from a
"-" separated date to a "." separated date. I also need to add 6 hours to let
the data be in my time zone.
s = '2013-08-11 09:48:49'
from datetime import datetime,timedelta
mytime = datetime.strptime(s,"%Y-%m-%d %H:%M:%S")
time = mytime.strftime("%Y.%m.%d %H:%M:%S")
dt = str(timedelta(minutes=6*60)) #6 hours
time+=dt
print time
print dt
I get the following result where it adds the six hours at the end and not to
the nine:
2013.08.11 09:48:496:00:00
6:00:00
Answer: You are adding the _string representation_ of the `timedelta()`:
>>> from datetime import timedelta
>>> print timedelta(minutes=6*60)
6:00:00
Sum `datetime` and `timedelta` objects, not their string representations; only
create a string **after** summing the objects:
from datetime import datetime, timedelta
s = '2013-08-11 09:48:49'
mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
mytime += timedelta(hours=6)
print mytime.strftime("%Y.%m.%d %H:%M:%S")
This results in:
>>> from datetime import datetime, timedelta
>>> s = '2013-08-11 09:48:49'
>>> mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
>>> mytime += timedelta(hours=6)
>>> print mytime.strftime("%Y.%m.%d %H:%M:%S")
2013.08.11 15:48:49
However, you probably want to use real timezone objects instead, I recommend
you use the [`pytz` library](http://pytz.sourceforge.net/):
>>> from pytz import timezone, utc
>>> eastern = timezone('US/Eastern')
>>> utctime = utc.localize(datetime.strptime(s, "%Y-%m-%d %H:%M:%S"))
>>> local_tz = utctime.astimezone(eastern)
>>> print mytime.strftime("%Y.%m.%d %H:%M:%S")
2013.08.11 15:48:49
This will take into account daylight saving time too, for example.
|
Writing multi-line strings to cells using xlwt module
Question: Python: Is there a way to write multi-line strings into an excel cell with
just the xlwt module? (I saw answers suggesting use of openpyxl module)
The `sheet.write()` method ignores the \n escape sequence. So, just xlwt, is
it possible? Thanks in advance.
Answer: I found the answer in the [python-excel Google
Group](https://groups.google.com/d/topic/python-excel/9eMr2npsKXY/discussion).
Using `sheet.write()` with the optional `style` argument, enabling word wrap
for the cell, does the trick. Here is a minimum working example:
import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet('Test')
# A1: no style, no wrap, despite newline
sheet.write(0, 0, 'Hello\nWorld')
# B1: with style, there is wrap
style = xlwt.XFStyle()
style.alignment.wrap = 1
sheet.write(0, 1, 'Hello\nWorld', style)
book.save('test.xls')
While in cell A1 shows `HelloWorld` without linebreak, cell B1 shows
`Hello\nWorld` (i.e. with linebreak).
|
Url open with username and password
Question: I have started to learn scala , the only other language I know is python. I am
trying to write a code in scala which I have written in python. In that code I
have to open a url thats in xml format which require a username and password
and then parse it and get the elements which matches string name=ID
Here is my python code
import urllib2
theurl = 'Some url'
username = 'some username'
password = 'some password'
# a great password
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, theurl, username, password)
# because we have put None at the start it will always
# use this username/password combination for urls
# for which `theurl` is a super-url
authhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandler
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler
# Make sure not to include the protocol in with the URL, or
# HTTPPasswordMgrWithDefaultRealm will be very confused.
# You must (of course) use it when fetching the page though.
pagehandle = urllib2.urlopen(theurl)
# authentication is now handled automatically for us
##########################################################################
from xml.dom.minidom import parseString
file = pagehandle
#convert to string:
data = file.read()
#close file because we dont need it anymore:
file.close()
#parse the xml you downloaded
dom = parseString(data)
#retrieve the first xml tag (<tag>data</tag>) that the parser finds with name tagName:
xmlData=[]
for s in dom.getElementsByTagName('string'):
if s.getAttribute('name') == 'ID':
xmlData.append(s.childNodes[0].data)
print xmlData
and this is what I have written in scala to open a url I am still to figure
out how to handle it with username password I have searched on internet
regarding the same and still didnt get what I am looking for.
object URLopen {
import java.net.URL
import scala.io.Source.fromURL
def main(arg: Array[String]){
val u = new java.net.URL("some url")
val in = scala.io.Source.fromURL(u)
for (line <- in.getLines)
println(line)
in.close()
}
}
Can someone help me to handle the url open with username password or tell me
from where I can learn how to do it? In python we have
docs.python.org/library/urllib2.html where I can learn about various modules
and how to use them. Is there some link for scala too?
PS: Any help regarding parsing xml and getting the elements with string name=
ID is also welcomed
Answer: What you are describing is Basic Authentication in which case you need:
import org.apache.commons.codec.binary.Base64;
object HttpBasicAuth {
val BASIC = "Basic";
val AUTHORIZATION = "Authorization";
def encodeCredentials(username: String, password: String): String = {
new String(Base64.encodeBase64String((username + ":" + password).getBytes));
};
def getHeader(username: String, password: String): String =
BASIC + " " + encodeCredentials(username, password);
};
Then just add this as a request header.
import scala.io.Source
import java.net.URL
object Main extends App {
override def main(args: Array[String]) {
val connection = new URL(yoururl).openConnection
connection.setRequestProperty(HttpBasicAuth.AUTHORIZATION, HttpBasicAuth.getHeader(username, password);
val response = Source.fromInputStream(connection.getInputStream);
}
}
|
How to start a query from a static website?
Question: **The problem**
I have the following question: I need to search for some information about a
company using the following
[link](http://corp.sec.state.ma.us/CorpWeb/CorpSearch/CorpSearch.aspx).
What I need to do with it is a `search by entity name` with `search type`
being "begin with" drop down value. I also would like to see "All items" per
page in the `Display number of items to view` part. For example, if I input
"google" in the "Enter name" text box, the script should return a list of
companies with names start with "google" _(though this is just the starting
point of what I want to do)_.
**Question:** How should I use Python to do this? I found the following
thread: [Using Python to ask a web page to run a
search](http://stackoverflow.com/questions/13962006/using-python-to-ask-a-web-
page-to-run-a-search)
I tried the example in the first answer, the code is put below:
from bs4 import BeautifulSoup as BS
import requests
protein='Q9D880'
text = requests.get('http://www.uniprot.org/uniprot/' + protein).text
soup = BS(text)
MGI = soup.find(name='a', onclick="UniProt.analytics('DR-lines', 'click', 'DR-MGI');").text
MGI = MGI[4:]
print protein +' - ' + MGI
The above code works because the `UniPort` website contains `analytics`, which
takes those parameters. However,the website I am using doesn't have that.
I also tried to do the same thing as the first answer in this thread: [how to
submit query to .aspx page in
python](http://stackoverflow.com/questions/1480356/how-to-submit-query-to-
aspx-page-in-python)
However, the example code provide in the 1st answer does not work on my
machine _(Ubuntu 12.4 with Python 2.7)_. I am also not clear about which
values should be there since I am dealing with a different aspx website.
How could I use Python to start a search with certain criteria _(not sure this
is proper web terminology, may be submit a form?)_ ?
I am from a C++ background and did not do any web stuff. I am also learning
Python. Any help is greatly appreciated.
**First EDIT:**
With great help from @Kabie, I collected the following code (trying to
understand how it works):
import requests
from lxml import etree
URL = 'http://corp.sec.state.ma.us/CorpWeb/CorpSearch/CorpSearch.aspx'
#With get_fields(), we fetched all <input>s from the form.
def get_fields():
res = requests.get(URL)
if res.ok:
page = etree.HTML(res.text)
fields = page.xpath('//form[@id="Form1"]//input')
return { e.attrib['name']: e.attrib.get('value', '') for e in fields }
#hard code some selects from the Form
def query(data):
formdata = get_fields()
formdata.update({
'ctl00$MainContent$ddRecordsPerPage':'25',
}) # Hardcode some <select> value
formdata.update(data)
res = requests.post(URL, formdata)
if res.ok:
page = etree.HTML(res.text)
return page.xpath('//table[@id="MainContent_SearchControl_grdSearchResultsEntity"]//tr')
def search_by_entity_name(entity_name, entity_search_type='B'):
return query({
'ctl00$MainContent$CorpSearch':'rdoByEntityName',
'ctl00$MainContent$txtEntityName': entity_name,
'ctl00$MainContent$ddBeginsWithEntityName': entity_search_type,
})
result = search_by_entity_name('google')
The above code is put in a script named `query.py`. I got the following error:
> Traceback (most recent call last): File "query.py", line 39, in
> result = search_by_entity_name('google')
> File "query.py", line 36, in search_by_entity_name
> 'ctl00$MainContent$ddBeginsWithEntityName': entity_search_type,
> File "query.py", line 21, in query
> formdata.update({
> AttributeError: 'NoneType' object has no attribute 'update'
It seems to me that the search is not successful? Why?
Answer: You can inspect the page to find out all the fields need to be posted. There
is [a nice tutorial](http://discover-devtools.codeschool.com/) for `Chrome
DevTools`. Other tools like `FireBug` on FireFox or `DragonFly` on Opera also
do the work while I recommend `DevTools`.
After you post a query. In the `Network` panel, you can see the form data
which actually been sent. In this case:
__EVENTTARGET:
__EVENTARGUMENT:
__LASTFOCUS:
__VIEWSTATE:5UILUho/L3O0HOt9WrIfldHD4Ym6KBWkQYI1GgarbgHeAdzM9zyNbcH0PdP6xtKurlJKneju0/aAJxqKYjiIzo/7h7UhLrfsGul1Wq4T0+BroiT+Y4QVML66jsyaUNaM6KNOAK2CSzaphvSojEe1BV9JVGPYWIhvx0ddgfi7FXKIwdh682cgo4GHmilS7TWcbKxMoQvm9FgKY0NFp7HsggGvG/acqfGUJuw0KaYeWZy0pWKEy+Dntb4Y0TGwLqoJxFNQyOqvKVxnV1MJ0OZ4Nuxo5JHmkeknh4dpjJEwui01zK1WDuBHHsyOmE98t2YMQXXTcE7pnbbZaer2LSFNzCtrjzBmZT8xzCkKHYXI31BxPBEhALcSrbJ/QXeqA7Xrqn9UyCuTcN0Czy0ZRPd2wabNR3DgE+cCYF4KMGUjMUIP+No2nqCvsIAKmg8w6Il8OAEGJMAKA01MTMONKK4BH/OAzLMgH75AdGat2pvp1zHVG6wyA4SqumIH//TqJWFh5+MwNyZxN2zZQ5dBfs3b0hVhq0cL3tvumTfb4lr/xpL3rOvaRiatU+sQqgLUn0/RzeKNefjS3pCwUo8CTbTKaSW1IpWPgP/qmCsuIovXz82EkczLiwhEZsBp3SVdQMqtAVcYJzrcHs0x4jcTAWYZUejvtMXxolAnGLdl/0NJeMgz4WB9tTMeETMJAjKHp2YNhHtFS9/C1o+Hxyex32QxIRKHSBlJ37aisZLxYmxs69squmUlcsHheyI5YMfm0SnS0FwES5JqWGm2f5Bh+1G9fFWmGf2QeA6cX/hdiRTZ7VnuFGrdrJVdbteWwaYQuPdekms2YVapwuoNzkS/A+un14rix4bBULMdzij25BkXpDhm3atovNHzETdvz5FsXjKnPlno0gH7la/tkM8iOdQwqbeh7sG+/wKPqPmUk0Cl0kCHNvMCZhrcgQgpIOOgvI2Fp+PoB7mPdb80T2sTJLlV7Oe2ZqMWsYxphsHMXVlXXeju3kWfpY+Ed/D8VGWniE/eoBhhqyOC2+gaWA2tcOyiDPDCoovazwKGWz5B+FN1OTep5VgoHDqoAm2wk1C3o0zJ9a9IuYoATWI1yd2ffQvx6uvZQXcMvTIbhbVJL+ki4yNRLfVjVnPrpUMjafsnjIw2KLYnR0rio8DWIJhpSm13iDj/KSfAjfk4TMSA6HjhhEBXIDN/ShQAHyrKeFVsXhtH5TXSecY6dxU+Xwk7iNn2dhTILa6S/Gmm06bB4nx5Zw8XhYIEI/eucPOAN3HagCp7KaSdzZvrnjbshmP8hJPhnFhlXdJ+OSYDWuThFUypthTxb5NXH3yQk1+50SN872TtQsKwzhJvSIJExMbpucnVmd+V2c680TD4gIcqWVHLIP3+arrePtg0YQiVTa1TNzNXemDyZzTUBecPynkRnIs0dFLSrz8c6HbIGCrLleWyoB7xicUg39pW7KTsIqWh7P0yOiHgGeHqrN95cRAYcQTOhA==
__SCROLLPOSITIONX:0
__SCROLLPOSITIONY:106
__VIEWSTATEENCRYPTED:
__EVENTVALIDATION:g2V3UVCVCwSFKN2X8P+O2SsBNGyKX00cyeXvPVmP5dZSjIwZephKx8278dZoeJsa1CkMIloC0D51U0i4Ai0xD6TrYCpKluZSRSphPZQtAq17ivJrqP1QDoxPfOhFvrMiMQZZKOea7Gi/pLDHx42wy20UdyzLHJOAmV02MZ2fzami616O0NpOY8GQz1S5IhEKizo+NZPb87FgC5XSZdXCiqqoChoflvt1nfhtXFGmbOQgIP8ud9lQ94w3w2qwKJ3bqN5nRXVf5S53G7Lt+Du78nefwJfKK92BSgtJSCMJ/m39ykr7EuMDjauo2KHIp2N5IVzGPdSsiOZH86EBzmYbEw==
ctl00$MainContent$hdnApplyMasterPageWitoutSidebar:0
ctl00$MainContent$hdn1:0
ctl00$MainContent$CorpSearch:rdoByEntityName
ctl00$MainContent$txtEntityName:GO
ctl00$MainContent$ddBeginsWithEntityName:M
ctl00$MainContent$ddBeginsWithIndividual:B
ctl00$MainContent$txtFirstName:
ctl00$MainContent$txtMiddleName:
ctl00$MainContent$txtLastName:
ctl00$MainContent$txtIdentificationNumber:
ctl00$MainContent$txtFilingNumber:
ctl00$MainContent$ddRecordsPerPage:25
ctl00$MainContent$btnSearch:Search Corporations
ctl00$MainContent$hdnW:1920
ctl00$MainContent$hdnH:1053
ctl00$MainContent$SearchControl$hdnRecordsPerPage:
What I post is `Begin with 'GO'`. This site is build with `WebForms`, so there
are these long `__VIEWSTATE` and `__EVENTVALIDATION` fields. We need send them
as well.
Now we are ready to make the query. First we need to get a blank form. The
following code are written in Python 3.3, through I think they should still
work on 2.x.
import requests
from lxml import etree
URL = 'http://corp.sec.state.ma.us/CorpWeb/CorpSearch/CorpSearch.aspx'
def get_fields():
res = requests.get(URL)
if res.ok:
page = etree.HTML(res.text)
fields = page.xpath('//form[@id="Form1"]//input')
return { e.attrib['name']: e.attrib.get('value', '') for e in fields }
With `get_fields()`, we fetched all `<input>`s from the form. Note there are
also `<select>`s, I will just hardcode them.
def query(data):
formdata = get_fields()
formdata.update({
'ctl00$MainContent$ddRecordsPerPage':'25',
}) # Hardcode some <select> value
formdata.update(data)
res = requests.post(URL, formdata)
if res.ok:
page = etree.HTML(res.text)
return page.xpath('//table[@id="MainContent_SearchControl_grdSearchResultsEntity"]//tr')
Now we have a generic `query` function, lets make a wrapper for specific ones.
def search_by_entity_name(entity_name, entity_search_type='B'):
return query({
'ctl00$MainContent$CorpSearch':'rdoByEntityName',
'ctl00$MainContent$txtEntityName': entity_name,
'ctl00$MainContent$ddBeginsWithEntityName': entity_search_type,
})
This specific example site use a group of `<radio>` to determine which fields
to be used, so `'ctl00$MainContent$CorpSearch':'rdoByEntityName'` here is
necessary. And you can make others like `search_by_individual_name` etc. by
yourself.
Sometimes, website need more information to verify the query. By then you
could add some [custom headers](http://docs.python-
requests.org/en/latest/user/quickstart/#custom-headers) like `Origin`,
`Referer`, `User-Agent` to mimic a browser.
And if the website is using JavaScript to generate forms, you need more than
`requests`. [`PhantomJS`](http://phantomjs.org) is a good tool to make browser
scripts. If you want do this in Python, you can use
[`PyQt`](http://www.riverbankcomputing.co.uk/software/pyqt/) with `qtwebkit`.
**Update** : It seems the website blocked our Python script to access it after
yesterday. So we have to feign as a browser. As I mentioned above, we can add
a custom header. Let's first add a `User-Agent` field to header see what
happend.
res = requests.get(URL, headers={
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36',
})
And now... `res.ok` returns `True`!
So we just need to add this header in both call `res = requests.get(URL)` in
`get_fields()` and `res = requests.post(URL, formdata)` in `query()`. Just in
case, add `'Referer':URL` to the headers of the latter:
res = requests.post(URL, formdata, headers={
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36',
'Referer':URL,
})
|
The use of \s in replace vs regular expressions
Question: While learning python I got my first real python stumper when processing a
multi line file. It seems like `\s` in the replace method does not remove
newlines, where `\s` remove newlines when used in a regular expressions. I can
remove the newlines using replace `\n` just fine, but I am troubled that the
definition of `\s` is different for the replace method and regular
expressions. Is this really the case?
s_clean = s.replace('\s', '')
import re
s_clean = re.sub(r'\s', '', s)
Answer: Yes `string.replace` is different from `re.sub`. The former replaces the
substrings you ask to replace and the latter replaces substrings which are
occurrences of the _pattern_ you give it.
This design is intentional, and probably not something that should trouble
you. After all, one is a method on strings, the other is a method on regexes.
Here's another example that you might find interesting:
>>> import re
>>> s = "aaaa+b"
>>> s.replace("a+", "c")
'aaacb'
>>> re.sub(s, "a+", "c")
'c'
I think this is pretty sensible. Yes it is true that other languages expect
either a regex or a string in `replace`, but Python actually keeps them
distinct!
|
Python 2.7 - find and replace from text file, using dictionary, to new text file
Question: I am newbie to programming, and have been studying python in my spare time for
the past few months. I decided I was going to try and create a little script
that converts American spellings to English spellings in a text file.
I have been trying all sorts of things for the past 5 hours, but eventually
came up with something that got me somewhat closer to my goal, but not quite
there!
#imported dictionary contains 1800 english:american spelling key:value pairs.
from english_american_dictionary import dict
def replace_all(text, dict):
for english, american in dict.iteritems():
text = text.replace(american, english)
return text
my_text = open('test_file.txt', 'r')
for line in my_text:
new_line = replace_all(line, dict)
output = open('output_test_file.txt', 'a')
print >> output, new_line
output.close()
I am sure there is a considerably better way to go about things, but for this
script,here are the issues I am having:
* In the output file the lines are written on every other line, with a line break between, but the original test_file.txt does not have this. Contents of test_file.txt shown at bottom of this page
* Only the first instance of an American spelling in a line gets converted to English.
* I didn't really want to open output file in append mode, but couldn't figure out 'r' in this code structure.
Any help appreciated for this eager newb!
The contents of the test_file.txt are:
I am sample file.
I contain an english spelling: colour.
3 american spellings on 1 line: color, analyze, utilize.
1 american spelling on 1 line: familiarize.
Answer: The extra blank line you are seeing is because you are using `print` to write
out a line that already includes a newline character at the end. Since `print`
writes its own newline too, your output becomes double spaced. An easy fix is
to use `outfile.write(new_line)` instead.
As for the file modes, the issue is that you're opening the output file over
and over. You should just open it once, at the start. Its usually a good idea
to use `with` statements to handle opening files, since they'll take care of
closing them for you when you're done with them.
I don't undestand your other issue, with only some of the replacements
happening. Is your dictionary missing the spellings for `'analyze'` and
`'utilize'`?
One suggestion I'd make is to not do your replacements line by line. You can
read the whole file in at once with `file.read()` and then work on it as a
single unit. This will probably be faster, since it won't need to loop as
often over the items in your spelling dictionary (just once, rather than once
per line):
with open('test_file.txt', 'r') as in_file:
text = in_file.read()
with open('output_test_file.txt', 'w') as out_file:
out_file.write(replace_all(text, spelling_dict))
Edit:
To make your code correctly handle words that contain other words (like
"entire" containing "tire"), you probably need to abandon the simple
`str.replace` approach in favor of regular expressions.
Here's a quickly thrown together solution that uses `re.sub`, given a
dictionary of spelling changes from American to British English (that is, in
the reverse order of your current dictionary):
import re
#from english_american_dictionary import ame_to_bre_spellings
ame_to_bre_spellings = {'tire':'tyre', 'color':'colour', 'utilize':'utilise'}
def replacer_factory(spelling_dict):
def replacer(match):
word = match.group()
return spelling_dict.get(word, word)
return replacer
def ame_to_bre(text):
pattern = r'\b\w+\b' # this pattern matches whole words only
replacer = replacer_factory(ame_to_bre_spellings)
return re.sub(pattern, replacer, text)
def main():
#with open('test_file.txt') as in_file:
# text = in_file.read()
text = 'foo color, entire, utilize'
#with open('output_test_file.txt', 'w') as out_file:
# out_file.write(ame_to_bre(text))
print(ame_to_bre(text))
if __name__ == '__main__':
main()
One nice thing about this code structure is that you can easily convert from
British English spellings back to American English ones, if you pass a
dictionary in the other order to the `replacer_factory` function.
|
Exception during groupby pandas
Question: I am just beginning to learn analytics with python for network analysis using
the [Python For Data
Analysis](http://shop.oreilly.com/product/0636920023784.do) book and I'm
getting confused by an exception I get while doing some groupby's... here's my
situation.
I have a CSV of NetFlow data that I've imported to pandas. The data looks
something like:
dt, srcIP, srcPort, dstIP, dstPort, bytes
2013-06-06 00:00:01.123, 123.123.1.1, 12345, 234.234.1.1, 80, 75
I've imported and indexed the data as follows:
df = pd.read_csv('mycsv.csv')
df.index = pd.to_datetime(full_set.pop('dt'))
What I want is a count of unique srcIPs which visit my servers per time period
(I have data over several days and I'd like time period by date,hour). I can
obtain an overall traffic graph by grouping and plotting as follows:
df.groupby([lambda t: t.date(), lambda t: t.hour]).srcIP.nunique().plot()
However, I want to know how that overall traffic is split amongst my servers.
My intuition was to additionally group by the 'dstIP' column (which only has 5
unique values), but I get errors when I try to aggregate on srcIP.
grouped = df.groupby([lambda t: t.date(), lambda t: t.hour, 'dstIP'])
grouped.sip.nunique()
...
Exception: Reindexing only valid with uniquely valued Index objects
So, my specific question is: How can I avoid this exception in order to create
a plot where traffic is aggregated over 1 hour blocks and there is a different
series for each server.
More generally, please let me know what newb errors I'm making. Also, the data
does not have regular frequency timestamps and I don't want sampled data in
case that makes any difference in your answer.
**EDIT 1** This is my ipython session exactly as input. output ommitted except
for the deepest few calls in the error.
**EDIT 2** Upgrading pandas from 0.8.0 to 0.12.0 as yielded a more descriptive
exception shown below
import numpy as np
import pandas as pd
import time
import datetime
full_set = pd.read_csv('june.csv', parse_dates=True, index_col=0)
full_set.sort_index(inplace=True)
gp = full_set.groupby(lambda t: (t.date(), t.hour, full_set['dip'][t]))
gp['sip'].nunique()
...
/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.pyc in _make_labels(self)
1239 raise Exception('Should not call this method grouping by level')
1240 else:
-> 1241 labs, uniques = algos.factorize(self.grouper, sort=self.sort)
1242 uniques = Index(uniques, name=self.name)
1243 self._labels = labs
/usr/local/lib/python2.7/dist-packages/pandas/core/algorithms.pyc in factorize(values, sort, order, na_sentinel)
123 table = hash_klass(len(vals))
124 uniques = vec_klass()
--> 125 labels = table.get_labels(vals, uniques, 0, na_sentinel)
126
127 labels = com._ensure_platform_int(labels)
/usr/local/lib/python2.7/dist-packages/pandas/hashtable.so in pandas.hashtable.PyObjectHashTable.get_labels (pandas/hashtable.c:12229)()
/usr/local/lib/python2.7/dist-packages/pandas/core/generic.pyc in __hash__(self)
52 def __hash__(self):
53 raise TypeError('{0!r} objects are mutable, thus they cannot be'
---> 54 ' hashed'.format(self.__class__.__name__))
55
56 def __unicode__(self):
TypeError: 'TimeSeries' objects are mutable, thus they cannot be hashed
Answer: So I'm not 100 percent sure why that exception was raised.. but a few
suggestions:
You can read in your data and parse the datetime and index by the datetime all
at once with `read_csv`:
df = pd.read_csv('mycsv.csv', parse_dates=True, index_col=0)
Then you can form your groups by using a lambda function that returns a tuple
of values:
gp = df.groupby( lambda t: ( t.date(), t.hour, df['dstIP'][t] ) )
The input to this lambda function is the index, we can use this index to go
into the dataframe in the outer scope and retrieve the `srcIP` value at that
index and thus factor it into the grouping.
Now that we have the grouping, we can apply the aggregator:
gp['srcIP'].nunique()
|
Logging ping results python?
Question: I can use the ping command and save the output using the following line:
command = os.system('ping 127.0.0.1 > new.txt')
However each time the script is run the text file is overwritten so I only
have the last ping saved. I have looked into logging but cannot find a way to
save the outputs of the ping requests into a text file without over writing.
I have tried:
logging.debug(command = os.system('ping 127.0.0.1'))
But this throws up an error with: debug() takes at least 1 argument (0 given)
Any help would be appreciated, thanks!
Answer: You could get result of subprocess.check_output and write it to a file:
import subprocess
result = subprocess.check_output(['ping', '127.0.0.1'])
with open("new.txt", "a") as myfile:
myfile.write(result)
|
terminal: open editor by click on stacktrace line
Question: I want python stacktrace lines to act like hyperlinks in a terminal. My
favorite editor should open the file and go to the correct line:
Traceback (most recent call last):
File "/home/foo_eins_dt/djangotools/utils/smtputils.py", line 73, in _inner_to_outbox
return func(*args, **kwargs)
File "/home/foo_eins_dt/foo_mail/tests/EditTest.py", line 289, in test_something
beleg_ids=importutils.import_msg_file(temp)
TypeError: bar() takes exactly 2 arguments (1 given)
Up to now I use gnome-terminal, but I could switch to a different terminal.
Example: I want to click on `File
"/home/foo_eins_dt/foo_mail/tests/EditTest.py"` and the file EditTest.py
should be opened at line 289.
Answer: For the internet future: This is possible in OS X in [iTerm
2](https://iterm2.com/index.html)
Here is my setup with Sublime Text: `~/bin/magic-iterm-open.py`
#!/usr/bin/python
import sys
from subprocess import call
if len(sys.argv) > 2:
pathToSubl = "/Users/rainer/bin/"
filename, linenum = sys.argv[1], sys.argv[2]
rest = "" if len(sys.argv) < 4 else sys.argv[3]
if not filename.endswith('.py'):
# I believe this approximates iTerm's default
call(['/usr/bin/open', filename])
else:
newLinenum = linenum
if not str.isdigit(linenum):
line = linenum.split(",")
if len(line) > 1:
newLinenum = filter(str.isdigit, line[1])
command = ["{0}subl".format(pathToSubl),
"--add", # If you'd like to add to your current sublime project
"{0}:{1}".format(filename, newLinenum)]
call(command)
And the config in iTerm2:
[](http://i.stack.imgur.com/Ymso8.gif)
All credit goes to an old redit post, here:
<https://www.reddit.com/r/SublimeText/comments/1kanze/iterm2_jump_to_location_in_sublime_text_23/>
|
WTForm not displayed, got python code instead
Question: I’m making a form for flask using WTForms. Here is the corresponding code :
class UploadForm(flask.ext.wtf.Form):
def __init__(self,year):
flask.ext.wtf.Form.__init__(self)
self.year=year
subjects = app.config["SUBJECTS"][year]
self.fichier = wtforms.fields.FileField(u'Fichier')
self.subject = wtforms.fields.SelectField(u'Matière', choices=subjects)
self.submit = wtforms.fields.SubmitField(u'Envoyer')
@app.route('/upload/<year>')
def upload(year):
print year
form = UploadForm(year)
return flask.render_template('upload.html', form=form)
And here is the template `upload.html` :
{% extends "base.html" %}
{% block content %}
<h2>Upload</h2>
<form action="{{ url_for('get', year='1A') }}" method="post"
enctype="multipart/form-data">
{{ form.hidden_tag() }}
{{ form.fichier.label }}
{{ form.fichier }}
{{ form.subject.label }}
{{ form.subject }}
{{ form.submit }}
</form>
{% endblock %}
But when I run it, the form isn’t displayed, and instead I have this :
<UnboundField(FileField, (u'Fichier',), {})> <UnboundField(SelectField, (u'Mati\xe8re',), {'choices': [('MA111', 'MA111'), ('NE111', 'NE111')]})> <UnboundField(SubmitField, (u'Envoyer',), {})>
Can someone help me to fix it ?
Answer: Your issue is that you are creating the form without any fields and then
adding unbound fields behind its back in your `UploadForm.__init__` method.
The `wtforms.form.Form` class actually does a lot of metaclass magic behind
the scenes. The way to do what you are doing is as follows:
from flask import render_template
from flask.ext.wtf import Form
from wtforms.fields import FileField, SelectField, SubmitField
class UploadForm(Form):
"""This seemingly static class will be transformed
by the WTForms metaclass constructor"""
fichier = FileField(u'Fichier')
subject = SelectField(u'Matière')
submit = SubmitField(u'Envoyer')
@app.route('/upload/<year>')
def upload(year):
subjects = app.config['SUBJECTS'][year]
form = UploadForm()
# We can set the choices dynamically, based on year
form.subject.choices = subjects
return render_template('upload.html', form=form)
|
Cannot establish connection to sql-server using pyodbc on Windows 7
Question: I'm using ActivePython 2.7.2.5 on Windows 7.
While trying to connect to a sql-server database with the pyodbc module using
the below code, I receive the subsequent Traceback. Any ideas on what I'm
doing wrong?
CODE:
import pyodbc
driver = 'SQL Server'
server = '**server-name**'
db1 = 'CorpApps'
tcon = 'yes'
uname = 'jnichol3'
pword = '**my-password**'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes')
cursor = cnxn.cursor()
cursor.execute("select * from appaudit_q32013")
rows = cursor.fetchall()
for row in rows:
print row
TRACEBACK:
Traceback (most recent call last):
File "pyodbc_test.py", line 9, in <module>
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes')
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)')
Answer: You're using a connection string of `'DRIVER={SQL
Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes'`,
you're trying to connect to a server called `server`, a database called `db1`,
etc. It doesn't use the variables you set before, they're not used.
It's possible to pass the connection string parameters as keyword arguments to
the [`connect`](http://code.google.com/p/pyodbc/wiki/Module#connect) function,
so you could use:
cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1,
trusted_connection=tcon, user=uname, password=pword)
|
How can i let the BASH script run as process? So that even the Python script is killed the BASH script runs forever?
Question: I need to track and launch few BASH scripts as process (if they for some
reason crashed or etc). So i was trying as below: but not working
def ps(self, command):
process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.stdin.write(command + '\n')
process.stdout.readline()
ps("/var/tmp/KernelbootRun.sh")
ps("ps aux | grep processCreator.py | awk '{print $2}' | xargs kill -9")
None is working.
Answer: How about running it through a subshell with disown:
import os
def ps(self, command):
os.system(command + " & disown")
ps("/var/tmp/KernelbootRun.sh")
ps("ps aux | grep processCreator.py | awk '{print $2}' | xargs kill -9")
Note that sometimes you have to use a null input and output to keep your
process active when the terminal is closed:
ps("</dev/null /var/tmp/KernelbootRun.sh >/dev/null 2>&1")
ps("</dev/null ps aux | grep processCreator.py | awk '{print $2}' | xargs kill -9 >/dev/null 2>&1")
Or perhaps define another function:
def psn(self, command):
os.system("</dev/null " + command + " >/dev/null 2>&1 & disown")
psn("/var/tmp/KernelbootRun.sh")
psn("ps aux | grep processCreator.py | awk '{print $2}' | xargs kill -9")
|
ideas reseting stats in class
Question: Hi I made a simple program but when my monster dies the stats dont reset(hp
mainly) I am lost In how to make it reset every time the monsters hp reaches 0
and the xp is awarded. I know that I can wright the code over again and again
but I would like to be able to make it continue is as little amount of code as
possible. Im still learning python so I dont really know as much as everyone
else here. Ive gotten to classes but not so much in depth here is the code:
import random
def title():
print"hello Hero, welcome to staghold"
print"you have traveld along way, and you find yourself"
print"surrounded by and army of monsters as far as the eye can see"
print"begin to draw your sword.....you run full speed towards the army"
print"how many monsters can you kill before the inevatable comes?"
raw_input("(press enter to continue)")
def stats():
print"you have 200 health"
print"your level is 1"
print"you have 0 exp"
raw_input("(press enter to continue)")
class monster:
hp=50
monsterattack=random.randint
xp=random.randint(20,50)
health=200
level=1
exp=0
wave=1
title()
stats()
print"you run into a wave"
while level==1:
if monster.hp<=0:
print"you have defeated this wave of monsters"
wave+=1
exp+=monster.xp
print" you get, "+str(monster.xp)+" exp from the monster"
print"you now have, "+str(exp)+" exp"
if exp>=300:
level+=1
if level==2:
print"CONGRADULATIONS YOU HAVE REACHED LEVEL 2"
elif monster.hp>=0:
choice=raw_input("Will you 'fight' or 'run' from this horde?")
if choice=='fight':
print"you swing your sword at the monster"
att=random.randint(2, 13)
health-=monster.monsterattack(2,15)
monster.hp-=att
hp=200-health
print"you do, "+str(att)+" damage to the monster"
print"the monster does, "+str(hp)+" damage to you"
print"you have, "+str(health)+" health left"
print"the monster has, "+str(monster.hp)+" health left"
elif choice=="run":
print"you got away from this wave safely"
else:
print"NOT A VALID CHOICE"
Answer: I can see you're pretty early in your programming journey-
in your example, monster is a class. This means it is a definition of how an
object will behave. That is good- but you never define an example of a
monster. That would be something like
lion = monster()
which would create a new monster named lion. You need to set up a constructor
in the monster class that tells the program how to build a new monster, for
example
class Monster:
def __init__(self):
self.hp = 50
self.xp = random.randint(20,50)
def monsterattack(self):
return random.randint()
This would allow you to create a monster, and allow you to have that monster
attack with
damage = lion.monsterattack
You could then create a new lion, of class monster, during each loop - and
have your hero fight it. The lion would only exist within the current run
through of the loop, so each time you create a lion, it would be a completely
new monster.
I like your dedication- keep at it, read some basic tutorials!
|
error in dynamic bar chart generation on python
Question: Going by the this example,
<http://matplotlib.org/examples/pylab_examples/barchart_demo.html>
I wanted to generated the dynamic bar chart.so far I have following script.
import sys
import matplotlib.pyplot as plt
import numpy as np
groups = int(sys.argv[1])
subgroup = int(sys.argv[2])
fig, ax = plt.subplots()
index = np.arange(groups)
print index
bar_width = 1.0 / (subgroup + 1)
print bar_width
mainlist = []
for x in range(0, groups):
#print x
templist = []
for num in range(0, subgroup):
templist.append(num+1)
#print templist
mainlist.append(templist)
print mainlist
for cnt in range(0,subgroup):
plt.bar(index + (bar_width * cnt), mainlist[cnt], bar_width)
plt.savefig('odd_bar_chart.png')
This works fine when i pass same values for groups and subgroup,
> odd_bar_chart.py 3 3
> odd_bar_chart.py 2 2
but if i pass different values like this,
> odd_bar_chart.py 3 2 odd_bar_chart.py 2 3
it gives following error AssertionError: incompatible sizes: argument 'height'
must be length {first argument} or scalar
Now I dont know hw height comes in picture ? can anybody tell me whats wrong
here ?
Answer: Take a look at the [docs for
`plt.bar`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar).
Here the first two arguments are `left` and `height` referring the value of
the left hand side of the bar and it's height.
Your error message is informing you that the second argument, `height` should
be either the same length as the first or a scalar (single value).
**The error** : In your iteration at the end you plot the height
`mainlist[cnt]` against the left locations `index + (bar_width * cnt)`.
Clearly you are trying to adjust the `x` location to spatially separate the
bar plots using the `bar_with*cnt` so this is a scalar. The length then of the
`left` is given by `index`, which is generated from `index =
np.arange(groups)` and so will have length `group`. But the length of the
heights is given by `subgroup`, this is done when `templist` (which has length
`subgroup`) is appended to `mainlist`.
So your error comes in the way you are generating your data. It is usually
better to either stick something in by hand (as they have done in the example
you referenced), or use [something form
`numpy.random`](http://docs.scipy.org/doc/numpy/reference/routines.random.html)
to generate a set of random numbers.
|
Python PIL cut off my 16-bit grayscale image at 8-bit
Question: I'm working on an python program to display images of stars. The images are
16-bit grayscale tiffs. If I try to display them in an extern program, e.g.
ImageMagick they are correct but if I load them in python and then use
'show()' or implement them in a canvas in Tkinter they are, unless a few
pixel, totally white. So I estimate python sets every pixel above 255 to white
but I don't know why. If I load the image and then save it as tiff again,
ImageMagick can show it correct. Thanks for help.
Answer: Try to convert the image to a numpy array and display that:
import Image
import matplotlib.pyplot as plt
import numpy as np
img = Image.open('image.tiff')
arr = np.asarray(img.getdata()).reshape(img.size[1], img.size[0])
plt.imshow(arr)
plt.show()
You can change the color mapping too:
from matplotlib import cm
plt.imshow(arr, cmap=cm.gray)
|
AttributeError: '_pjsua.Transport_Config' object has no attribute '_cvt_to_pjsua'
Question: I'm currently trying to use the `pjsip` api `pjsua` in python and therefor
studying this Hello World example:
<http://trac.pjsip.org/repos/wiki/Python_SIP/Hello_World>
I copied the code over, integrated account configuration according to
<http://trac.pjsip.org/repos/wiki/Python_SIP/Accounts> etc. But when I run the
sample, I get the following output:
Traceback (most recent call last):
File "/home/dmeli/workspace/eit.cubiephone.sip_test/eit/cubiephone/sip_test/hello.py", line 48, in <module>
acc = lib.create_account(acc_cfg)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 2300, in create_account
err, acc_id = _pjsua.acc_add(acc_config._cvt_to_pjsua(), set_default)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 900, in _cvt_to_pjsua
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
AttributeError: '_pjsua.Transport_Config' object has no attribute '_cvt_to_pjsua'
Because I'm not really a python expert and never worked with PJSIP before, I
can't really figure out the error. Too me, it looks like it's actually an
error in the `pjsip` python wrapper. But what do I know?
Code:
lib = pj.Lib()
lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))
transport = lib.create_transport(pj.TransportType.UDP)
lib.start()
acc_cfg = pj.AccountConfig("XXXXX", "XXXXXX", "XXXXXX")
acc_cfg.id = "sip:XXXXXXX@XXXXXXXX"
acc_cfg.reg_uri = "sip:XXXXXXXXX"
acc_cfg.proxy = [ "sip:XXXXXXXXX;lr" ]
acc = lib.create_account(acc_cfg)
# Make call
call = acc.make_call("XXXXXXXXXXX", MyCallCallback())
Line where the error happens in pjsua.py:
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
(`rtp_transport_cfg` doesn't seem to have a member `_cvt_to_pjsua()`??)
Answer: **For further work correctly, look at the PJSIP api (pjsua.py) that he is
waiting for the order and structure!!!**
## start lib.
def start(self):
try:
self._start_lib()
self._start_acc()
except pj.Error:
print "Error starting lib."
def _bind(self):
try:
t = pj.TransportConfig()
t.bound_addr = '0.0.0.0'
t.port = 5060
acc_transport = "udp" # depend if you need.
if acc_transport == "tcp":
self.transport = self.lib.create_transport(pj.TransportType.TCP, t)
# or this pj.TransportConfig(0) is creating random port ...
#self.transport = self.lib.create_transport(pj.TransportType.TCP, pj.TransportConfig(0))
else:
self.transport = self.lib.create_transport(pj.TransportType.UDP, t)
#self.transport = self.lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0))
except pj.Error:
print "Error creating transport."
#you need create callbacks for app, to work incoming calls, check on the server that returns the error code 200, and such a way your program will know that you are logged on correctly
#from callback.acc_cb import acc_cb
#self.acc_t = self.lib.create_account_for_transport(self.transport, cb=acc_cb())
def _start_lib(self):
self.lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))
self.lib.start()
self._bind()
#codecs.load_codecs()
def _start_acc(self):
#from callback.acc_cb import acc_cb
try:
proxy = "sip server ip" # or proxy = socket.gethostbyname(unicode("sip.serverdnsname.com")) is needed to import socket
login = "Atrotygma" # real username
password = "Atrotygma_password" # real username
lib.create_account(acc_config=pj.AccountConfig(proxy, login, password))
except Exception, e:
print "Error creating account", e
|
Redis mass insertion do not work
Question: Problem as simple as I want to do mass insertion in redis using a file and
redis-cli in pipe mode. Redis documentation explains this here:
<http://redis.io/topics/mass-insert>
My file contains only this command:
HMSET client:1 name "Michael"
When I try it in my shell (Ubuntu Linux):
cat data.txt | redis-cli --pipe
I get this error:
ERR unknown command '$4'
ERR wrong number of arguments for 'echo' command
ERR unknown command '$20'
I've seen that other users have same problem ([How to use Redis mass
insertion?](http://stackoverflow.com/questions/13195341/how-to-use-redis-mass-
insertion)) but I haven't found a good solution.
Any help would be appreciated.
**UPDATE: SOLUTION**
Finally the best option for me was to use a redis client developed in Python.
This is a pretty straight forward solution, and the point is that we don't
need to use/code redis protocol directly.
I choose redis-py client (<https://github.com/andymccurdy/redis-py>). After
installing it you can import its functionality in your python script. This is
an example of how my script does the job:
import redis
# Connection to 0 database (default in redis)
r = redis.Redis(host="localhost",db=0)
# inserting client hashmaps
r.hmset('client:1', {'name':'John', 'company':'Microsoft'})
r.hmset('client:2', {'name':'James', 'company':'Apple'})
# inserting a list of domains for client 1
r.rpush('client:1:domains','www.microsoft.com','www.msn.com')
#to print values in stdout
print(r.hgetall('client:1'))
Answer: Your input file is supposed to contain Redis protocol, not text commands.
See an example here: [Redis Mass
Insertion](http://stackoverflow.com/questions/18870623/redis-mass-
insertion/18872283#18872283)
Redis protocol is described here: <http://redis.io/topics/protocol>
|
How to show a text from wx module?
Question: Yesterday found out that my router can be controlled by telnet, and today I
was looking for some qt4,pygtk or wx to store all the router telnet commands
in a gui. Less than 15 minutes ago I found this website -
zetcode(dot)com/wxpython/advanced/ , which got the right information that I
need. Unfortunatelly I don't understand how to include text in wx modules,
because I am using it for a first time. Can you tell me how to assign text to
the left window, because once I start the module it shows me a grey screen
with a buttons in it's menu. The grey area that is the most left must contain
around 10 telnet commands, where the "help" contains all of the commands saved
in a html file.
import wx
import wx.html as html
class HelpWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(570, 400))
toolbar = self.CreateToolBar()
toolbar.AddLabelTool(1, 'Exit', wx.Bitmap('icons/exit.png'))
toolbar.AddLabelTool(2, 'Help', wx.Bitmap('icons/help.png'))
toolbar.Realize()
self.splitter = wx.SplitterWindow(self, -1)
self.panelLeft = wx.Panel(self.splitter, -1, style=wx.BORDER_SUNKEN)
self.panelRight = wx.Panel(self.splitter, -1)
vbox2 = wx.BoxSizer(wx.VERTICAL)
header = wx.Panel(self.panelRight, -1, size=(-1, 20))
header.SetBackgroundColour('#6f6a59')
header.SetForegroundColour('WHITE')
hbox = wx.BoxSizer(wx.HORIZONTAL)
st = wx.StaticText(header, -1, 'Help', (5, 5))
font = st.GetFont()
font.SetPointSize(9)
st.SetFont(font)
hbox.Add(st, 1, wx.TOP | wx.BOTTOM | wx.LEFT, 5)
close = wx.BitmapButton(header, -1, wx.Bitmap('icons/fileclose.png', wx.BITMAP_TYPE_PNG),
style=wx.NO_BORDER)
close.SetBackgroundColour('#6f6a59')
hbox.Add(close, 0)
header.SetSizer(hbox)
vbox2.Add(header, 0, wx.EXPAND)
help = html.HtmlWindow(self.panelRight, -1, style=wx.NO_BORDER)
help.LoadPage('wx.html')
vbox2.Add(help, 1, wx.EXPAND)
self.panelRight.SetSizer(vbox2)
self.panelLeft.SetFocus()
self.splitter.SplitVertically(self.panelLeft, self.panelRight)
self.splitter.Unsplit()
self.Bind(wx.EVT_BUTTON, self.CloseHelp, id=close.GetId())
self.Bind(wx.EVT_TOOL, self.OnClose, id=1)
self.Bind(wx.EVT_TOOL, self.OnHelp, id=2)
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
self.CreateStatusBar()
self.Centre()
self.Show(True)
def OnClose(self, event):
self.Close()
def OnHelp(self, event):
self.splitter.SplitVertically(self.panelLeft, self.panelRight)
self.panelLeft.SetFocus()
def CloseHelp(self, event):
self.splitter.Unsplit()
self.panelLeft.SetFocus()
def OnKeyPressed(self, event):
keycode = event.GetKeyCode()
if keycode == wx.WXK_F1:
self.splitter.SplitVertically(self.panelLeft, self.panelRight)
self.panelLeft.SetFocus()
app = wx.App()
HelpWindow(None, -1, 'HelpWindow')
app.MainLoop()
Answer: Found it...
wx.StaticText(self.panelLeft, -1, 'thetextgoeshere', (15, 5))
|
Comparing two numpy arrays of different length
Question: I need to find the indices of the first less than or equal occurrence of
elements of one array in another array. One way that works is this:
import numpy
a = numpy.array([10,7,2,0])
b = numpy.array([10,9,8,7,6,5,4,3,2,1])
indices = [numpy.where(a<=x)[0][0] for x in b]
_indices_ has the value [0, 1, 1, 1, 2, 2, 2, 2, 2, 3], which is what I need.
The problem of course, is that python "for" loop is slow and my arrays might
have millions of elements. Is there any numpy trick for this? This doesn't
work because they arrays are not of the same length:
indices = numpy.where(a<=b) #XXX: raises an exception
Thanks!
Answer: This may be a special case, but you should be able to use numpy
[digitize](http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html).
The caveat here is the bins must be monotonically decreasing or increasing.
>>> import numpy
>>> a = numpy.array([10,7,2,0])
>>> b = numpy.array([10,9,8,7,6,5,4,3,2,1])
>>> indices = [numpy.where(a<=x)[0][0] for x in b]
[0, 1, 1, 1, 2, 2, 2, 2, 2, 3]
>>> numpy.digitize(b,a)
array([0, 1, 1, 1, 2, 2, 2, 2, 2, 3])
* * *
Setup for the timing test:
a = np.arange(50)[::-1]
b = np.random.randint(0,50,1E3)
np.allclose([np.where(a<=x)[0][0] for x in b],np.digitize(b,a))
Out[55]: True
Some timings:
%timeit [np.where(a<=x)[0][0] for x in b]
100 loops, best of 3: 4.97 ms per loop
%timeit np.digitize(b,a)
10000 loops, best of 3: 48.1 µs per loop
Looks like two orders of magnitude speed up, this will depend heavily on the
number of bins however. Your timings will vary.
* * *
To compare to Jamie's answer I have timed the two following pieces of code. As
I mainly wanted to focus on the speed of `searchsorted` vs `digitize` I pared
down Jamie's code a bit. The relevant chunk is here:
a = np.arange(size_a)[::-1]
b = np.random.randint(0, size_a, size_b)
ja = np.take(a, np.searchsorted(a, b, side='right', sorter=a)-1)
#Compare to digitize
if ~np.allclose(ja,np.digitize(b,a)):
print 'Comparison failed'
timing_digitize[num_a,num_b] = timeit.timeit('np.digitize(b,a)',
'import numpy as np; from __main__ import a, b',
number=3)
timing_searchsorted[num_a,num_b] = timeit.timeit('np.take(a, np.searchsorted(a, b, side="right", sorter=a)-1)',
'import numpy as np; from __main__ import a, b',
number=3)
This is a bit beyond my limited matplotlib ability so this is done in
DataGraph. I have plotted the logarithmic ratio of
`timing_digitize/timing_searchsorted` so values greater then zero
`searchsorted` is faster and values less then zero `digitize` is faster. The
colors also give relative speeds. For example is shows that in the top right
(a = 1E6, b=1E6) `digitize` is ~300 times slower then `searchsorted` while for
smaller sizes `digitize` can be up to 10x faster. The black line is roughly
the break even point:
 Looks like
for raw speed `searchsorted` is almost always faster for large cases, but the
simple syntax of `digitize` is nearly as good if the number of bins is small.
|
neo4django mixin inheritance problems
Question: Considering [my previous
question](http://stackoverflow.com/questions/18849973/neo4django-multiple-
inheritance), I try to implement what I need.
The following is the content of a django app models.py.
from neo4django.db import models
from neo4django.auth.models import User as AuthUser
class MyManager(models.manager.NodeModelManager):
def filterLocation(self,**kwargs):
qs = self.get_query_set()
if 'dist' in kwargs:
qs = qs.filter(_where_dist=kwargs['dist'])
elif 'prov' in kwargs:
qs = qs.filter(_where_prov=kwargs['prov'])
elif 'reg' in kwargs:
qs = qs.filter(_where_reg=kwargs['reg'])
return qs
class MyMixin(object):
_test = models.BooleanProperty(default=True)
_where_dist = models.StringProperty(indexed=True)
_where_prov = models.StringProperty(indexed=True)
_where_reg = models.StringProperty(indexed=True)
search = MyManager()
class Meta:
abstract = True
class Activity(MyMixin,models.NodeModel):
name = models.StringProperty()
class User(MyMixin,AuthUser):
info = models.StringProperty()
I have many problems. The first is the non-inheritance of MyMixin's
attributes:
>>> joe=User.objects.create(username='joe') # OK!
>>> joe
<User: joe>
>>> bill=User.objects.create(username='bill',_test=True)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/neo4django/db/models/manager.py", line 43, in create
return self.get_query_set().create(**kwargs)
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/neo4django/db/models/query.py", line 1296, in create
return super(NodeQuerySet, self).create(**kwargs)
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/django/db/models/query.py", line 375, in create
obj = self.model(**kwargs)
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/neo4django/db/models/base.py", line 141, in __init__
super(NodeModel, self).__init__(*args, **kwargs)
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/django/db/models/base.py", line 367, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
TypeError: '_test' is an invalid keyword argument for this function
But also the create fails to set User's own attributes!
>>> k=User.objects.create(username='kevin',info='The Best')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/neo4django/db/models/manager.py", line 43, in create
return self.get_query_set().create(**kwargs)
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/neo4django/db/models/query.py", line 1296, in create
return super(NodeQuerySet, self).create(**kwargs)
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/django/db/models/query.py", line 375, in create
obj = self.model(**kwargs)
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/neo4django/db/models/base.py", line 141, in __init__
super(NodeModel, self).__init__(*args, **kwargs)
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/django/db/models/base.py", line 367, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
TypeError: 'info' is an invalid keyword argument for this function
None of the mixin or User class own attributes exist in User. If I derived in
reverse order:
class User(AuthUser,MyMixin):
Here they are present, but I don't think is a good practice, should not core
models go to the right? Anyway, as we see below, Activity does not have this
problem,
like if AuthUser removed all attributes (intended behavior?).
While the alternative creation method works:
>>> k=User(username='kevin',info='The Best')
>>> k.save()
>>> k
<User: kevin>
But using the other Model, Activity, which inherits directly from
NodeModelManager
(with User we have an intermediate parent AuthUser), things are better:
>>> a=Activity.objects.create(name="AA")
>>> a
<Activity: Activity object>
Several tests made with a simple NodeModel inheritance were ok, the problems
arise with multiple inheritance and mixins.
Another problem, with my NodeModelManager:
>>> User.search.filterLocation(dist="b")
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/tonjo/prj/tuned_prj/tuned_django/myapp/models.py", line 6, in filterLocation
qs = self.get_query_set()
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/neo4django/db/models/manager.py", line 31, in get_query_
set
return NodeQuerySet(self.model)
File "/home/tonjo/venv/tuned/local/lib/python2.7/site-packages/neo4django/db/models/query.py", line 1222, in __init__
self._app_label = model._meta.app_label
AttributeError: 'NoneType' object has no attribute '_meta'
This one is beyond my comprehension ;) MyManager worked well when in a
previous test I derived from a NodeModel's child, not from a mixin.
Answer: This is a pretty complicated question, but hopefully I can give you a pointer.
First- you need to understand that Django fields (and by extension neo4django
properties) cooperate with the class on which they're defined. That's why they
_only_ work when defined on a `Model` (or, in neo4django, a `NodeModel`).
There is no easy way to do multiple inheritance using Django models and
fields- my mixin suggestion from [your other
question](http://stackoverflow.com/questions/18849973/neo4django-multiple-
inheritance/) allows adding Python methods and attributes, but won't magically
make `Property` or `Field` play nicely with `object` as a parent class.
If you really want to avoid duplication of property definitions in this
situation, you have a few choices.
One is to use a shared super class- but in this case, you can't, since you
need to inherit from `neo4django.auth.models.User` with one of your classes.
This particular requirement will when neo4django supports Django 1.5+, which
allows swappable user models.
Most metaprogramming won't work easily, since Django and neo4django make use
of metaclasses. That said, I'm sure you could hack around this with a clever
class decorator or child metaclass- but I'm not sure you should from a sanity
standpoint :)
Let me know how it goes- maybe I'm missing an easier approach.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.