text
stringlengths 226
34.5k
|
---|
Relative import correction without sys or os
Question: I've read almost all of the solutions for fixing relative imports and none of
them seem to work. Here's my current structure:
structures
\ containers
\ queue.py
\ trees
\ binaryTree.py
I want to import the queue in to my binary tree file but I'm getting slammed
with relative import issue. I tried `__init__.py` but that doesn't seem to
solve the relative import issue. Is there a solution to this? (I'm on Python
3.3.x)
Edit:
This is my import statement
from .containers.queue import Queue
and the error:
Traceback (most recent call last):
File "binaryTree.py", line 1, in <module>
from .containers.queue import Queue
SystemError: Parent module '' not loaded, cannot perform relative import
Answer:
from ..containers.queue import Queue
|
Calling a function in a class of another program - Python
Question: As the title says, how do you call a function in a class of another program?
Class.py
class Object:
def __init__(self, mood):
self.__mood = mood
def set_mood(self, mood):
self.__mood = mood
def check_mood(self):
if random.randint(1, 3) == 1:
self.__mood = 'happy'
elif random.randint(1, 3) == 2:
self.__mood = 'hungry'
elif random.randint(1, 3) == 3:
self.__mood = 'sleepy'
def get_mood(self):
return self.__mood
Generator.py
from test import Object
import test
mood = 'happy'
ani = Object.test(mood)
print("This is your mood: " + get_mood())
Mood is set as a default value of "happy". I need that to change based on the
random integer roll in test so that when mood is displayed, it isn't always
displayed as "happy"
Answer: You have to **_explicitly_** call `check_mood` to change the object's
attribute. See code below.
from random import randint
class Foo(object):
def __init__(self, mood):
self.__mood = mood
self.__selection = {
1:'happy',
2:'hungry',
3:'sleepy',
4:'angry',
5:'bored'
}
def check_mood(self):
m = randint(1,5)
self.__mood = self.__selection[m]
def get_mood(self):
return self.__mood
mood = 'happy'
f = Foo(mood)
print 'This is your previous mood:', f.get_mood()
f.check_mood() # This rerolls the mood.
print 'This is your current mood:', f.get_mood()
# This is your previous mood: happy
# This is your current mood: bored
Otherwise, if you want it to change "behind-the-scenes", I suggest calling
`check_mood` _inside_ `get_mood` (or just get rid of `check_mood` entirely and
put its code inside `get_mood`).
However, the way `get_mood` is defined makes it modify the original
`self.__mood`, rendering the original passed-in argument as lost once you call
`get_mood`.
|
Scrapy Flight Search
Question: I'm trying to use Scrapy in Python to run a flight search on some flights and
then export it to a csv. This is just for fun as I learn more about Scrapy.
Here is what I have
from scrapy.item import Item, Field
from scrapy.http import FormRequest
from scrapy.spider import Spider
class DeltaItem(Item):
title = Field()
link = Field()
desc = Field()
class DmozSpider(Spider):
name = "delta"
allowed_domains = ["delta.com"]
start_urls = ["http://www.delta.com"]
def parse(self, response):
yield FormRequest.from_response(response,
formname='flightSearchForm',
formdata={'departureCity[0]': 'JFK',
'destinationCity[0]': 'SFO',
'departureDate[0]': '07.20.2013',
'departureDate[1]': '07.28.2013'},
callback=self.parse1)
def parse1(self, response):
print response.status
When I run it it returns blank.
Thanks
Answer: Tested in my spider and give me the log
> 2015-04-17 11:29:28+0800 [delta] DEBUG: Crawled (200) http://www.delta.com>
> (referer: None)
> 2015-04-17 11:29:28+0800 [delta] DEBUG: Crawled (200)
> http://www.delta.com/air-shopping/findFlights.action> (referer:
> <http://www.delta.com>)
> 200 #**This is the print of parse1**
> 2015-04-17 11:29:28+0800 [delta] INFO: Closing spider (finished)
|
Code not returning response to command
Question: Quick question: I'm using the Speech Python Module for voice recognition.
Here's the code I have so far,
import speech
import time
def callback(phrase, listener):
if listener == "hello":
print "Hello sir."
listener.stoplistening()
listener = speech.listenforanything(callback)
while listener.islistening():
time.sleep(.5)
But it never prints "Hello sir." I'm wondering if I'm doing something wrong.
I've looked online, but there's not much documentation. Can anyone help?
Ps: I'm using a Windows 8 laptop 64-bit and Python 2.7.
Answer: Try this:
import speech
import time
def callback(phrase, listener):
# I have used phrase is here
if phrase == "hello":
print "Hello sir."
listener.stoplistening()
listener = speech.listenforanything(callback)
while listener.islistening():
time.sleep(.5)
|
Restarting a thread in Python
Question: I'm trying to make threaded flight software for a project in Python 3.4, in
which I need threads to restart themselves in case an I/O error occurs during
a sensor read or another fluke crash like that. Therefore I am working on
making a watchdog to check if threads have died and restarting them.
At first I attempted to just check if the thread was no longer alive and
restart it, which did this:
>>> if not a_thread.isAlive():
... a_thread.start()
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "c:\Python34\lib\threading.py", line 847, in start
raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
This behaviour makes sense from the standpoint of `threading`and Python
itself, but makes my job harder. So I implemented a solution using a
dictionary to store the initial thread and copy it to a new object and start
it when necessary. Unfortunately this doesn't work either. Here's a basic
example:
import threading
import logging
import queue
import time
from copy import copy, deepcopy
def a():
print("I'm thread a")
def b():
print("I'm thread b")
# Create thread objects
thread_dict = {
'a': threading.Thread(target=a, name='a'),
'b': threading.Thread(target=b, name='b')
}
threads = [copy(t) for t in thread_dict.values()]
for t in threads:
t.start()
for i in range(len(threads)):
if not threads[i].isAlive():
temp = thread_dict[threads[i].name]
threads[i] = deepcopy(temp)
threads[i].start()
thread(i).join(5)
which returns:
I'm thread a
I'm thread b
Traceback (most recent call last):
File "main_test.py", line 25, in <module>
threads[i] = deepcopy(temp)
File "c:\Python34\lib\copy.py", line 182, in deepcopy
y = _reconstruct(x, rv, 1, memo)
... (there's about 20 lines of traceback within copy)
File "c:\Python34\lib\copyreg.py", line 88, in __newobj__
return cls.__new__(cls, *args)
TypeError: object.__new__(_thread.lock) is not safe, use _thread.lock.__new__()
So apparently `threading` objects are not safe to copy... Is there anyway to
restart threads short of recreating the entire object?
Answer: 1. There's no reason to let your threads die.
If they're actually crashing, your whole program will crash.
If they're just raising exceptions, you can just catch the exceptions.
If they're returning normally, you can just not do that.
You can even trivially wrap a thread function to restart itself on exception
or return:
def threadwrap(threadfunc):
def wrapper():
while True:
try:
threadfunc()
except BaseException as e:
print('{!r}; restarting thread'.format(e))
else:
print('exited normally, bad thread; restarting')
return wrapper
thread_dict = {
'a': threading.Thread(target=wrapper(a), name='a'),
'b': threading.Thread(target=wrapper(b), name='b')
}
Problem solved.
* * *
2. You cannot restart a thread.
Most platforms have no way to do so.
And conceptually, it doesn't make any sense. When a thread finished, its stack
is dead; its parent is flagged or signaled; once it's joined, its resources
are destroyed (including kernel-level resources like its process table entry).
The only way to restart it would be to create a whole new set of everything.
Which you can already do by creating a new thread.
So, just do it. If you really don't want to handle the exceptions internally,
just store the construction arguments and use them to start a new thread.
You can even create your own subclass that hangs onto them for you:
class RestartableThread(threading.Thread):
def __init__(self, *args, **kwargs):
self._args, self._kwargs = args, kwargs
super().__init__(*args, **kwargs)
def clone(self):
return RestartableThread(*args, **kwargs)
And now it's easy to "copy" the thread (with the semantics you wanted):
if not a_thread.is_alive():
a_thread = a_thread.clone()
* * *
3. Yes, `threading.Thread` objects are not safe to copy
What would you expect to happen? At best, you'd get a different wrapper around
the same OS-level thread object, so you'd fool Python into not noticing that
you're trying to do the illegal, possibly segfault-inducing things it was
trying to stop you from doing.
|
Histogram with independent line matplotlib
Question: Working with matplotlib (1.3.1-2), python 2.7.
I create a a stacked histogram with timely distribution on the x-Axis the
following:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
#the dates for plotting (numpy array)
date1 = [735133.84893519 734066.13166667 732502.86928241 732502.81313657 732502.81313657 735133.85021991 735133.85019676 733935.8158912 733935.81766204 733361.04634259 733361.04921296 733361.05106481 733935.81671296 734010.75708333 734772.85976852 734010.75684028]
date2 = [732582.51802083 732582.51796296 734893.73981481 735629.50372685 735629.50369213 732874.66700231 734663.6618287 734687.42241898 734687.4216088 734687.42064815 733616.43398148 734663.67599537 734600.71085648 734598.31212963 734598.31207176 734600.71082176 734598.31199074 735044.42799769 734643.24407407 734617.59635417]
date3 = [734372.11476852 734372.11424769 734359.19949074 734359.19871528 734359.19790509 734359.19711806 734359.19630787 734359.19534722 734359.19452546 734359.19372685 734359.1921412 734359.14888889 734359.14819444 734359.1475 734359.14677083 734359.14599537]
#plot it
fig, ax = plt.subplots(1,1)
ax.hist([date2, date2, date3], bins = 200, stacked = True, normed = True, edgecolor = 'None', linewidth = 0, color = ("#007d13", "#2eb1f3", "#aaa1ff"))
plt.legend(["date1", "date2", "date3"])
ax.autoscale(enable = True, axis = "x", tight = True)
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y'))
plt.tick_params(axis = "both", which = "both", direction = 'out' )
plt.xticks(rotation = 50)
plt.grid()
plt.show()
What I need now is a line in there. That line will be defined by a date and a
value.
#numpy array
point1 = [734598.31212963 66352]
point2 = [732582.51802083 551422]
point3 = [735133.84893519 77162]
As you can see, the value of these dates will be way higher than the
cumulative ones from my dates. Thus, I will need second different scaled
y-Axis as well.
Any suggestions?
Answer: you can perfectly have 2 different scale in matplotlib. See documentation
here:
<http://matplotlib.org/examples/api/two_scales.html>
complete code here :
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
#the dates for plotting (numpy array)
date1 = [735133.84893519,734066.13166667,732502.86928241,732502.81313657,732502.81313657,735133.85021991,735133.85019676,733935.8158912,733935.81766204,733361.04634259,733361.04921296,733361.05106481,733935.81671296,734010.75708333,734772.85976852,734010.75684028]
date2 = [732582.51802083,732582.51796296,734893.73981481,735629.50372685,735629.50369213,732874.66700231,734663.6618287, 734687.42241898,734687.4216088, 734687.42064815,733616.43398148,734663.67599537,734600.71085648,734598.31212963,734598.31207176,734600.71082176,734598.31199074,735044.42799769,734643.24407407,734617.59635417]
date3 = [734372.11476852,734372.11424769,734359.19949074,734359.19871528,734359.19790509,734359.19711806,734359.19630787,734359.19534722,734359.19452546,734359.19372685,734359.1921412, 734359.14888889,734359.14819444,734359.1475,734359.14677083,734359.14599537]
#plot it
fig, ax = plt.subplots(1,1)
ax.hist([date2, date2, date3], bins = 200, stacked = True, normed = True, edgecolor = 'None', linewidth = 0, color = ("#007d13", "#2eb1f3", "#aaa1ff"))
plt.legend(["date1", "date2", "date3"])
ax.autoscale(enable = True, axis = "x", tight = True)
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y'))
plt.tick_params(axis = "both", which = "both", direction = 'out' )
plt.xticks(rotation = 50)
plt.grid()
# setting your values in a correct form
point1 = [734598.31212963,66352]
point2 = [732582.51802083,551422]
point3 = [735133.84893519,77162]
t=[point2[0],point1[0],point3[0]]
val=[point2[1],point1[1],point3[1]]
ax2 = ax.twinx()
ax2.plot(t, val, 'r')
ax2.set_ylabel('axe2', color='r')
for tl in ax2.get_yticklabels():
tl.set_color('r')
plt.show()
|
how to create dynamic configuration file using python
Question: I have a python script which is controlled by a config file called
**system.config** .the structure of config file is like bellow with some
default values.
[company]
companyname: XYZ
[profile]
name: ABC
joining: 1/1/2014
the code for config file is : **config_parser_details.py**
import ConfigParser
import sys
Config = ConfigParser.ConfigParser()
Config.read("system.config")
filename = "system.config"
def ConfigSectionMap(section):
dict1 = {}
options = Config.options(section)
for option in options:
try:
dict1[option] = Config.get(section, option)
if dict1[option] == -1:
DebugPrint("skip: %s" % option)
except:
print("exception on %s!" % option)
dict1[option] = None
return dict1
company = ConfigSectionMap("company")['companyname']
name = ConfigSectionMap("profile")['name']
joindate = ConfigSectionMap("profile")['joining']
now the code for my script is : **test.py**
import config_parser_details as p
import sys
import warnings
import os
company = p.company
name = p.name
date = p.joindate
print("%s\n" %company)
print("%s\n" %name)
output is
XYZ
ABC
now I want to give input in the config file through command line. like
python test.py --compname ="testing"
if any argument is missing in the command line than default value will be the
input.
Answer: You could use [argparse](https://docs.python.org/2/library/argparse.html)
library to parse command line arguments.
So your _test.py_ file looks like below :
import config_parser_details as p
import sys
import warnings
import os
import argparse
commandLineArgumentParser = argparse.ArgumentParser()
commandLineArgumentParser.add_argument("-c", "--compname", help="Company name", default=p.company)
commandLineArguments = commandLineArgumentParser.parse_args()
company = commandLineArguments.compname
name = p.name
date = p.joindate
print("%s\n" %company)
print("%s\n" %name)
|
How to always use the same instance of a class in Python?
Question: I am using the following solution to maintain a list of classes instances:
<http://stackoverflow.com/a/12102163>
Now I want to use that list to make sure that there is always only one
instance of the class. Renewed initializations of the class should return the
one existing instance.
The code I have is:
class MyClass:
instances = []
def __init__(self):
if not MyClass.instances:
self.data=1234
else:
self = MyClass.instances[0]
So:
>> a=MyClass()
>> a.data
1234
And b=MyClass() should return the same instance as a. This is not working.
What is wrong with my code?
**EDIT: OK, so it turns out I am looking for the singleton pattern, but
couldn't recreate it myself. Can anyone please explain why my code does not
work?**
Answer: Going on your code line and your style. You can make following modifications:-
class MyClass:
instance = None
def __init__(self):
self.data=1234
MyClass.instance = self
def get_myclass():
if MyClass.instance:
return MyClass.instance
return MyClass()
`get_myclass` would be a wrapper function for creating class objects. Trying
the code.
>>> import instance
>>> a=instance.get_myclass()
>>> b=instance.get_myclass()
>>> a is b
True
|
Python import vs direct execution
Question:
#conf.py
def init():
global mylist
mylist=[]
#change.py
import conf
def change():
if __name__ == "__main__":
print('Direct')
conf.mylist.append('Directly executed')
print(conf.mylist)
else:
conf.mylist.append('It was imported')
#exec.py
import conf
import change
conf.init()
change.change()
print (conf.mylist)
When running _exec.py_ the result is what I expected, **but** when running
_change.py_ directly I didn't get any output (no _Direct_ , no `conf.mylist`)
Answer: Yes, that's the normal behavior. You need to call the `change` function for
this code to execute.
You can add the following to the end of _change.py_
if __name__=="__main__":
change()
|
Python - Zipping a directory
Question: This code currently creates a zip file on the same destination the Python
script is executed, and attempts to populate the zip with the contents on
"Documents and Settings\Owner". However, it keeps trying to copy across
ntuser.dat and NTUSER.dat which gives me an error: `[Errno 13] Permission
denied: 'C:\\Documents and Settings\\Owner\\NTUSER.DAT'`
How can I skip those two files to allow the zip process to continue? I've
attempted to identify if a ntuser files is trying to be copied, and just pass
over the error, but has no effect.
import os, zipfile, getpass
try:
user= getpass.getuser()
zf = zipfile.ZipFile(user + ".zip", "w", zipfile.ZIP_DEFLATED)
directory = "C:\\Documents and Settings\Owner"
for dirname, subdirs, files in os.walk(directory):
zf.write(dirname)
for filename in files:
if "NTUSER" in filename:
pass
zf.write(os.path.join(dirname, filename))
except IOError as e:
print e
pass
zf.close()
Answer: Your code doesn't _do_ anything when you find a matching file:
for filename in files:
if "NTUSER" in filename:
pass
zf.write(os.path.join(dirname, filename))
`pass` is a _no operation_ statement. Python will just continue to the next
line, which writes the file to the ZIP.
If you wanted to skip those files, use `continue` instead:
for filename in files:
if "NTUSER" in filename:
continue
zf.write(os.path.join(dirname, filename))
This tells Python to skip the rest of the loop body and go to the next
iteration instead, thus skipping the `zf.write()` call.
A `pass` statement is only useful in places where the Python grammar
_requires_ there to be a line. For example, if you wanted to ignore a specific
exception you'd write:
try:
# code that can raise an exception
except SpecificException:
pass
because you have to write _something_ in the `except` block; `pass` fits that
'something' nicely.
|
How to write long Pandas aggregations well?
Question: **TL;DR**
How do you write long aggregations involving many operations like `groupby()`,
`unstack()` or `apply()` well?
**Example**
Say you have a `DataFrame()` with `n_sales = 1000` ticket sales for `n_events
= 10` different events, like
import pandas as pd
import numpy as np
sales = pd.DataFrame({
'Event': np.random.choice(range(n_events), n_sales),
'Time': np.random.rand(n_sales)})
and you want to plot in how many events at least `n = [50, 100]` tickets were
sold over the evening: 
Then I would do
accumulation_of_sales = sales.groupby(['Time', 'Event']).size().unstack().fillna(0).cumsum()
events_with_n_sales = accumulation_of_sales.apply(lambda x: x.value_counts(), axis=1).fillna(0)
events_with_geq_n_sales = events_with_n_sales[events_with_n_sales.columns[::-1]].cumsum(axis=1)
events_with_geq_n_sales[n].plot()
which seems hard to read to me and the lines are in principle too long (see
[PEP](https://www.python.org/dev/peps/pep-0008/#maximum-line-length)). So,
* how are this specific and similar operations done best?
* are there some tutorials/style guides/... for beginners? Maybe not particularly for Pandas, but similar languages?
Answer: One way to write multiline pandas queries is to use :
accumulation_of_sales = sales.groupby(['Time', 'Event'])\
.size()\
.unstack()\
.fillna(0)\
.cumsum()
_I sometimes prefer to wrap these in parenthesis instead._
However, if you are doing several things here often there is a simpler way.
For example, whenever you see "groupby + unstack" you should think
"pivot_table":
sales.pivot_table(columns='Event', index='Time', aggfunc=len, fill_value=0).cumsum()
_(Which is equivalent, more efficient and more readable.)_
|
Python, Jinja2 nl2br and security
Question: I'm using the [snippet from
Jinja2](http://jinja.pocoo.org/docs/dev/api/#custom-filters) for showing
multiline texts in html and I'm facing an issue :
If the user enters
"Hello\nMy name is Jon"
the `nl2br` tag will render it as
"Hello<br />My name is Jon"
with the br correctly interpreted (a break line).
Now this is good, but if the user enters
"Hello<script>alert('hacked');</script>"
since I have to interpret the html to show the breaklines correctly, the
`<script>` will also be executed...
How can I avoid that?
Answer: The example code you've linked to _already_ escapes the input prior to
replacing newlines. Subsequently, the text is marked safe, because at that
point it is. The relevant code is:
from jinja import escape, Markup
value = escape(value)
return Markup(value)
For the input `"Hello<script>alert('hacked');</script>"`, this results in
`"Hello <script>alert('hacked');</script>"`. Notice that
the problematic syntax has been replaced with escape characters. When rendered
in the HTML document, there will be no script execution, just text.
|
pkg_resources.resource_stream fails on python3
Question: I am trying to load a resource which is present in my project using
`pkg_resources` but it just throws me an exception saying that it quote
**"Can't perform this operation for loaders without 'get_data()'"**. I am not
sure if I am doing something wrong here, or if `pkg_resources` is somehow
broken on python 3.3. I am using python 3.3.3 to be exact. Here is the code I
am trying to execute
>>> import pkg_resources
>>> data = pkg_resources.resource_stream('configgenerator', 'schema_rules.yml')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/users/frank/workspace/configgenerator/env/lib/python3.3/site-packages/distribute-0.6.31-py3.3.egg/pkg_resources.py", line 931, in resource_stream
self, resource_name
File "/home/users/frank/workspace/configgenerator/env/lib/python3.3/site-packages/distribute-0.6.31-py3.3.egg/pkg_resources.py", line 1207, in get_resource_stream
return StringIO(self.get_resource_string(manager, resource_name))
File "/home/users/frank/workspace/configgenerator/env/lib/python3.3/site-packages/distribute-0.6.31-py3.3.egg/pkg_resources.py", line 1210, in get_resource_string
return self._get(self._fn(self.module_path, resource_name))
File "/home/users/frank/workspace/configgenerator/env/lib/python3.3/site-packages/distribute-0.6.31-py3.3.egg/pkg_resources.py", line 1289, in _get
"Can't perform this operation for loaders without 'get_data()'"
NotImplementedError: Can't perform this operation for loaders without 'get_data()'
>>>
Does anyone has an idea on how to fix this?
Answer: This can happen for a number of reasons, but the the most common is the the
package is not an importable module because there is no `__init__.py`.
|
Healpy pix2ang: Convert from HEALPix index to RA,Dec or glong,glat
Question: I am new to HEALPix and fairly new to Python as well. I try to use healpy to
convert a HEALPix index to RA,Dec. I get that I have to use pix2ang, but
cannot figure how to convert the output theta,phi into RA,Dec... I tried this:
import healpy as hp
import numpy as np
theta, phi = hp.pix2ang(256, 632668 ,nest=True)
ra= phi*180./np.pi
dec = 90.-(theta*180./np.pi)
but it does not seem to give the correct result.
Hope someone can help!
Answer: First of all the method `pix2ang(nside,indx)` gives you the coordinates of
pixel with number indx. The pixel number is not directly related to a
coordinate, i.e. two consecutive pixel numbers are not necessarily next to
each other.
Second, as written in the manual of Healpix (which is the underlying code for
healpy) (<http://healpix.sourceforge.net/html/csubnode2.htm>) the angle theta
is defined in range [0,pi] and therefore it cannot directly represent
declination [-pi/2,pi/2].
So what I do is I define a transformation and I implement it in two functions,
for instance:
def IndexToDeclRa(index):
theta,phi=hp.pixelfunc.pix2ang(NSIDE,index)
return -np.degrees(theta-pi/2.),np.degrees(pi*2.-phi)
def DeclRaToIndex(decl,RA):
return hp.pixelfunc.ang2pix(NSIDE,np.radians(-decl+90.),np.radians(360.-RA))
then the map itself will not be in Decl&RA but if you stick to using
`IndexToDeclRa` and `DeclRaToIndex` you'll effecively have what you need.
|
Replace a tag with another tag in BeautifulSoup
Question: I'm attempting to find a tag within an XML document, and replace it entirely
with a new tag. I've got what I think should work below:
para = monograph.find('para', text='Some text.')
newpara = '<para>Some <emph type="bold">new</emph> text.</para>'
newpara = BeautifulSoup(newpara, 'xml')
para.replaceWith(newpara)
Unfortunately, when I run this, I'm getting:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python34\lib\site-packages\bs4\element.py", line 211, in replace_with
my_index = self.parent.index(self)
AttributeError: 'NoneType' object has no attribute 'index'
Any advice?
Answer: You can use
[**replaceWith()**](http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#Replacing%20one%20Element%20with%20Another)
to achieve this, here is one way how to do it:
In [8]: from bs4 import BeautifulSoup
In [9]: tree = BeautifulSoup('<html><body><div>Foo</div><div>Bar</div><para>Some text.</para></body></html>', 'xml')
In [10]: newpara = '<para>Some <emph type="bold">new</emph> text.</para>'
In [11]: newpara = BeautifulSoup(newpara, 'xml')
# here I use newpara.para as a shortcut to get the <para> element
# as a new BeautifulSoup will include wrapping tags
In [12]: tree.find('para', text='Some text.').replaceWith(newpara.para)
Out[12]: <para>Some text.</para>
In [13]: print tree
<?xml version="1.0" encoding="utf-8"?>
<html><body><div>Foo</div><div>Bar</div><para>Some <emph type="bold">new</emph> text.</para></body></html>
Hope this helps.
|
Get grid points of a specific plot in python
Question: I have plotted a map using matplotlib. I want the coordinates of all grid
points within the map and neglect all the grid points outside the map. Is
there any method which can be used directly in this? Intertools is giving all
the grid points but i want only the points within the map.
import matplotlib.pylab as pt
import itertools
pt.set_xticks(np.arange(65,100,.75))
pt.set_yticks(np.arange(0,100,.75))
gridpoints = list( itertools.product(xticks, yticks) )
print gridpoints
Answer: I'm not entirely sure what you're trying to do, but I'll venture a guess. If
you're trying to get all of the grid line intersections on a plot you might
try something like this:
def getGridPoints(ax):
xticks = ax.get_xticks()
yticks = ax.get_yticks()
xmin, xmax = ax.get_xbound()
ymin, ymax = ax.get_ybound()
return list( itertools.product( [x for x in xticks if x>xmin and x<xmax],
[y for y in yticks if y>ymin and y<ymax]))
|
python unicode replace MemoryError
Question: i want replace unicode character to a file with python
this is my code :
with codecs.open('/etc/bluetooth/main.conf', "r", "utf8") as fi:
mainconf=fi.read()
forrep = ''.decode('utf8')
for line in mainconf.splitlines():
if('Name = ' in line):
forrep = line.split('=')[1]
print 'name',type(name)
print 'mainconf',type(mainconf)
print 'forrep',type(forrep)
mainconf = mainconf.replace(forrep, name)
#mainconf = mainconf.replace(forrep.decode('utf8'),' '+name)
with codecs.open('/etc/bluetooth/main.conf','w',"utf8") as fi:
fi.write(mainconf)
but python always get me error `MemoryError`...
this out :
name <type 'unicode'>
mainconf <type 'unicode'>
forrep <type 'unicode'>
Traceback (most recent call last):
File "WORK/Bluetooth/Bluetooth.py", line 359, in <module>
if __name__ == '__main__':main()
File "WORK/Bluetooth/Bluetooth.py", line 336, in main
BLMan.SetAllHCIName(common.cfg.get('BLUETOOTH', 'HCI_DEVICE_NAME'))
File "WORK/Bluetooth/Bluetooth.py", line 194, in SetAllHCIName
mainconf = mainconf.replace(forrep, name)
MemoryError
Answer: Iterate over the file object, you are storing the whole file content in memory
using `mainconf=fi.read()` :
with codecs.open('/etc/bluetooth/main.conf', "r", "utf8") as fi:
for line in fi:
You store all the lines with read then you store a list of all the lines using
splitlines so you are storing all the file content twice and as @abarnet
pointed out in a comment you then try to store a third copy with `mainconf =
mainconf.replace(forrep, name)`.
Iterating over the file object will give you a line at a time, if you need to
store the lines after replacing do so each time through the loop so at most
you will only have one copy of the file content in memory.
I have no idea what name is but writing to a tempfile will be the most
efficient way to do what you want:
from tempfile import NamedTemporaryFile
with open('/etc/bluetooth/main.conf') as fi, NamedTemporaryFile(dir=".", delete=False) as out:
for line in fi:
if line.startswith("Name ="):
a, b = line.split("=",1)
out.write("{} = {}".format(a, name.encode("utf-8")))
else:
out.write(line)
move(out.name, '/etc/bluetooth/main.conf')
|
collective.localfunctions prevents plone from starting
Question: Plone 4.3.3
I am trying to get some extra python modules available to my plone scripts.
'Net search led me to collective.localfunctions, which supposedly demonstrates
how to lighten up restricted python. I installed per the instructions:
git clone https://github.com/collective/collective.localfunctions
easy_install collective.localfunctions
# not installed where plone can get to it, so...
copy from system python lib to the plone build-cache/eggs director
added collective.localfunctions to eggs = and zcml =
Running buildout and restarting results in a non-responsive site, nothing is
listening on 8080. There is nothing useful in var/log, either. So, bottom line
question is, how do I enable python modules, specifically re and datetime?
Answer: The proper way to allow extra modules to be used in restricted python is
outlined in the answer to this [Importing ping module in RestrictedPython
script in Plone](http://stackoverflow.com/questions/11576938/importing-ping-
module-in-restrictedpython-script-in-plone)
|
Type Error Python
Question: I am currently working on a game and I tried to make an image move and I keep
getting this error right here
TypeError: unbound method put_here() must be called with create_entity instance as first argument (got int instance instead)
Here is the code for the PlayerEntity.py file the I made.
class create_entity:
def __init__(self, image, name, armor, skills, weapons):
self.entity_image = image
self.entity_name = name
self.entity_armor = armor
self.entity_skills = skills
self.entity_weapons = weapons
def put_here(self,x,y):
screen.blit(self.entity_image, (x,y))
Now here is the main Game file that I was testing this in
if __name__ == '__main__':
import PlayerEntity as p_entity
p_entity.create_entity('test_img.png', 'Default', [], [], [])
p_entity.create_entity.put_here(300,300)
Answer: You should save the instantiated object into a variable and use it to call its
function:
entity = p_entity.create_entity('test_img.png', 'Default', [], [], [])
entity.put_here(300,300)
This code assumes that `import PlayerEntity as p_entity` returns a module
`p_entity` that contains the class `create_entity` ([bad name for a
class](https://www.python.org/dev/peps/pep-0008/#class-names) \- by the way)
|
Python: ContextManager-like for function alias
Question: ContextManager is really useful and it's also make our code more readable, but
it seems it only works if the given function is meant to be a context manager,
otherwise it will fail (no `__exit__` or something else). I' wondering if we
can use any function including those in libraries such as Django as a
contextmanager, suppose the given code
self.assertEqual(Transaction.objects.filter(account=a, date=b, year=c).count(), 10)
self.assertEqual(Transaction.objects.filter(account=e, date=f, year=g).count(), 15)
self.assertEqual(Transaction.objects.filter(account=h, date=i, year=j).count(), 20)
Can be transformed into:
with Transaction.objects.filter as f:
self.assertEqual(f(account=a, date=b, year=c).count(), 10)
self.assertEqual(f(account=d, date=d, year=e).count(), 15)
self.assertEqual(f(account=h, date=i, yearj).count(), 20)
The way I look at it is that the one below is much readable, cleaner and less
verbose. Is this possible?
Answer: Just do:
f = Transaction.objects.filter
before your statements!
If you really wanted to use a context manager, you could write one that does
what you want:
from contextlib import contextmanager
@contextmanager
def alias(func):
yield func
with alias(Transaction.objects.filter) as f:
...
Note that, however you do this, without an explicit `del` statement, `f` will
still be around after the `with`.
|
java's e.printStackTrace equivalent in haskell
Question: I am trying out haskell's kafka library from git and got this
[error](https://github.com/tcrayford/hafka/issues/2). To debug this error, i
like to print stacktrace at the error line.
In python world, it is just,
import traceback; print traceback.print_exc()
(or) in java, it is
e.printStackTrace()
So, how to do the same in haskell world?
Answer: You can get stack traces in Haskell but it is not as convenient as just
`e.printStackTrace()`. Here is a minimal example:
import Control.Exception
import Debug.Trace
getStack :: String -> SomeException -> IO a
getStack msg e = traceStack (show e) $ error msg
main :: IO ()
main = do
(head []) `catch` (getStack "error on main at head")
Finally, compile it with `ghc -prof -fprof-auto StackTrace.hs` and it will
produce
Prelude.head: empty list
Stack trace:
Main.getStack (StackTrace.hs:5:9-56)
Main.main (StackTrace.hs:(8,9)-(9,74))
GHC.List.CAF (<entire-module>)
StackTrace.exe: error on main at head
|
Python 2.7: Multiprocessing: How to not block whilst using a queue for communication
Question: I am using a Queue for communicating between processes and also an event flag
to indicate whether or not the parent process wants to exit however the Queue
in child process is in a blocked state, waiting for more input.
I can make the queue not block by using get_nowait() however that is making
the processor use 100%
What is the recommended way of being able to close a child process and accept
input at the same time?
from multiprocessing import Process
from multiprocessing import Event
from multiprocessing import Queue
class EchoProcess(Process):
def __init__(self, iQ, closeEvent):
Process.__init__(self)
self.iQ = iQ
self.closeEvent = closeEvent
def run(self):
while not self.closeEvent.is_set():
istring = self.iQ.get()
print(istring)
print("exited")
if __name__ == "__main__":
iQ = Queue()
closeEvent = Event()
echoProcess = EchoProcess(iQ, closeEvent)
echoProcess.start()
while True:
istring = raw_input("Enter:")
if istring == "quit": break
iQ.put(istring)
closeEvent.set()
Answer: You can use a sentinel.
Define the sentinel as a value that never appears in normal data and when
EchoProcess gets it, it quits.
For example:
from multiprocessing import Process
from multiprocessing import Queue
class Sentinel(object): pass
class EchoProcess(Process):
def __init__(self, iQ):
Process.__init__(self)
self.iQ = iQ
def run(self):
for istring in iter(iQ.get, Sentinel):
print(istring)
print("exited")
if __name__ == "__main__":
iQ = Queue()
echoProcess = EchoProcess(iQ)
echoProcess.start()
while True:
istring = raw_input("Enter:")
if istring == "quit": break
iQ.put(istring)
iQ.put(Sentinel)
echoProcess.join()
|
Skip a specified number of columns with numpy.genfromtxt() python 3.4 error
Question:
import os
import numpy as np
import matplotlib.pyplot as plt
# Open a file
path = "input/"
filelist = list(filter(lambda s: s.endswith(".asc"), os.listdir(path)))
firstImage = np.genfromtxt (" ".join(ln.split()[1:]) for ln in path+next(iter(filelist)))
what is wrong? getting: TypeError: Can't convert 'bytes' object to str
implicitly
Answer: Check out the function's doc, it seems able to to all kinds of crazy things
out of the box :
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html>
Including but not limited to, using the `usecols` parameters would allow you
to skip using some columns.
Then there would be no need for fancy operations
|
How can I import a Python class that is in two directories above and one below?
Question: How can I import a CustomerHelper class inside `customer_helper.py` from
`customer_helper_test.py`? It's possible? I used `from
..helpers..tests..app.helpers.customer_helper import CustomerHelper` but it's
invalid syntax.
Here is the folders organized:
program/
app/
helpers/
customer_helper.py
__init__.py
__init__.py
tests/
helpers/
customer_helper_test.py
__init__.py
__init__.py
__init__.py
Thanks in advance!
Answer: Always strive to use absolute imports.
from program.app.helpers.customer_helper import CustomerHelper
If for some reason you absolutely can't, then
from ...app.helpers.customer_helper import CustomerHelper
Note that `app` must be a package regardless.
|
Having trouble understanding directory navigation with os.walk
Question: I'm relatively new to python and I'm trying my hand at a weekend project. I
want to navigate through my music directories and get the artist name of each
music file and export that to a csv so that I can upgrade my music collection
(a lot of it is from when I was younger and didn't care about quality).
Anyway, I'm trying to get the path of each music file in its respective
directory, so I can pass it to id3 tag reading module to get the artist name.
Here is what I'm trying:
import os
def main():
for subdir, dirs, files in os.walk(dir):
for file in files:
if file.endswith(".mp3") or file.endswith(".m4a"):
print(os.path.abspath(file))
However, .abspath() doesn't do what I think it should. If I have a directory
like this:
music
--1.mp3
--2.mp3
--folder
----a.mp3
----b.mp3
----c.mp3
----d.m4a
----e.m4a
and I run my code, I get this output:
C:\Users\User\Documents\python_music\1.mp3
C:\Users\User\Documents\python_music\2.mp3
C:\Users\User\Documents\python_music\a.mp3
C:\Users\User\Documents\python_music\b.mp3
C:\Users\User\Documents\python_music\c.mp3
C:\Users\User\Documents\python_music\d.m4a
C:\Users\User\Documents\python_music\e.m4a
I'm confused why it doesn't show the 5 files being inside of a folder. Aside
from that, am I even going about this in the easiest or best way? Again, I'm
new to python so any help is appreciated.
Answer: You are passing _just_ the filename to `os.path.abspath()`, which has no
context but your current working directory.
Join the path with the `subdir` parameter:
print(os.path.join(subdir, file))
From the [`os.path.abspath()`
documentation](https://docs.python.org/3/library/os.path.html#os.path.abspath):
> On most platforms, this is equivalent to calling the function `normpath()`
> as follows: `normpath(join(os.getcwd(), path))`.
so if your current working directory is `C:\Users\User\Documents\python_music`
all your files are joined relative to that.
But `os.walk` gives you the correct location to base filenames off instead;
from [the documentation](https://docs.python.org/3/library/os.html#os.walk):
> For each directory in the tree rooted at directory _top_ (including _top_
> itself), it yields a 3-tuple `(dirpath, dirnames, filenames)`.
>
> _dirpath_ is a string, the path to the directory. _[...]_ _filenames_ is a
> list of the names of the non-directory files in _dirpath_. **Note that the
> names in the lists contain no path components. To get a full path (which
> begins with _top_) to a file or directory in _dirpath_ , do
> `os.path.join(dirpath, name)`.**
Emphasis mine.
|
Correct way to make python module smaller by delegating
Question: I'm trying to reduce clutter in my project's models.py and I decide to move
out "utility" methods of some models.
The idea was to create a bunch of utility modules with classes and functions
which will be used by model classes, but since there is no significant piece
of code that doesn't use other models, it results in a circular dependence.
E.g. in `models.py`:
from myproject import parse_util
class Entry(models.Model):
text = models.TextField()
parser = parse_util.Parser(self)
def get_some_object():
return parser.parse_text()
class SomeModel(models.Model):
name = models.CharField(max_length=32, null=False, unique=True)
In `parse_util.py`:
from myproject.models import SomeModel
class Parser():
def __init__(self, entry):
self.entry = entry
def parse_text(self):
# parsing self.entry.text
...
some_object = SomeModel.objects.get(name=parsed_value)
return some_object
I can avoid it by importing `SomeModel` directly in the function, instead of
doing it module-wide, or use `get_model('myapp', 'SomeModel')`. But both of
these don't look good.
After the whole day in thoughts I generalised the problem: what is the correct
and pythonic way (if any) to move some code coupled with another code in the
module out of that module?
That is if there is a module with `classA` and `classB` and there are lengthy
methods of `classB`, which use both `classA` and `classB` in some way, is
there any good solution to cut down described module by splitting it into
several models, but keeping entry points to `classA` and `classB` in place.
Answer: So you have the following hardcoded dependencies: Entry → Parser → SomeModel.
The way I would break the dependency is to make `Parser` generic like this:
class Parser(object):
def __init__(self, entry, model):
self.entry = entry
self.model = model
def parse_text(self):
# parsing self.entry.text
...
some_object = self.model.objects.get(name=parsed_value)
return some_object
Now the hardcoded dependencies are just: Entry → Parser
|
Singpath Python Error. "Your code took too long to return."
Question: I was playing around with the _Singpath_ Python practice questions. And came
across a simple question which asks the following:
Given an input of a list of numbers and a high number,
return the number of multiples
of each of those numbers that are less than the maximum number.
For this case the list will contain a maximum of 3 numbers
that are all relatively prime to each other.
I wrote this simple program, it ran perfectly fine:
"""
Given an input of a list of numbers and a high number,
return the number of multiples
of each of those numbers that are less than the maximum number.
For this case the list will contain a maximum of 3 numbers
that are all relatively prime to each other.
>>> countMultiples([3],30)
9
>>> countMultiples([3,5],100)
46
>>> countMultiples([3,5,7],30)
16
"""
def countMultiples(l, max):
j = []
for num in l:
i = 1
count = 0
while num * i < max:
if num * i not in j:
j.append(num * i)
i += 1
return len(j)
print countMultiples([3],30)
print countMultiples([3,5],100)
print countMultiples([3, 5, 7],30)
But when I try to run the same on SingPath, it gave me this error
Your code took too long to return.
Your solution may be stuck in an infinite loop. Please try again.
Has anyone experienced the same issues with Singpath?
Answer: I suspect the error you're getting means exactly what it says. For some input
that the test program gives your function, it takes too long to return. I
don't know anything about singpath myself, so I don't know exactly how long
that might be. But I'd guess that they give you enough time to solve the
problem if you use the best algorithm.
You can see for yourself that your code is slow if you pass in a very large
`max` value. Try passing `10000` as `max` and you may end up waiting for a
minute or two to get a result.
There are a couple of reasons your code is slow in these situations. The first
is that you have a `list` of every multiple that you've found so far, and you
are searching the list to see if the latest value has already been seen. Each
search takes time proportional to the length of the list, so for the whole run
of the function, it takes quadratic time (relative to the result value).
You could improve on this quite a lot by using a `set` instead of a `list`.
You can test if an object is in a `set` in (amortized) constant time. But if
`j` is a set, you don't actually need to test if a value is already in it
before adding, since `set`s ignore duplicated values anyway. This means you
can just `add` a value to the set without any care about whether it was there
already.
def countMultiples(l, max):
j = set() # use a set object, rather than a list
for num in l:
i = 1
count = 0
while num * i < max:
j.add(num*i) # add items to the set unconditionally
i += 1
return len(j) # duplicate values are ignored, and won't be counted
This runs a fair amount faster than the original code, and `max` values of a
million or more will return in a not too unreasonable time. But if you try
values larger still (say, 100 million or a billion), you'll eventually still
run into trouble. That's because your code uses a loop to find all the
multiples, which takes linear time (relative to the result value).
Fortunately, there is a better algorithm.
(If you want to figure out the better approach on your own, you might want to
stop reading here.)
The better way is to use division to find how many times you can multiply each
value to get a value less than `max`. The number of multiples of `num` that
are strictly less than `max` is `(max-1) // num` (the `-1` is because we don't
want to count `max` itself). Integer division is much faster than doing a
loop!
There is an added complexity though. If you divide to find the number of
multiples, you don't actually have the multiples themselves to put in a `set`
like we were doing above. This means that any integer that is a multiple of
more than than one of our input numbers will be counted more than once.
Fortunately, there's a good way to fix this. We just need to count how many
integers were over counted, and subtract that from our total. When we have two
input values, we'll have double counted every integer that is a multiple of
their least common multiple (which, since we're guaranteed that they're
relatively prime, means their product).
If we have three values, We can do the same subtraction for each pair of
numbers. But that won't be exactly right either. The integers that are
multiples of all three of our input numbers will be counted three times, then
subtracted back out three times as well (since they're multiples of the LCM of
each pair of values). So we need to add a final value to make sure those
multiples of all three values are included in the final sum exactly once.
import itertools
def countMultiples(numbers, max):
count = 0
for i, num in enumerate(numbers):
count += (max-1) // num # count multiples of num that are less than max
for a, b in itertools.combinations(numbers, 2):
count -= (max-1) // (a*b) # remove double counted numbers
if len(numbers) == 3:
a, b, c = numbers
count += (max-1) // (a*b*c) # add the vals that were removed too many times
return count
This should run in something like constant time for any value of `max`.
Now, that's probably as efficient as you need to be for the problem you're
given (which will always have no more than three values). But if you wanted a
solution that would work for more input values, you can write a general
version. It uses the same algorithm as the previous version, and uses
`itertools.combinations` a lot more to get different numbers of input values
at a time. The number of products of the LCM of odd numbers of values get
added to the count, while the number of products of the LCM of even numbers of
values are subtracted.
import itertools
from functools import reduce
from operator import mul
def lcm(nums):
return reduce(mul, nums) # this is only correct if nums are all relatively prime
def countMultiples(numbers, max):
count = 0
for n in range(len(numbers)):
for nums in itertools.combinations(numbers, n+1):
count += (-1)**n * (max-1) // lcm(nums)
return count
Here's an example output of this version, which is was computed very quickly:
>>> countMultiples([2,3,5,7,11,13,17], 100000000000000)
81947464300342
|
Python Assign Value to New Column If Contains() Is True
Question: How can I use the str.contains() method to check a column if it contains
specific strings and assign a value if true in a different column?
Essentially, I'm trying to mimic a CASE WHEN LIKE THEN syntax in SQL but in
pandas. Really new to python and pandas and would appreciate any help!
Essentially, I want to search 'Source' for either video, audio, default, and
if found, then Type would be video, audio, default accordingly. I hope this
makes sense!
Source Type
video1393x2352_high video
audiowefxwrwf_low audio
default2325_none default
23234_audio audio
Answer: Use the str.extract method ... takes a regular expression as an argument ...
returns matched group as a string ...
df['Type'] = df.Source.str.extract('(video|audio|default)')
For some case sensitivity you could add ...
df['Type'] = df.Source.str.lower().str.extract('(video|audio|default)')
Example, including a non match follows ...
In [24]: %paste
import pandas as pd
data = """
Source
video1393x2352_high
audiowefxwrwf_low
default2325_none
23234_audio
complete_crap
AUDIO_upper_case_test"""
from StringIO import StringIO # import from io for python 3
df = pd.read_csv(StringIO(data), header=0, index_col=None)
df['Type'] = df.Source.str.lower().str.extract('(video|audio|default)')
## -- End pasted text --
In [25]: df
Out[25]:
Source Type
0 video1393x2352_high video
1 audiowefxwrwf_low audio
2 default2325_none default
3 23234_audio audio
4 complete_crap NaN
5 AUDIO_upper_case_test audio
|
Getting rid of SettingWithCopyWarning in Python pandas
Question: I am loading a bunch of csvs and processing certain columns if they exist,
after loading the csv with pandas
data = pd.read_csv('Test.csv', encoding = "ISO-8859-1", index_col=0)
this dataframe will be used in the example
import pandas as pd
data = pd.DataFrame({'A': [1, 2.1, 0, 4.7, 5.6, 6.8],
'B': [0, 1, 0, 0, 0, 0],
'C': [0, 0, 0, 0, 0, 1],
'D': [5, 5, 6, 5, 5.6, 6.8],
'E': [2, 4, 1, 0, 0, 5],
'F': [0, 0, 1, 0, 0, 0],
'G': [0, 0, 0, 0, 0, 0],})
Next I check and select specific columns that are going be processed
coltitles = ['A', 'B','C', 'D', 'E']
columns = []
for name in coltitles:
if name in data.columns:
columns.append(name)
else:
print (name, 'is missing')
df = data[columns]
if 'A' in df.columns:
#perform some processing, I will put print to simplify it
print ('Exist')
The code works if I use a dataframe for `data`, but If I load the data from a
csv I get a Warning:
<module3>:74: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
The warning is caused by the line where `df = data[columns]`.
The code still works with the warning but how do I get rid of this warning
without suppressing it?
Answer: > The chained assignment warnings / exceptions are aiming to inform the user
> of a possibly invalid assignment. There may be false positives; situations
> where a chained assignment is inadvertantly reported.
The purpose of this warning is to flag to the user that the assignment is
carried out on a copy of the DataFrame slice instead of the original Dataframe
itself.
You generally want to use .loc (or .iloc, .at, etc.) type indexing instead of
'chained' indexing which has the potential to not always work as expected.
To make it clear you only want to assign a copy of the data (versus a view of
the original slice) you can append .copy() to your request, e.g.
`df = data[columns].copy()`
See the [documentation](http://pandas.pydata.org/pandas-
docs/stable/indexing.html#returning-a-view-versus-a-copy) for more details.
|
Passing model class to function changes behavior
Question: The first set of python code properly imports an entire CSV file. However, if
I try to pass the model ZipMHA as a parameter, it only imports the first line
of the CSV file. Can anybody explain this change in behavior when passing the
model into the function?
import csv
from bah_api.models import withDependents, withOutDependents, ZipMHA
# Populate CSV file into model
def LoadCSV(file_location, delim):
f = open(file_location)
csv_f = csv.reader(f, delimiter=delim)
for row in csv_f:
i = 1
# create a model instance
target_model = ZipMHA()
#loop through the rows
for y in row:
setattr(target_model, target_model._meta.fields[i].name, y)
i += 1
# save each row
target_model.save()
f.close()
LoadCSV("BAH2015/sorted_zipmha15.txt", ' ')
Model passed as parameter (only reads first line):
# Populate CSV file into model
def LoadCSV(file_location, my_model, delim):
f = open(file_location)
csv_f = csv.reader(f, delimiter=delim)
for row in csv_f:
i = 1
# create a model instance
target_model = my_model
#loop through the rows
for y in row:
setattr(target_model, target_model._meta.fields[i].name, y)
i += 1
# save each row
target_model.save()
f.close()
LoadCSV("BAH2015/sorted_zipmha15.txt", ZipMHA(), ' ')
Answer: You are passing the model instance instead of the model class. Creation of the
`target_model` instance should be like this:
target_model = my_model() # note the round brackets
And call the function without the brackets after the `ZipMHA` class name:
LoadCSV("BAH2015/sorted_zipmha15.txt", ZipMHA, ' ')
|
Python: Copy two dependent lists together with their dependence
Question: I am stuck with some problem which I guess is not very difficult, but I could
not find any answer to it.
I have two lists of objects, each of them containing lists of objects in the
other. I would like to copy them both to do come tests and evaluate the
results before repeating the process. In the end, I would keep the best
result.
However, when copying each lists, the result is, unsurprisingly, not two
dependent lists but two lists which do not interact anymore. How can I solve
this? Is there some proper way to do it?
Given the two classes defined as follow.
import copy
class event:
def __init__(self, name):
self.name = name
self.list_of_persons = []
def invite_someone(self, person):
self.list_of_persons.append(person)
person.list_of_events.append(self)
class person:
def __init__(self, name):
self.name = name
self.list_of_events = []
I tried to write some simple example of the situation I am facing. The print
function shows that the objects identifiers are different in the two lists.
# Create lists of the events and the persons
the_events = [event("a"), event("b")]
the_persons = [person("x"), person("y"), person("z")]
# Add some persons at the events
the_events[0].invite_someone(the_persons[0])
the_events[0].invite_someone(the_persons[1])
the_events[1].invite_someone(the_persons[1])
the_events[1].invite_someone(the_persons[2])
print("Original :", id(the_persons[1]), id(the_events[0].list_of_persons[1]), id(the_events[1].list_of_persons[0]))
# Save the original configuration
original_of_the_events = copy.deepcopy(the_events)
original_of_the_persons = copy.deepcopy(the_persons)
for i in range(10):
# QUESTION: How to make the following copies?
the_events = copy.deepcopy(original_of_the_events)
the_persons = copy.deepcopy(original_of_the_persons)
print(" i =", i, ":", id(the_persons[1]), id(the_events[0].list_of_persons[1]), id(the_events[1].list_of_persons[0]))
# Do some random stuff with the two lists
# Rate the resulting lists
# Record the best configuration
# Save the best result in a file
I thought about using some dictionary and make the list independent, but that
would imply a lot of code revision which I would like to avoid.
Thank you in advance for any help! I am new both to Python and StackExchange.
Answer: Since deepcopy makes copies of all underlying objects of the thing being
copied, doing two independent calls to deepcopy breaks your links between
objects. If you create a new object with references to both of these things
(like a dict) and copy that object, that will preserve the object references.
workspace = {'the_persons': the_persons, 'the_events': the_events}
cpw = copy.deepcopy(workspace)
|
Pygame2exe not executing my game
Question: I made a game called "Fish Food" with Python 2.7.6
When executing pygame2exe:
running py2exe
c:\python27\lib\distutils\dist.py:267: UserWarning: Unknown distribution
option: 'dist_dir'
warnings.warn(msg)
That returns error: bundle-files 1 not yet supported on win64
I am running Windows 8, 64 bit. If it is a problem of compatibility, is there
any way for me to create an executable for my game (I used pygame) so that
people who don't have python on their system can play it?
I have the script and it is incredibly long (and hard to format it on the
website). But, it's just this: <https://www.pygame.org/wiki/Pygame2exe>, but
modified to load "FishFood.py" and the new dist folder "c:\python27\games\fish
food\dist\"
Thanks
Answer: Well this was annoying, but I somehow figured it out to get my game to become
a .exe. Didn't even use the long pygame2exe script.
1) Make sure latest Microsoft Visual C++ Redistributable Package is installed
(not sure if my troubles were from that before). And make sure you have py2exe
installed.
2) if your code has "None" as a font somewhere, change it! It could be
anything besides None!
self.font = pygame.font.font(None,32)
change to
self.font = pygame.font.SysFont("Arial",32)
3) Setup.py code:
# setup.py, put in same folder as src
from distutils.core import setup
import py2exe
setup(console=['Game.py'])
4) Change file associations for .py from whatever editing program you use to
python.
5) Go to cmd, change directory to your game folder, and then launch setup.py
withpy2exe:
cd c:\python27\YOURGAMESRC\
setup.py py2exe
6) Copy all folders containing files that are used in the game (sprites,
sounds, fonts, etc)
7) For installation instructions, extract all files and then click the .exe
file to play and it worked for me.
|
Calling a function in another function causing error due to arguments in parantheses
Question: As it happens I am just getting into programming with Python and I was about
to program a little rock-paper-scissors game.
Unfortunately when I'm trying to run my script, I am receiving the following
error:
file rps.py, line 53 in game
compare (move,choice)
NameError: name 'move' is not defined"
Here's my code so far:
from random import randint
possibilities = ['rock', 'paper', 'scissors']
def CPU(list):
i = randint(0, len(list)-1)
move = list[i]
#print (str(move))
return move
def User():
choice = str(input('Your choice? (Rock [r], Paper[p], Scissors[s])'))
choice = choice.lower()
if choice == 'rock' or choice == 'r':
choice = 'rock'
elif choice == 'scissors' or choice =='s':
choice = 'scissors'
elif choice == 'paper' or choice == 'p':
choice = 'paper'
#print ('Your choice: ' + str(choice))
return choice
def compare(c, u):
if c == u:
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('That is what we call a tie. Nobody wins.')
elif c == 'paper' and u == 'rock':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('This means that you, my friend, lose.')
elif c == 'paper' and u == 'scissors':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('Congratulations, you win....this time.')
elif cc == 'rock' and u == 'paper':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('Congratulations, you win....this time.')
elif c == 'rock' and u == 'scissors':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('This means that you lose.')
elif c == 'scissors' and u == 'paper':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('This means that you lose.')
elif c == 'scissors' and u == 'rock':
print ('Your choice was: ' + str(u) + 'and I chose: ' + str(c))
print ('Congratulations, you win....this time.')
def game():
CPU(possibilities)
User()
compare(move, choice)
game()
I am pretty sure that I did something wrong when I defined the function
`compare(c,u)` and added the arguments 'c' and 'u' in the parentheses. I
thought that I made sure that I was able to use these variables by using the
return statement before.
I am quite new to programming in general and therefore inexperienced, so
please be kind!
Answer: The problem is that you are only calling the functions `CPU` and `User` but
you are not assigning them to any variables. Hence you need to re-define your
function `game` as in
def game():
move = CPU(possibilities)
choice = User()
compare(move, choice)
In this way you will be calling the function `compare` with a local copy of
the values `return`ed after calling the two other functions.
You can refer more about functions and the `return` statement by referring the
official
[documentation](https://docs.python.org/2/tutorial/controlflow.html#defining-
functions)
|
How to run one-off python script on Heroku
Question: I have a Django app up and running on Heroku. I want to run a simple script
called import.py, which imports a CSV file into my models. It works great on
my local computer. When I try to run the script on Heroku using this commmand:
heroku run python manage.py < import.py
All it does is read the script back to me, but not execute any of the content.
What am I doing wrong?
Edit:
This is the start of the result I get when I run: heroku run python manage.py
< import.py
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import csv
>>> from bah_api.models import withDependents, withOutDependents, ZipMHA
>>>
>>> # Populate CSV file into model
>>> def LoadCSV(file_location, my_model, delim):
... f = open(file_location)
File "<console>", line 2
f = open(file_location)
^
IndentationError: expected an indented block
>>> csv_f = csv.reader(f, delimiter=delim)
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'f' is not defined
>>> for row in csv_f:
...
Display all 182 possibilities? (y or n)
Answer: I think you should create command for this. Commands should be placed in
`app/management/commands` directory in your project. If this directory doesn't
exist, create it. The name of the script is the name of your command, so you
should name it `import.py` (bad name...). Another thing that has to be done is
creating `__init__.py` files in both the 'management' and 'commands'
directories, because these have to be Python packages. Tree should be like
this :
app
├── admin.py
├── __init__.py
├── management
│ ├── commands
│ │ ├── __init__.py
│ │ └── import.py
│ └── __init__.py
├── models.py
... other files
Now you should be able to make something like this: `python manage.py import`
(really bad name...)
Or`heroku run python manage.py import` will work with heroku.
P.S. I don't know if it works with name 'import'
|
moving mutiple files from one folder to another using python
Question: I have a “.txt ”file which consists of various filenames and I want to search
each filename in a source_folder where these files are actually kept and I
want to move the matching files to a specific folder. Source_folder contain
files within multiple folders.
My .txt file looks like this:
ant1.aiq
ant2.aiq
ant3.aiq
ant4.aiq
I want to match each line of my textfile (`ant1.aiq`, `ant2.aiq` and so on)
with filenames which are present at some specific place (`R:\Sample`) and
extract matching files into some other place (`R:\sample\wsa`).
So far I have written following code but it doesnt work:
import os
import shutil
sourceDir = "R:\test_vectors\pxi_wcdma"
targetDir = "R:\\Sample\\wsa"
existingFiles = set(f for f in os.listdir(sourceDir) if os.path.isfile(os.path.join(sourceDir, f)))
infilepath = "aiq_hits.txt"
with open(infilepath) as infile:
for line in infile:
fname = line.strip()
if fname not in existingFiles: continue
shutil.move(os.path.join(sourceDir, fname),os.path.join(targetDir, fname))
Path for source folder is : R:\test_vectors\pxi_wcdma pxi_wcdma folder
contains .aiq files which are to be copied
Answer: I've tested this on my server and it works. Make sure the paths are correct
and you've permissions to read and write.
import os
import shutil
file = "test.txt"
sourceDir = "R:\\test_vectors\\pxi_wcdma\\"
targetDir = "R:\\Sample\\wsa\\"
for line in open("test.txt") :
line = line.rstrip('\n')
if os.path.isfile(sourceDir+line):
shutil.move(sourceDir+line, targetDir+line)
* * *
Some tips about path names on windows OS:
This works both in linux and windows:
'C:/mydir'
Other posibility is :
'C:\\mydir'
If you have problems with some names you can also try raw strings:
r'C:\mydir'
|
connect two raspberry pi via ethernet cable
Question: I am using python to connect two raspberry pi via serial port. one pi will
send data to another pi. and another pi will do some specfic task depending on
received data. can i use ethernet port for this function? Is there any
function similar to serial.read() and serial.available() in case of ethernet
port.
I wrote the simple server program
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host=socket.gethostname()
port=12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'got connection from',addr
c.send('Thank you for connecting')
c.close()
and client program is
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname()
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close
error is no connection is made because target machine actively refuse it. what
is my mistake?
Answer: Yes, you can use ethernet for this purpose. You can create a
[TCP](https://wiki.python.org/moin/TcpCommunication) connection between the
two machines. Much like a serial connection, this will give you a
bidrectional, byte stream.
|
how use server-celery with flask
Question: I installed celery-server 3.0.0 to flask and then I started the server, but
when I used the server to run a python code backgroud I find this error.
> ~/Bureau$ sudo python exme.py
> Traceback (most recent call last):
> File "exme.py", line 2, in
> from celery import Celery
> ImportError: No module named celery
>
from flask import Flask
from celery import Celery
app = Flask(__name__)
app.config.update(
CELERY_BROKER_URL='redis://localhost:6379',
CELERY_RESULT_BACKEND='redis://localhost:6379'
)
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
@celery.task()
def add_together(a, b):
return a + b
@APP.route('/test',methods=['POST'])
def test():
try:
result=add_together.delay(5,2)
return result
except Exception as e:
return e
Answer: You probably don't need to use `sudo` to run your app. When you use `sudo`,
your environment variables are not carried over and you loose your virtualenv.
Run your app like this instead:
$ python exme.py
|
how can i get translate values in maya python api?
Question: Actually i'am new to api and am trying to get the translation values(x,y,z)
but the problem is i cant get when i specify only "translate" instead of
"translateX", "translateY", "translateZ" in every separate line. is there any
way to get what i actually want?
here's the code:
import maya.OpenMaya as om
selected = om.MSelectionList()
om.MGlobal.getActiveSelectionList(selected)
obj = om.MObject()
selected.getDependNode(0,obj)
print(om.MFnDependencyNode(obj).findPlug("translateX").asFloat())
print(om.MFnDependencyNode(obj).findPlug("translateY").asFloat())
print(om.MFnDependencyNode(obj).findPlug("translateZ").asFloat())
thank you...
Answer: The translate attribute is a compound attribute. In the Maya API, you have to
individually query each child attribute of a compound attribute in order to
retrieve the complete value of the compound attribute.
But the MEL getAttr() command can retrieve the value of the translate
attribute all at once. Since you are using Python, you can mix MEL commands
and calls to the Maya API together in the same script:
import maya.OpenMaya as om
import maya.cmds as cmds
selected = om.MSelectionList()
om.MGlobal.getActiveSelectionList(selected)
obj = om.MObject()
selected.getDependNode(0,obj)
depNodeName = om.MFnDependencyNode(obj).name()
print(cmds.getAttr(depNodeName + '.translate')[0])
|
FuncAnimation Plot hangs when length of list increases
Question: For my college project I am developing a traffic generation script in python.
This traffic generation script makes use to multiprocessing module to generate
large amount of http traffic in concurrent fashion. My scripts are working
fine and now I am trying to build a user friendly GUI using wxpython to
operate working of these scripts. I have kept both these scripts separate.In
my GUI script, I have imported my traffic generation (work) script and then I
call its function(work.time_func() or work.requests_func()) to run
multiprocesses when initiated by user on GUI. Upto here my script works fine.
Further, in my wxpython panel I have appended a graph that plots some data
(shared list between various processes) related to traffic generation script (
work.rt ( multiprocessing.Manager().list())-->which is actually shared data
between all processes). now the length of data (len(work.rt)) to be plotted
here goes upto 1,00,00,000, but my GUI hangs after plotting around 2500 datas
only. What could be the problem here? How to overcome it? I am using centos
6.5. Here is my code:
import work #traffic generation script
import wx.lib.scrolledpanel as scrolled
import matplotlib.animation as anim
import matplotlib.figure as mfigure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar
import time
import wx
import os
import paramiko
import sys
from paramiko import SSHConfig
from paramiko import SSHClient
from multiprocessing import Value
import thread
class TabPanel1(scrolled.ScrolledPanel):
def __init__(self,parent):
scrolled.ScrolledPanel.__init__(self,parent=parent)
self.SetDoubleBuffered(True)
self.label_0=wx.StaticText(self,-1,"Mode of Operation:",(40,25))
self.label_0_list=['Request Based','Time Based']
self.label_0_combo=wx.ComboBox(self,-1,'None',(200,25),wx.DefaultSize,self.label_0_list,wx.CB_DROPDOWN)
self.label_1=wx.StaticText(self,-1,"Number of Clients:",(40,75))
self.label_1_list=['1','2','3','4','5','10','15','20','25','30','35','40','45','50']
self.label_1_combo=wx.ComboBox(self,-1,'None',(200,75),wx.DefaultSize,self.label_1_list,wx.CB_DROPDOWN)
self.label_2=wx.StaticText(self,-1,"Actions:",(40,125))
self.label_2_list=['Web','Download','Video']
self.label_2_combo=wx.ComboBox(self,-1,'None',(200,125),wx.DefaultSize,self.label_2_list,wx.CB_DROPDOWN)
self.label_3=wx.StaticText(self,-1,"Number of Servers:",(40,175))
self.label_3_list=['1','2','3','4','5','6','7','8','9','10']
self.label_3_combo=wx.ComboBox(self,-1,'None',(200,175),wx.DefaultSize,self.label_3_list,wx.CB_DROPDOWN)
self.label_4=wx.StaticText(self,-1,"Size of File:",(40,225))
self.label_4_list=['small-files','0to1kb','10kb','20kb','50kb','70kb','100kb','200kb','500kb','700kb','1mb','2mb','video1.2mb','video2.2mb','video2mb','video3mb','allfiles']
self.label_4_combo=wx.ComboBox(self,-1,'None',(200,225),wx.DefaultSize,self.label_4_list,wx.CB_DROPDOWN)
self.label_5=wx.StaticText(self,-1,"RampUpTime(ms):",(40,275))
self.label_5_list=['500','750','1000','2000','5000']
self.label_5_combo=wx.ComboBox(self,-1,'None',(200,275),wx.DefaultSize,self.label_5_list,wx.CB_DROPDOWN)
self.label_6_list=['1minute','5minutes','10minutes','15minutes','30minutes','1hour','2hours','3hours','4hours','5hours','6hours','10hours','12hours','15hours','18hours','24hours','Mode is Request Based']
self.label_6=wx.StaticText(self,-1,"Test Time:",(40,325))
self.label_6_combo=wx.ComboBox(self,-1,'None',(200,325),wx.DefaultSize,self.label_6_list,wx.CB_DROPDOWN)
self.label_7_list=['10000','20000','40000','50000','70000','100000','200000','500000','700000','1000000','Mode is Time Based']
self.label_7=wx.StaticText(self,-1,"Number of Requests:",(40,375))
self.label_7_combo=wx.ComboBox(self,-1,'None',(200,375),wx.DefaultSize,self.label_7_list,wx.CB_DROPDOWN)
self.failed=wx.StaticText(self,-1,"Failed Requests:",(400,25))
self.result=wx.StaticText(self, label="",pos=(525,25))
self.result.SetForegroundColour(wx.RED)
self.scripttime=wx.StaticText(self,-1,"Script_Run_Time:",(400,50))
self.tresult=wx.StaticText(self, label="",pos=(525,75))
self.tresult.SetForegroundColour(wx.RED)
self.ok=wx.Button(self,label="OK",pos=(40,425))
self.ok.Bind(wx.EVT_BUTTON,self.onok)
self.cancle=wx.Button(self,label='Cancle',pos=(140,425))
self.cancle.Bind(wx.EVT_BUTTON,self.oncancle)
self.run=wx.Button(self,label="RUN",pos=(240,425))
self.run.Bind(wx.EVT_BUTTON,self.onrun)
self.cap=wx.Button(self,label="Capture",pos=(340,425))
self.cap.Bind(wx.EVT_BUTTON,self.oncap)
self.testcomplete=wx.Button(self,label="Test Complete",pos=(440,425))
self.testcomplete.Bind(wx.EVT_BUTTON,self.oncomplete)
self.action=self.label_2_combo.GetValue()
self.xmax=len(work.rt) if len(work.rt)>100 else 100
self.xmin=self.xmax-100
self.myfig=mfigure.Figure(dpi=50)
self.axes=self.myfig.add_subplot(111)
self.axes.set_xbound(lower=self.xmin,upper=self.xmax)
self.canvas=FigureCanvas(self,-1,self.myfig)
self.canvas.SetPosition((400,100))
self.toolbar=NavigationToolbar(self.canvas)
self.toolbar.Realize()
self.toolbar.SetPosition((400,75))
tw,th=self.toolbar.GetSizeTuple()
fw,fh=self.canvas.GetSizeTuple()
self.toolbar.SetSize(wx.Size(fw,th))
self.toolbar.update()
self.animator=anim.FuncAnimation(self.myfig,self.animator,interval=1000,repeat=True)
self.SetupScrolling()
def onok(self,event):
self.mode=self.label_0_combo.GetValue()
self.noc=int(self.label_1_combo.GetValue())
work.noc=self.noc
self.action=self.label_2_combo.GetValue()
if (self.action=='Web'):
work.action=Value('i',0)
elif(self.action=='Download'):
work.action=Value('i',1)
elif(self.action=='Video'):
work.action=Value('i',2)
else:
self.label_2=wx.StaticText(self,-1,"Please restart & select proper Action",(40,475))
self.Close()
self.nos=int(self.label_3_combo.GetValue())
work.nos=Value('i',self.nos)
self.filesize=self.label_4_combo.GetValue()
if (self.filesize=='small-files'):
work.low=Value('i',0)
work.high=Value('i',1)
elif (self.filesize=='0to1kb'):
work.low=Value('i',1)
work.high=Value('i',2)
elif (self.filesize=='10kb'):
work.low=Value('i',2)
work.high=Value('i',3)
elif (self.filesize=='20kb'):
work.low=Value('i',3)
work.high=Value('i',4)
elif (self.filesize=='50kb'):
work.low=Value('i',4)
work.high=Value('i',5)
elif (self.filesize=='70kb'):
work.low=Value('i',5)
work.high=Value('i',6)
elif (self.filesize=='100kb'):
work.low=Value('i',6)
work.high=Value('i',7)
elif (self.filesize=='200kb'):
work.low=Value('i',7)
work.high=Value('i',8)
elif (self.filesize=='500kb'):
work.low=Value('i',8)
work.high=Value('i',9)
elif (self.filesize=='700kb'):
work.low=Value('i',9)
work.high=Value('i',10)
elif (self.filesize=='1mb'):
work.low=Value('i',10)
work.high=Value('i',11)
elif (self.filesize=='2mb'):
work.low=Value('i',11)
work.high=Value('i',12)
elif (self.filesize=='video1.2mb'):
work.low=Value('i',12)
work.high=Value('i',13)
elif (self.filesize=='video2.2mb'):
work.low=Value('i',13)
work.high=Value('i',14)
elif (self.filesize=='video2mb'):
work.low=Value('i',14)
work.high=Value('i',15)
elif (self.filesize=='video3mb'):
work.low=Value('i',15)
work.high=Value('i',16)
elif (self.filesize=='allfiles'):
work.low=Value('i',0)
work.high=Value('i',16)
else:
self.label_2=wx.StaticText(self,-1,"Please restart & select proper file size",(40,475))
self.Close()
self.rampuptime=int(self.label_5_combo.GetValue())
work.rampuptime=(self.rampuptime/1000)
self.mytime=self.label_6_combo.GetValue()
if (self.mytime=='1minute'):
self.testtime=60.0
elif (self.mytime=='5minutes'):
self.testtime=300.0
elif (self.mytime=='10minutes'):
self.testtime=600.0
elif (self.mytime=='15minutes'):
self.testtime=900.0
elif (self.mytime=='30minutes'):
self.testtime=1800.0
elif (self.mytime=='1hour'):
self.testtime=3600.0
elif (self.mytime=='2hours'):
self.testtime=7200.0
elif (self.mytime=='3hours'):
self.testtime=10800.0
elif (self.mytime=='4hours'):
self.testtime=14400.0
elif (self.mytime=='5hours'):
self.testtime=18000.0
elif (self.mytime=='6hours'):
self.testtime=21600.0
elif (self.mytime=='10hours'):
self.testtime=36000.0
elif (self.mytime=='12hours'):
self.testtime=43200.0
elif (self.mytime=='15hours'):
self.testtime=54000.0
elif (self.mytime=='18hours'):
self.testtime=64800.0
elif (self.mytime=='24hours'):
self.testtime=86400.0
elif (self.mytime=='Mode is Request Based'):
work.end_time=0
else:
self.label_2=wx.StaticText(self,-1,"Please restart & select proper test time",(40,475))
self.Close()
self.nor=self.label_7_combo.GetValue()
def oncancle(self,event):
sys.exit()
def oncap(self,event):
os.system("gnome-terminal -e 'tcpdump -ni eth0 port 80 -w cap.pcap'")
def onrun(self,event):
time.sleep(1)
self.scriptstart=float(time.time())
self.mode=self.label_0_combo.GetValue()
if (self.mode=='Time Based'):
work.end_time=time.time()+self.testtime
thread.start_new_thread(work.time_func, ())
elif(self.mode=='Request Based'):
work.number_of_requests=int(self.nor)
thread.start_new_thread(work.requests_func, ())
def oncomplete(self,event):
self.label_2=wx.StaticText(self,-1,"All work Done..!! To generate traffic again, Please restart the script ",(40,475))
x=len(work.rt)
y=work.scriptend-self.scriptstart
self.result.SetLabel("Errors=%d/%d"%(work.error_count.value,x))
self.tresult.SetLabel("%f"%y)
def animator(self,i):
self.axes.cla()
self.axes.set_ylabel("Response Time")
self.axes.set_xlabel("Number of Files")
return self.axes.plot(work.rt)
class DemoFrame(wx.Frame):
def __init__ (self):
wx.Frame.__init__(self,None,wx.ID_ANY,"Python_Scripts",size=(800,500))
self.mypanel=TabPanel1(self)
self.SetDoubleBuffered(True)
self.Layout()
self.Centre()
self.Show()
def onexit(self,event):
sys.exit()
if __name__=='__main__':
app=wx.App(False)
frame=DemoFrame()
frame.Show()
app.MainLoop()
Answer: Found the solution, use wx.calllater instead of animating the graph, i.e.
instead of using funcanimation with 1000 millisecond of interval time,first
call the plotting function that simple draws the canvas and then within that
function provide wx.calllater at end that calls itself after every 1000
miliseconds eg.
main_function():
plot_function()
plot_function(self):
<plotting of graph>
wx.CallLater(1000,self.plot_function)
|
OpenERP 6, Aptana - debugger doesn't stop at breakpoint in QR Bar Code Label code
Question: I am trying to debug code for QR Bar Code Labels in OpenERP 6 using Aptana
Studio 3. I put a breakpoint in "pyqr" module, file "myfile.py", function
"generate_image()", as per attached picture:

Now, when I run OpenERP server from Aptana IDE ("openerp-server.py" -> Debug
As -> Python Run) and navigate to Manufacturing Orders where I can click on
one of the right hand buttons "Large Label" or "Medium Label" or "Small
Label", the debugger doesn't stop at the breakpoint and yet the label is
printed in opened PDF file.
I have performed the following tests to check if the code in "myfile.py"
executes. I have put "print" statement in "generate_image()" function, and it
did not print anything in console. I put "import pdb" and "pdb.set_trace()"
and the execution did not stop there. I added a message box in
"generate_image()" function and message box did not display, yet the QR bar
code label was created. It looks like that "myfile.py" code is not executed at
all adding to mystery which code is executed that creates QR Bar Code labels.
How I can make debugger stop at this breakpoint? What am I missing?
Answer: To be able to debug in your IDE, I assume that you are running the Odoo server
from source and start it from inside the IDE.
I'm not sure what is your actual setup, but maybe these pointers can help.
* Try putting the breakpoint on a line of the method, instead of on it's definition.
* Are you sure that the code is being executed? Try placing a `print` statement in it to confirm. Or try adding a `import pdb; pdb.set_trace()` line as a way to force a breakpoint.
|
Drop observations from the data frame in python
Question: How to delete observation from data frame in python. For example, I have data
frame with variables a, b, c in it, and I vat to delete observation if
variable a is missing, or variable c is equal to zero.
Answer: You could build a boolean mask using `isnull`:
mask = (df['a'].isnull()) | (df['c'] == 0)
and then select the desired rows with:
df = df.loc[~mask]
`~mask` is the boolean inverse of `mask`, so `df.loc[~mask]` selects rows
where `a` is not null _and_ `c` is not 0.
* * *
For example,
import numpy as np
import pandas as pd
arr = np.arange(15, dtype='float').reshape(5,3) % 4
arr[arr > 2] = np.nan
df = pd.DataFrame(arr, columns=list('abc'))
# a b c
# 0 0 1 2
# 1 NaN 0 1
# 2 2 NaN 0
# 3 1 2 NaN
# 4 0 1 2
mask = (df['a'].isnull()) | (df['c'] == 0)
df = df.loc[~mask]
yields
a b c
0 0 1 2
3 1 2 NaN
4 0 1 2
|
GMAIL API doesn't accept most queries (GAE Python)
Question: I'm trying to fetch all sent messages for the last 3 months, using a Google
App Engine app on Python. For some reason though it doesn't accept most of the
queries that I enter. It returns results for a simple string, but if I enter
something like "after:2015/01/20", or "newer_than:3m" it gives me the
following error:
AttributeError: 'Resource' object has no attribute 'messages'
I have no clue where this could be coming from. My current code for the
request is:
import webapp2, httplib2
from dateutil.relativedelta import *
from oauth2client.appengine import OAuth2Decorator
from apiclient import discovery, errors
from oauth2client import client
from google.appengine.api import memcache
http = httplib2.Http(memcache)
service = discovery.build("gmail", "v1", http=http)
decorator = OAuth2Decorator(client_id=settings.CLIENT_ID,
client_secret=settings.CLIENT_SECRET,
scope=settings.SCOPE)
class retrieveMessages(webapp2.RequestHandler):
@decorator.oauth_required
def get(self):
try:
user = '[email protected]'
after = (datetime.datetime.now()+relativedelta(months=-3)).strftime("%Y/%m/%d")
query = 'after:'+after
http = decorator.http()
response = service.users().messages().list(userId=user, labelIds='SENT', q=query, maxResults=1000).execute(http=http)
messages = []
if 'messages' in response:
messages.extend(response['messages'])
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId=user, labelIds='SENT', q=query, pageToken=page_token).executehttp=http(http=http)
messages.extend(response['messages'])
return messages
except errors.HttpError, error:
print 'An error occurred: %s' % error
if error.resp.status == 401:
# Credentials have been revoked.
# TODO: Redirect the user to the authorization URL.
raise NotImplementedError()
Answer: Shouldn't this snippet inside the while loop:
response = service.messages()...
be
response = service.users().messages()...
|
Python typeError: can't multiply sequence by non-int of type 'float'
Question: I have this code
a = [0.0, 1.1, 2.2]
b = a * 2.0
and that is where I get the error
typeError: can't multiply sequence by non-int of type 'float'
what I want it to `return` is
b = [0.0, 2.2, 4.4]
Answer: The error is that you are multiplying a list, that is `a` and a float, that is
`2.0`.
Do this instead (a list comprehension)
b = [i*2.0 for i in a]
A small demo
>>> a = [0.0, 1.1, 2.2]
>>> b = [i*2.0 for i in a]
>>> b
[0.0, 2.2, 4.4]
Using `map`
map(lambda x:x*2.0 , a)
Here are the `timeit` results
bhargav@bhargav:~$ python -m timeit "a = [0.0, 1.1, 2.2]; b = [i*2.0 for i in a]"
1000000 loops, best of 3: 0.34 usec per loop
bhargav@bhargav:~$ python -m timeit "a = [0.0, 1.1, 2.2]; b = map(lambda x:x*2.0 , a)"
1000000 loops, best of 3: 0.686 usec per loop
bhargav@bhargav:~$ python -m timeit "import numpy; a = numpy.array([0.0, 1.1, 2.2]); b = a * 2.0"
10 loops, best of 3: 5.51 usec per loop
The list comprehension is the fastest.
|
python pandas : how to control the constraints and indices automatically created by to_sql?
Question: I am using pandas 0.16 and sqlalchemy to export data to a Microsft SQL Server
2014 database. The dataframe to_sql method automatically creates certain
constraints on the table, e.g. it creates a constraint that a boolean column
must be either 0 or 1.
I suspect these constraints are slowing down the export process. Is there a
way to disable them, at least temporarily (i.e. re-enabling them only after
all the data is in SQL)?
Also, is this documented anywhere? I couldn't find any mention of this,
neither in the pandas docs nor in the sqlalchemy.
Answer: The reason `to_sql` writes your boolean data as 0 and 1's, is because _SQL
Server has no boolean data type_ (see eg [Is there Boolean data in sql server
like mysql?](http://stackoverflow.com/questions/3138029/is-there-boolean-data-
in-sql-server-like-mysql)).
In such cases, SQLAlchemy by default adds those constraints to the column, as
is documented in the SQLAlchemy docs:
<http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.Boolean>
Using the possibility of overriding the default type with the `dtype` argument
in `to_sql` (documented [here](http://pandas.pydata.org/pandas-
docs/stable/io.html#sql-data-types)), you can specify to not create this
constraint:
from sqlalchemy.types import Boolean
df.to_sql('name', engine, dtype={'my_bool_col': Boolean(create_constraint=False)})
|
Adding in-between column in csv Python
Question: I work with csv files and it seems python provides a lot of flexibility for
handling csv files.
I found several questions linked to my issue, but I cannot figure out how to
combine the solutions effectively...
My starting point CSV file looks like this (note there is only 1 column in the
'header' row):
FILE1
Z1 20 44 3
Z1 21 44 5
Z1 21 44 8
Z1 22 45 10
What I want to do is add a column in between cols #1 and #2, and keep the rest
unchanged. This new column has the same # rows as the other columns, but
contains the same integer for all entries (10 in my example below). Another
important point is I don't really know the number of rows, so I might have to
count the # rows somehow first (?) My output should then look like:
FILE1
Z1 10 20 44 3
Z1 10 21 44 5
Z1 10 21 44 8
Z1 10 22 45 10
Is there a simple solution to this?
Answer: I think the easiest solution would be to just read each row and write a
corresponding new row (with the inserted value) in a new file:
import csv
with open('input.csv', 'r') as infile:
with open('output.csv', 'w') as outfile:
reader = csv.reader(infile, delimiter=' ')
writer = csv.writer(outfile, delimiter=' ')
for row in reader:
new_row = [row[0], 10]
new_row += row[1:]
writer.writerow(new_row)
This might not make sense if you're not doing anything else with the data
besides this bulk processing, though. You'd' want to look into csv libraries
if that were the case.
|
cannot cast array data when a saved classifier is called
Question: I have created a classifier using <https://gist.github.com/zacstewart/5978000>
example. To train the classifier I am using following code
import os
import numpy
NEWLINE = '\n'
SKIP_FILES = set(['cmds'])
def read_files(path):
for root, dir_names, file_names in os.walk(path):
for path in dir_names:
read_files(os.path.join(root, path))
for file_name in file_names:
if file_name not in SKIP_FILES:
file_path = os.path.join(root, file_name)
if os.path.isfile(file_path):
past_header, lines = False, []
f = open(file_path)
for line in f:
if past_header:
lines.append(line)
elif line == NEWLINE:
past_header = True
f.close()
yield file_path, NEWLINE.join(lines).decode('cp1252', 'ignore')
from pandas import DataFrame
def build_data_frame(path, classification):
data_frame = DataFrame({'text': [], 'class': []})
for file_name, text in read_files(path):
data_frame = data_frame.append(
DataFrame({'text': [text], 'class': [classification]}, index=[file_name]))
return data_frame
HAM = 0
SPAM = 1
SOURCES = [
('data/spam', SPAM),
('data/easy_ham', HAM),
('data/hard_ham', HAM),
('data/beck-s', HAM),
('data/farmer-d', HAM),
('data/kaminski-v', HAM),
('data/kitchen-l', HAM),
('data/lokay-m', HAM),
('data/williams-w3', HAM),
('data/BG', SPAM),
('data/GP', SPAM),
('data/SH', SPAM)
]
data = DataFrame({'text': [], 'class': []})
for path, classification in SOURCES:
data = data.append(build_data_frame(path, classification))
data = data.reindex(numpy.random.permutation(data.index))
import numpy
from sklearn.feature_extraction.text import CountVectorizer
count_vectorizer = CountVectorizer()
counts = count_vectorizer.fit_transform(numpy.asarray(data['text']))
from sklearn.naive_bayes import MultinomialNB
classifier = MultinomialNB()
targets = numpy.asarray(data['class'])
clf = classifier.fit(counts, targets)
from sklearn.externals import joblib
joblib.dump(clf, 'my_trained_data.pkl', compress=9)
If i test an example in this file then it works correctly. But i am trying to
save the classifier to my_trained_data.pkl then call it ass following
from sklearn.externals import joblib
clf = joblib.load('my_trained_data.pkl')
examples = ['Free Viagra call today!', "I'm going to attend the Linux users group tomorrow."]
predictions = clf.predict(examples)
This give following error.
TypeError: Cannot cast array data from dtype('float64') to dtype('S32') according to the rule 'safe'
Following is the trace
In [12]: runfile('/home/harpreet/Machine_learning/untitled0.py', wdir='/home/harpreet/Machine_learning') MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True) Traceback (most recent call last):
File "<ipython-input-12-521f3ed1e6da>", line 1, in <module>
runfile('/home/harpreet/Machine_learning/untitled0.py', wdir='/home/harpreet/Machine_learning')
File "/home/harpreet/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "/home/harpreet/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
builtins.execfile(filename, *where)
File "/home/harpreet/Machine_learning/untitled0.py", line 13, in <module>
clf.predict(examples)
File "/home/harpreet/anaconda/lib/python2.7/site-packages/sklearn/naive_bayes.py", line 62, in predict
jll = self._joint_log_likelihood(X)
File "/home/harpreet/anaconda/lib/python2.7/site-packages/sklearn/naive_bayes.py", line 441, in _joint_log_likelihood
return (safe_sparse_dot(X, self.feature_log_prob_.T)
File "/home/harpreet/anaconda/lib/python2.7/site-packages/sklearn/utils/extmath.py", line 180, in safe_sparse_dot
return fast_dot(a, b)
TypeError: Cannot cast array data from dtype('float64') to dtype('S32') according to the rule 'safe'
Answer: You need to transform the test document with the same `vectorizer` instance:
examples_vectors = count_vectorizer.transform(examples)
clf.predict(examples_vectors)
In general it's easier to use a pipeline:
from sklearn.pipeline import make_pipeline
pipeline = make_pipeline(CountVectorizer(), MultinomialNB())
pipeline.fit(data['text'].values, data['class'].values)
then later:
pipeline.predict(examples)
|
Basic Docopt Example does not work
Question: So, I'm trying to run `odd_even_example.py` from the [docopt examples git
repo](https://github.com/docopt/docopt/blob/master/examples/odd_even_example.py).
No matter what I try to do, or change, the example won't work as expected.
When I:
python odd_even_example.py 1 2 3 4
I expect to see a dictionary with the command line options or arguments I
passed. But instead I just get the `__doc__` string over and over again.
I'm confused because I just copied and ran the file verbatim from the examples
repo, and it's straight up broken.
This is the content of the file:
"""Usage: odd_even_example.py [-h | --help] (ODD EVEN)...
Example, try:
odd_even_example.py 1 2 3 4
Options:
-h, --help
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__)
print(arguments)
Answer: I had the same problem, and I think the problem is with whether or not you are
entering something for the `(ODD EVEN)` portion of the command. I played with
it a bit and still don't understand how exactly that is meant to work, but
here is an example that works like you expect. It takes one or more numbers as
input, and prints the results to stdout.
"""Usage: odd_even_example.py [-h | --help] (NUMBERS)...
Example, try:
odd_even_example.py 1 2 3 4
Options:
-h, --help
"""
from docopt import docopt
def is_even(x):
xIsEven = x%2 == 0
if xIsEven:
return 'EVEN'
else:
return 'ODD'
if __name__ == '__main__':
arguments = docopt(__doc__) # returns a dictionary
print(arguments)
numbers_entered = [int(i) for i in arguments['NUMBERS']]
answers = [is_even(x) for x in numbers_entered]
print(answers)
|
Convert VTK to raster image (Ruby or Python)
Question: I have the results of a simulation on an unstructured 2D mesh. I usually
export the results in VTK and visualize them with Paraview. This is what
results look like.

I would like to obtain a raster image from the results (with or without
interpolation) to use it as a texture for visualization in a 3D software. From
reading around I have gathered that I need to do some kind of resampling in
order to convert from the unstructured grid to a 2d regular grid for the
raster image.
VTK can export to raster, but it exports only a full scene without any defined
boundary so it requires manual tweaking to fit the image.
Ideally I would like to export only the results within the results bounding
box and 'map' them to a raster image programmatically with Ruby or Python.
Answer: This script uses paraview and creates an image perfectly centered and scaled
so that it can be used as a texture. Notice the `855` value for the vertical
size. It seems to be related to the resolution of the screen and it is needed
only on OSX according to Paraview mailing list.
It should be run to the Paraview Python interpreter `pvbatch`.
import sys, json
#### import the simple module from the paraview
from paraview.simple import *
#### disable automatic camera reset on 'Show'
paraview.simple._DisableFirstRenderCameraReset()
args = json.loads(sys.argv[1])
# create a new 'Legacy VTK Reader'
vtk_file = args["file"]
data = LegacyVTKReader(FileNames=[vtk_file])
# get active view
renderView1 = GetActiveViewOrCreate('RenderView')
# uncomment following to set a specific view size
xc = float(args["center"][0])
yc = float(args["center"][1])
zc = float(args["center"][2])
width = float(args["width"])
height = float(args["height"])
output_file = args["output_file"]
scalar = args["scalar"]
colormap_min = float(args["colormap_min"])
colormap_max = float(args["colormap_max"])
ratio = height / width
magnification = 2
height_p = 855 * magnification
width_p = int(height_p * 1.0 / ratio / magnification)
renderView1.ViewSize = [width_p , height_p]
# show data in view
dataDisplay = Show(data, renderView1)
# trace defaults for the display properties.
dataDisplay.ColorArrayName = ['CELLS', scalar]
# set scalar coloring
ColorBy(dataDisplay, ('CELLS', scalar))
# rescale color and/or opacity maps used to include current data range
dataDisplay.RescaleTransferFunctionToDataRange(True)
# get color transfer function/color map for 'irradiation'
irradiationLUT = GetColorTransferFunction(scalar)
# Rescale transfer function
irradiationLUT.RescaleTransferFunction(colormap_min, colormap_max)
irradiationLUT.LockDataRange = 1
irradiationLUT.ColorSpace = 'RGB'
irradiationLUT.NanColor = [0.498039, 0.0, 0.0]
#changing interaction mode based on data extents
renderView1.InteractionMode = '2D'
renderView1.CameraPosition = [xc, yc, 10000.0 + zc]
renderView1.CameraFocalPoint = [xc, yc, zc]
# hide color bar/color legend
dataDisplay.SetScalarBarVisibility(renderView1, False)
# current camera placement for renderView1
renderView1.InteractionMode = '2D'
#renderView1.CameraPosition = [3.641002, 197.944122, 10001.75]
#renderView1.CameraFocalPoint = [3.641002, 197.944122, 1.75]
renderView1.CameraParallelScale = (height / 2.0)
# save screenshot
SaveScreenshot(output_file, magnification=magnification, quality=100, view=renderView1)
|
XML Prettifying from file in Python
Question: I have an xml file which looks like the example below.
Many texts contain space as the start character, or have `\n` (newline) at the
beginning, or other crazy stuff. I'm working with `xml.etree.ElementTree`, and
it is good to parse from this file.
But I want more! :) I tried to prettify this mess, but without success. Tried
many tutorials, but it always ends without pretty XML.
<?xml version="1.0"?>
<import>
<article>
<name> Name with space
</name>
<source> Daily Telegraph
</source>
<number>72/2015
</number>
<page>10
</page>
<date>2015-03-26
</date>
<author> Tomas First
</author>
<description>Economy
</description>
<attachment>
</attachment>
<region>
</region>
<text>
My text is here
</text>
</article>
<article>
<name> How to parse
</name>
<source> Internet article
</source>
<number>72/2015
</number>
<page>1
</page>
<date>2015-03-26
</date>
<author>Some author
</author>
<description> description
</description>
<attachment>
</attachment>
<region>
</region>
<text>
My text here
</text>
</article>
</import>
When I tried another answers from SO it generates same file or more messy XML
Answer: [`bs4`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#) can do it
from bs4 import BeautifulSoup
doc = BeautifulSoup(xmlstring, 'xml')
print doc.prettify()
|
Evaluating K means clustering using python
Question: I have a data set slightly similar like this:

I have performed **K means clustering** using this code:
from scipy.cluster.vq import kmeans, vq
data=np.matrix(dataAll.ix[:,:-1])
centers, _ = kmeans(data, 3, iter=100)
cluster, _ = vq(data, centers)
In here I want to ask how to evaluate **k means clustering**. I want to get
value such as precision, accuracy, **f measure**.
Answer: If you have the Gold standard/Ground truth values, you can use my code
[**[Link](https://sutanto.org/pairwise-fscore-nmi/)**] to calculate pairwise
precision, recall, FScore & NMI.
Notes, that the article is in Indonesian language, but don't worry you can
skip all of the explanations and go straight to the code at the bottom of the
article. [I wrote Matlab & Python implementation] The python code is a fork of
**[this work](http://eprints.qut.edu.au/60711/)** that is available
**[here](http://greententacle.techfak.uni-
bielefeld.de/reseed/reseed_eval.py)**.
|
win 8.1 cygwin - pip is installing into windows python directory?
Question: I have recently just started the foray into running cygwin on windows.
Attempting to setup a development environment, and noticing some oddities. so
for example, I have installed virtualenvwrapper but when i open a new cygwin
terminal i get (after setting appropriate lines in my .bashrc)
-bash: /usr/local/bin/virtualenvwrapper.sh: No such file or directory
so i attempt to reinstall virtualenvwrapper using pip and i get
$ pip install virtualenvwrapper
Requirement already satisfied (use --upgrade to upgrade): virtualenvwrapper in c:\python27\lib\site-packages
Requirement already satisfied (use --upgrade to upgrade): virtualenv in c:\python27\lib\site-packages (from virtualenvwrapper)
Requirement already satisfied (use --upgrade to upgrade): virtualenv-clone in c:\python27\lib\site-packages (from virtualenvwrapper)
Requirement already satisfied (use --upgrade to upgrade): stevedore in c:\python27\lib\site-packages (from virtualenvwrapper)
Requirement already satisfied (use --upgrade to upgrade): argparse in c:\python27\lib\site-packages (from stevedore->virtualenvwrapper)
Requirement already satisfied (use --upgrade to upgrade): six>=1.9.0 in c:\python27\lib\site-packages (from stevedore->virtualenvwrapper)
Requirement already satisfied (use --upgrade to upgrade): pbr!=0.7,<1.0,>=0.6 in c:\python27\lib\site-packages (from stevedore->virtualenvwrapper)
Requirement already satisfied (use --upgrade to upgrade): pip in c:\python27\lib\site-packages (from pbr!=0.7,<1.0,>=0.6->stevedore->virtualenvwrapper)
What gives? why is it installing it to the windows directory? sure enough i
can see virtualenvwrapper is not installed in c:/cygwin64/lib/Python2.7/site-
packages/ in fact that directory is completely bare. I expected to see the
updated version of pip i installed. it's of course in the windows directory.
**I had previously installed virtualenvwrapper via pip on windows, but my
understanding is that the windows environment and the cygwin terminal are
totally seperate and shouldn't know about each other(?)**
as you might expect this is also wrecking havoc with other packages. for
example attempting to install uwsgi i get this error:
Collecting uWSGI==2.0.7 (from -r _pip/requirements.txt (line 52))
Downloading uwsgi-2.0.7.tar.gz (772kB)
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "c:\cygwin64\tmp\pip-build-n5cvur\uWSGI\setup.py", line 3, in <module>
import uwsgiconfig as uc
File "uwsgiconfig.py", line 8, in <module>
uwsgi_os = os.uname()[0]
AttributeError: 'module' object has no attribute 'uname'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in c:\cygwin64\tmp\pip-build-n5cvur\uWSGI
which i understand is because os.uname doesn't exist on windows. Why is the
pip installer running setup using windows python?
\------- update -------
I think i found the root cause
$ which pip
/c/Python27/Scripts/pip
so my questions are: **why is pip the windows one by default? or how did this
happen?**
\-------- Update 2 ----------
i just discovered that the default PATH env variable in cygwin appends the
windows one. sure enough the path to the windows pip is there.
$ echo $PATH
**Is this expected? if so, why is this desireable?** doesn't it increase the
chance of unintentional conflicts like this one?
Answer: So I'll just leave this here as a warning to n00bs like myself.
cygwin appends the windows path to the cygwin terminal PATH env variable.
if you already have pip installed on windows and it is on your path it will
work but with unexpected results like above.
to check make sure you do
which python
which pip
to confirm what version you are running.
only python 2.7.9 and up include pip by default and the package included in
cygwin isn't there yet. so you will most likely need to install pip manually
if you had a cygwin terminal open, you will need to close all windows
otherwise it remembers the path to the windows pip.
|
How to call a function only Once in Python
Question: here I want to call web service function only once throughout the program. how
to accomplish this anybody suggest me
import sys,os
def web_service(macid):
# do something
if "__name__" = "__main__" :
web_service(macid)
Answer: You can use a decorator.
def run_once(f):
def wrapper(*args, **kwargs):
if not wrapper.has_run:
wrapper.has_run = True
return f(*args, **kwargs)
wrapper.has_run = False
return wrapper
@run_once
def web_service(macid):
return doSomething
Now `web_service` will only run once. Other calls to it will return `None`.
Just add an `else` clause to the `if` if you want it to return something else.
From your example, it doesn't need to return anything, ever.
If you don't control the creation of the function, or the function needs to be
used normally in other contexts, you can just apply the decorator manually as
well:
action = run_once(web_service)
while True:
if predicate:
action()
This will leave `web_service` available for other uses.
Finally, if you need to only run it once twice, then you can just do this:
action = run_once(web_service)
action() # run once the first time
action.has_run = False
action() # run once the second time
|
wxpython: adding rows to wxgrid dynamically does not fit to panel
Question: I have a wxgrid inside a resizable scrollable panel. I dynamically
add/hide/show rows in wxgrid. When I try to add/show more rows in wxgrid, it
does not fit to the available space in panel but instead occupies a small area
it had been occupying previously with a scrollbar for wxgrid.
Like this:

But after I resize the panel or frame, then it fits perfectly. Like this:

How can I make it to fit properly without needing to resize the panel?
I have tried all combinations of wx.EXPAND, wx.GROW, wx.ALL while adding grid
to sizer and also tried gridobj.Layout() Nothing works. Any Ideas?
Iam using wx 3.0 with python 2.7 on windows 7
Edit: Here's my code
controls.py
import wx
import wx.grid
import wx.combo
class SimpleGrid(wx.grid.Grid):
def __init__(self, parent):
wx.grid.Grid.__init__(self, parent, -1)
self.CreateGrid(10, 5)
for i in range(10):
self.SetRowLabelValue(i,str(i))
class ListCtrlComboPopup(wx.ListCtrl, wx.combo.ComboPopup):
def __init__(self,parent):
self.gfobj = parent
self.PostCreate(wx.PreListCtrl())
self.parent = parent
wx.combo.ComboPopup.__init__(self)
def AddItem(self, txt):
self.InsertStringItem(self.GetItemCount(), txt)
self.Select(0)
def GetSelectedItems(self):
del self.gfobj.selection[:]
current = -1
while True:
next = self.GetNextSelected(current)
if next == -1:
return
self.gfobj.selection.append(next)
current = next
def onItemSelected(self, event):
item = event.GetItem()
self.GetSelectedItems()
self.parent.draw_plot()
def onItemDeSelected(self, event):
self.GetSelectedItems()
self.parent.draw_plot()
def Init(self):
""" This is called immediately after construction finishes. You can
use self.GetCombo if needed to get to the ComboCtrl instance. """
self.value = -1
self.curitem = -1
def Create(self, parent):
""" Create the popup child control. Return True for success. """
wx.ListCtrl.Create(self, parent,
style=wx.LC_LIST|wx.SIMPLE_BORDER)
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onItemSelected)
self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.onItemDeSelected)
return True
def GetControl(self):
""" Return the widget that is to be used for the popup. """
return self
def SetStringValue(self, val):
""" Called just prior to displaying the popup, you can use it to
'select' the current item. """
idx = self.FindItem(-1, val)
if idx != wx.NOT_FOUND:
self.Select(idx)
def GetStringValue(self):
""" Return a string representation of the current item. """
a = self.GetItemText(self.value)
if self.value >= 0:
return a
return ""
def OnPopup(self):
""" Called immediately after the popup is shown. """
self.state = []
for i in range(self.GetItemCount()):
item = self.GetItem(itemId=i)
self.state.append(item.GetState())
#print self.state
wx.combo.ComboPopup.OnPopup(self)
def OnDismiss(self):
" Called when popup is dismissed. """
wx.combo.ComboPopup.OnDismiss(self)
main.py
import wx
import wx.lib.scrolledpanel
from controls import SimpleGrid
from controls import ListCtrlComboPopup
class GraphFrame(wx.Frame):
title = 'Demo: Data Trending Tool'
def __init__(self):
self.selection = []
self.displaySize = wx.DisplaySize()
wx.Frame.__init__(self, None, -1, self.title,
style = wx.DEFAULT_FRAME_STYLE,
size = (self.displaySize[0]/2, self.displaySize[1]/2))
self.containingpanel = wx.Panel(self, -1)
self.toppanel = wx.Panel(self, -1)
self.splittedwin = wx.SplitterWindow(self.containingpanel, wx.ID_ANY, style=wx.SP_3D | wx.SP_BORDER)
self.splittedwin.SetMinimumPaneSize(20)
self.gridpanel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
self.panel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
#### GRID
self.grid = SimpleGrid(self.gridpanel)
self.gridpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
self.gridpanelsizer.Add(self.grid, wx.GROW)
self.gridpanel.SetSizer(self.gridpanelsizer)
self.gridpanelsizer.Fit(self)
#### COMBOBOX
self.cc = wx.combo.ComboCtrl(self.toppanel, style=wx.CB_READONLY, size=(200,-1), )
self.cc.SetPopupMaxHeight(140)
popup = ListCtrlComboPopup(self)
self.cc.SetPopupControl(popup)
self.cc.SetText("--select--")
# Add some items to the listctrl
for i in range(10):
popup.AddItem(str(i))
#### SIZER FOR COMBOBOX
self.cbpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
self.cbpanelsizer.Add(self.cc, border = 5,flag = wx.LEFT)
self.toppanel.SetSizer(self.cbpanelsizer)
self.splittedwin.SplitHorizontally(self.gridpanel,self.panel,100)
##### SIZER FOR CONTAININGPANEL
self.cpsizer = wx.BoxSizer(wx.VERTICAL)
self.cpsizer.Add(self.splittedwin, 1, wx.EXPAND, 0)
self.containingpanel.SetSizer(self.cpsizer)
self.cpsizer.Fit(self.containingpanel)
mainsizer = wx.BoxSizer(wx.VERTICAL)
mainsizer.Add(self.toppanel, 0, wx.EXPAND)
mainsizer.Add(self.containingpanel, 1, wx.EXPAND)
self.SetSizerAndFit(mainsizer)
self.panel.SetAutoLayout(1)
self.panel.SetupScrolling()
self.gridpanel.SetAutoLayout(1)
self.gridpanel.SetupScrolling()
self.draw_plot()
def draw_plot(self):
for i in range(10):
if i in self.selection:
self.grid.ShowRow(i)
else:
self.grid.HideRow(i)
self.Layout()
#self.gridpanel.Layout()
if __name__ == "__main__":
app = wx.PySimpleApp()
app.frame = GraphFrame()
app.frame.Show()
app.MainLoop()
To simulate: 1\. run main.py It displays a splitted window with a grid with
single row in one panel.
2. Use the drop down to select more than one item (hold ctrl and select)
3. The wxgrid is cramped to one row space with a wxgrid scrollbar
4. Resize the panel using the splitter or resize the window. Now all the selected rows appear as required.
Answer: A great tool to debug this is the WIT
(<http://wiki.wxpython.org/Widget%20Inspection%20Tool>)
With your corrected code I can get it to grow by forcing the sash position,
not ideal, but it shows that the 'problem' is with the splitter.
import wx
import wx.lib.scrolledpanel
from controls import SimpleGrid
from controls import ListCtrlComboPopup
class GraphFrame(wx.Frame):
title = 'Demo: Data Trending Tool'
def __init__(self):
self.selection = []
self.displaySize = wx.DisplaySize()
wx.Frame.__init__(self, None, -1, self.title,
style = wx.DEFAULT_FRAME_STYLE,
size = (self.displaySize[0]/2, self.displaySize[1]/2))
self.containingpanel = wx.Panel(self, -1)
self.toppanel = wx.Panel(self, -1)
self.splittedwin = wx.SplitterWindow(self.containingpanel, wx.ID_ANY, style=wx.SP_3D | wx.SP_BORDER)
self.splittedwin.SetMinimumPaneSize(20)
self.gridpanel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
self.panel = wx.lib.scrolledpanel.ScrolledPanel(self.splittedwin,-1, style = wx.SUNKEN_BORDER)
#### GRID
self.grid = SimpleGrid(self.gridpanel)
self.gridpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
self.gridpanelsizer.Add(self.grid, wx.GROW)
self.gridpanel.SetSizer(self.gridpanelsizer)
self.gridpanelsizer.Fit(self)
#### COMBOBOX
self.cc = wx.combo.ComboCtrl(self.toppanel, style=wx.CB_READONLY, size=(200,-1), )
self.cc.SetPopupMaxHeight(140)
popup = ListCtrlComboPopup(self)
self.cc.SetPopupControl(popup)
self.cc.SetText("--select--")
# Add some items to the listctrl
for i in range(10):
popup.AddItem(str(i))
#### SIZER FOR COMBOBOX
self.cbpanelsizer= wx.BoxSizer(wx.HORIZONTAL)
self.cbpanelsizer.Add(self.cc, border = 5,flag = wx.LEFT)
self.toppanel.SetSizer(self.cbpanelsizer)
self.splittedwin.SplitHorizontally(self.gridpanel, self.panel, 50)
##### SIZER FOR CONTAININGPANEL
self.cpsizer = wx.BoxSizer(wx.VERTICAL)
self.cpsizer.Add(self.splittedwin, 1, wx.EXPAND, 0)
self.containingpanel.SetSizer(self.cpsizer)
mainsizer = wx.BoxSizer(wx.VERTICAL)
mainsizer.Add(self.toppanel, 0, wx.EXPAND)
mainsizer.Add(self.containingpanel, 1, wx.EXPAND)
self.SetSizer(mainsizer)
self.panel.SetupScrolling()
self.gridpanel.SetupScrolling()
self.draw_plot()
def draw_plot(self):
for i in range(10):
if i in self.selection:
self.grid.ShowRow(i)
else:
self.grid.HideRow(i)
s = self.grid.GetBestSize()
print(s)
self.splittedwin.SetSashPosition(s[1])
if __name__ == "__main__":
from wx.lib.mixins.inspection import InspectableApp
app = InspectableApp()
app.frame = GraphFrame()
app.frame.Show()
app.MainLoop()
|
Installing Sci Kit Learn on Mac OSX
Question: On my OSX laptop I have installed Sci Kit Learn by copying and pasting this
command `pip install -U numpy scipy scikit-learn` to terminal as instructed on
[this](http://scikit-learn.org/stable/install.html#mac-osx) page.
This is the result I get when I run the command on terminal again:
Requirement already up-to-date: numpy in /usr/local/lib/python2.7/site- packages
Requirement already up-to-date: scipy in /usr/local/lib/python2.7/site-packages
Requirement already up-to-date: scikit-learn in /usr/local/lib/python2.7/site-packages
Cleaning up...
This is the error message I get when I run `from sklearn import datasets` on
Python 3.3.4. IDLE: (I was trying [this](http://scikit-
learn.org/dev/tutorial/basic/tutorial.html#loading-an-example-dataset)
example)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
from sklearn import dataset
ImportError: No module named 'sklearn'
What is the issue here?
Answer: You have the packages installed for python 2.7 as you can see in the log
Requirement already up-to-date: numpy in /usr/local/lib/python2.7/site-packages
and you're running with python 3.3.4.
So either run it with python 2.7.x or install the packages for python3.x. How?
Check [here](http://stackoverflow.com/questions/10763440/how-to-install-
python3-version-of-package-via-pip-on-ubuntu)
|
python get substring from regex
Question: I want to extract a substring from a string, which is conform to a certain
regex. The regex is:
`(\[\s*(\d)+ byte(s)?\s*\](\s*|\d|[A-F]|[a-f])+)`
Which effectively means that all of these strings get accepted:
[4 bytes] 66 74 79 70 33 67 70 35
[ 4 bytes ] 66 74 79 70 33 67 70 35
[1 byte] 66 74 79 70 33 67 70 35
I want to extract only the amount of bytes (just the number) from this string.
I thought of doing this with `re.search`, but I'm not sure if that will work.
What would be the cleanest and most performant way of doing this?
Answer: Use [`match.group`](https://docs.python.org/3/library/re.html#re.match.group)
to get the groups your regular expression defines:
import re
s = """[4 bytes] 66 74 79 70 33 67 70 35
[ 4 bytes ] 66 74 79 70 33 67 70 35
[1 byte] 66 74 79 70 33 67 70 35"""
r = re.compile(r"(\[\s*(\d)+ byte(s)?\s*\](\s*|\d|[A-F]|[a-f])+)")
for line in s.split("\n"):
m = r.match(line)
if m:
print(m.group(2))
The first group matches `[4 bytes]`, the second only `4`.
Output:
4
4
1
|
python how to use mailchimp to send email
Question: I have been reading a lot on internet to know how can i use python to send
emails using mailchimp api
it seems that the website is so complected and doesn't have any example,
please could you guide me to any example to use pytyon
### what I tried
i installed the library from pip using
pip install mailchimp
i have created the campain
i have created the lists
but yet i couldn't know how to send the emails programmatically
Answer: If you want to trigger a campaign see:
<https://apidocs.mailchimp.com/api/2.0/campaigns/send.php>
The typical module `mailchimp` at pypi supports it as followed.
from mailchimp import Mailchimp
mailchimp = Mailchimp(api_key)
mailchimp.campaigns.send(campaign_id)
Sourcecode at: <https://bitbucket.org/mailchimp/mailchimp-api-
python/src/32ed2394d6b49d7551089484221fa3ee019bee37/mailchimp.py?at=master>
Hope it helps.
Cheers, mrcrgl
|
Erase some lines in json file
Question: **_i have a json file:_**

i want to erase some line in this file **_like this:_**

how can i do this with a python script ..?
Answer:
import json
data = json.loads(open("input.json").read())
with open("output.json", "w") as outfile:
json.dump(data["Stock"]["Vehicule"], outfile)
|
Image convolution at specific points
Question: Is there a way in scipy (or other similar library) to get the convolution of
an image with a given kernel only at some desired points?
I'm looking for something like:
ndimage.convolve(image, kernel, mask=mask)
Where `mask` contains `True` (or `1`) whenever the kernel needs to be applied,
`False` (or `0`) otherwise.
EDIT: Example python code that does what I'm trying to do (but not faster than
a whole image convolution using scipy):
def kernel_responses(im, kernel, mask=None, flatten=True):
if mask is None:
mask = np.ones(im.shape[:2], dtype=np.bool)
ks = kernel.shape[0]//2
data = np.pad(im, ks, mode='reflect')
y, x = np.where(mask)
responses = np.empty(y.shape[0], float)
for k, (i, j) in enumerate(zip(y, x)):
responses[k] = (data[i:i+ks*2+1, j:j+ks*2+1] * kernel).sum()
if flatten:
return responses
result = np.zeros(im.shape[:2], dtype=float)
result[y, x] = responses
return result
The above code does the job with a `wrap` boundary conditions, but the inner
loop is in python, and thus, slow. I was wondering if there is something
faster already implemented in `scipy`/`opencv`/`skimage`.
Answer: I don't know of any function that does exactly what you're asking. If instead
of providing a mask of points to be convolved you provided a list of points
ex. `[(7, 7), (100, 100)]` then it might be as simple as getting the
appropriate image patch (say the same size as your provided kernel), convolve
the image patch and kernel, and insert back into the original image.
Here's a coded example, hopefully it's close enough for you to modify lightly:
[**EDIT** : I noticed a couple errors I had in my padding and patch
arithmetic. Previously, you could not convolve with a point right on the
boarder (say (0, 0)), I doubled the padding, fixed some arithmetic, and now
all is well.]
import cv2
import numpy as np
from scipy import ndimage
from matplotlib import pyplot as plt
def image_convolve_mask(image, list_points, kernel):
# list_points ex. [(7, 7), (100, 100)]
# assuming kernels of dims 2n+1 x 2n+1
rows, cols = image.shape
k_rows, k_cols = kernel.shape
r_pad = int(k_rows/2)
c_pad = int(k_cols/2)
# zero-pad the image in case desired point is close to border
padded_image = np.zeros((rows + 2*k_rows, cols + 2*k_cols))
# set the original image in the center
padded_image[k_rows: rows + k_rows, k_cols: cols + k_cols] = image
# should you prefer to use np.pad:
# padded_image = np.pad(image, (k_rows, k_cols), 'constant', constant_values=(0, 0))
for p in list_points:
# extract pertinent patch from image
# arbitrarily choosing the patch as same size as the kernel; change as needed
patch = padded_image[p[0] + k_rows - r_pad: p[0] + 2*k_rows - r_pad, p[1] + k_cols - c_pad: p[1] + 2*k_cols - c_pad]
# here use whatever function for convolution; I prefer cv2filter2D()
# commented out is another option
# conv = ndimage.convolve(patch, kernel, mode='constant', cval=0.0)
conv = cv2.filter2D(patch, -1, kernel)
# set the convolved patch back in to the image
padded_image[p[0] + k_rows - r_pad: p[0] + 2*k_rows - r_pad, p[1] + k_cols - c_pad: p[1] + 2*k_cols - c_pad] = conv
return padded_image[k_rows: rows + k_rows, k_cols: cols + k_cols]
Now to try it out on an image:
penguins = cv2.imread('penguins.png', 0)
kernel = np.ones((5,5),np.float32)/25
# kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], np.float32)
conv_image = image_convolve_mask(penguins, [(7, 7), (36, 192), (48, 207)], kernel)
plt.imshow(conv_image, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])
plt.show()
I applied a 5x5 box smoother and can't really see any change around pixel (7,
7), but I chose the other two points to be the tips of the two left-most
penguin's beaks. So you can see the smoothed patches.  
Here is a lena512 image with 21 convolution points (time:0.006177 sec).

[**EDIT 2** : An example of using a mask to generate a list of row, col tuples
to feed in to the function.]
mask = np.eye(512)
k = np.ones((25, 25), np.float32)/625
list_mask = zip(np.where(mask==1)[0], np.where(mask==1)[1])
tic = time.time()
conv_image = image_convolve_mask(lena, list_mask, k)
print 'time: ', time.time()-tic # 0.08136 sec

|
Python 2.7 TypeError: 'file' object has no attribute '__getitem__'
Question: not sure why my statement is giving me this error. I am trying to open a file
that the user enters the path.
import csv
f = open(raw_input('Enter file path: '),'r')[1:-1]
Answer: This should be enough to open the file:
f = open('workfile', 'w')
If you want to read a part of the file you should let is read line by line
after is opened.
You don't need the [1:-1]
for line in f:
print line
|
PyDev: Can't compile after accidentally naming file after Python io.py
Question: So I without thinking stupidly named a file io.py in my working directory.
When I tried to compile I got a traceback error. Having realised what I'd done
I renamed my file and updated references to it but I still get the following
error:
Traceback (most recent call last):
File "C:\Users\Tom\workspace\Converter\get_file.py", line 9, in <module>
from scipy import complex_
File "C:\Python27\lib\site-packages\scipy\__init__.py", line 70, in <module>
from numpy import show_config as show_numpy_config
File "C:\Python27\lib\site-packages\numpy\__init__.py", line 185, in <module>
from . import add_newdocs
File "C:\Python27\lib\site-packages\numpy\add_newdocs.py", line 13, in <module>
from numpy.lib import add_newdoc
File "C:\Python27\lib\site-packages\numpy\lib\__init__.py", line 8, in <module>
from .type_check import *
File "C:\Python27\lib\site-packages\numpy\lib\type_check.py", line 11, in <module>
import numpy.core.numeric as _nx
File "C:\Python27\lib\site-packages\numpy\core\__init__.py", line 46, in <module>
from numpy.testing import Tester
File "C:\Python27\lib\site-packages\numpy\testing\__init__.py", line 13, in <module>
from .utils import *
File "C:\Python27\lib\site-packages\numpy\testing\utils.py", line 15, in <module>
from tempfile import mkdtemp
File "C:\Python27\lib\tempfile.py", line 32, in <module>
import io as _io
File "C:\Users\Tom\workspace\Converter\io.py", line 1, in <module>
"""The io module provides the Python interfaces to stream handling. The
File "C:\Users\Tom\workspace\Converter\get_file.py", line 9, in <module>
from scipy import complex_
ImportError: cannot import name complex_
I have restarted PyDev to no avail. I have refreshed the interpreter to no
avail.
I have followed the instructions found in [this Python
issue](http://bugs.python.org/issue22967) but that command returns the correct
result on my machine.
Is tempfile.py a temporary file I can remove to resolve this issue?
Answer: I have found the solution. Stupidly simple but maybe worth leaving here for
other newbies who fall into the same trap.
PyDev compiles the code into *.pyc files. When you update the references and
rename the files these aren't immediately recompiled. Deleting the io.pyc file
I had allowed compilation too run properly.
I found some [more info on common pitfalls](http://python-
notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html) too.
|
Python Sqlite3 Database Error
Question: I am trying to run a program to put prices into the database but when I try to
write to the database I get an error. I'm using Python3.4 and I have sqlite
version 3.7.14.1
import sqlite3
con = sqlite3.connect('/../../stocks.db')
cur = con.cursor()
cur.execute("insert into apple values (?,?)",(price,time))
con.commit()
#error
cur.execute("insert into apple values (?,?)",(price,time))
sqlite3.DatabaseError: file is encrypted or is not a database
Answer: Try replacing `con = sqlite3.connect('/../../stocks.db')`
with
con = sqlite3.connect('../../stocks.db')
or with the correct path to stocks.db
In `con = sqlite3.connect('/../../stocks.db')`, `/` as the first character of
a path means the root directory, and from `/` the parent `..` is also the root
directory `/`
So `/../../stocks.db` is `/stocks.db` which is probably not where the
stocks.db actually is, if you meant a relative path.
When a db file does not exist, sqlite3 will still try to open it as a new
database _if file permissions permit_. However, in this case the user probably
doesn't have permission to write to the root directory at `/stocks.db`
|
Scrapy reverses order of arguments in url Python
Question: I'm running a scraper to crawl from <http://www.johnlscott.com/agent-
search.aspx> to the office rosters.
The office roster addresses look like this: [http://www.johnlscott.com/agent-
search.aspx?p=agentResults.asp&OfficeID=8627](http://www.johnlscott.com/agent-
search.aspx?p=agentResults.asp&OfficeID=8627) \- but Scrapy crawls
[http://www.johnlscott.com/agent-
search.aspx?OfficeID=8627&p=agentResults.asp](http://www.johnlscott.com/agent-
search.aspx?OfficeID=8627&p=agentResults.asp) which is a dead page. **The two
parts after .aspx are swapped.**
I even went so far as to manually load every single address explicitly as
start_urls, and it still happens.
I'm using the most recent Scrapy on python-2.7, Windows 8.1
Code Sample:
class JLSSpider(CrawlSpider):
name = 'JLS'
allowed_domains = ['johnlscott.com']
# start_urls = ['http://www.johnlscott.com/agent-search.aspx']
rules = (
Rule(callback="parse_start_url", follow=True),)
def start_requests(self):
with open('hrefnums.csv', 'rbU') as ifile:
read = csv.reader(ifile)
for row in read:
for col in row:
# I have a csv of the office IDs: (Just letting it crawl through them creates the same issue)
yield self.make_requests_from_url("http://www.johnlscott.com/agent-search.aspx?p=agentResults.asp&OfficeID=%s" % col)
def parse_start_url(self, response):
items = []
sel = Selector(response)
sections = sel.xpath("//tr/td/table[@id='tbAgents']/tr")
for section in sections:
item = JLSItem()
item['name'] = section.xpath("td[2]/text()")[0].extract().replace(u'\xa0', ' ').strip()
items.append(item)
return(items)
Answer: You can prevent the swapping of url parts by using the option
`canonicalize=False` like in the code:
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
class JLSSpider(CrawlSpider):
name = 'JLS'
allowed_domains = ['johnlscott.com']
start_urls = ['http://www.johnlscott.com/agent-search.aspx']
rules = (
# http://www.johnlscott.com/agent-search.aspx?p=agentResults.asp&OfficeID=7859
Rule(
LinkExtractor(
allow=('p=agentResults.asp&OfficeID=',
),
canonicalize=False
),
callback='parse_roster',
follow=True),
)
def parse_roster(self, response):
pass
|
How to workaround IronPython Compile() Issue?
Question: I'm trying to run the following in my C#/IronPython:
import re
Message = re.sub(r"^EVN\|A\d+", "EVN|A08", Message, flags=MULTILINE)
This works fine on real python at the command prompt. However, once I put it
into IronPython I get an error:
IronPython.Runtime.PythonContext.InvokeUnaryOperator(CodeContext context, UnaryOperators oper, Object target, String errorMsg)
at IronPython.Runtime.Operations.PythonOps.Length(Object o)
at IronPython.Modules.Builtin.len(Object o)
at Microsoft.Scripting.Interpreter.FuncCallInstruction`2.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3)
at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at Microsoft.Scripting.Interpreter.DynamicInstruction`4.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
at IronPython.Compiler.PythonScriptCode.Run(Scope scope)
at IronPython.Compiler.RuntimeScriptCode.InvokeTarget(Scope scope)
at IronPython.Compiler.RuntimeScriptCode.Run(Scope scope)
at Microsoft.Scripting.SourceUnit.Execute(Scope scope, ErrorSink errorSink)
at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
at Microsoft.Scripting.Hosting.ScriptEngine.Execute(String expression, ScriptScope scope)
Research led me to understand (right or wrong?) that the MULTILINE flag
triggers Compile() in IronPython. Then I found this article about its lack of
support in IronPython: <https://ironpython.codeplex.com/workitem/22692>.
Removing `flags=MULTILINE` fixes the error. However, It doesn't match on
`"^EVN"` any longer.
EDIT: If I use `flags=re.MULTILINE` I receive this error:
ERROR Error while processing the message. Message: sub() got an unexpected keyword argument 'flags'. Microsoft.Scripting.ArgumentTypeException: sub() got an unexpected keyword argument 'flags'
END EDIT
My question is: How can I work around this issue and still get the same
results I would get at the command line given the above code snippet, but in
IronPython?
I rarely use Python, let alone IronPython, so please be forgiving as I'm not
sure of my alternatives.
Answer: It’s possible that IronPython does not support the `flags` keyword argument in
[`re.sub`](https://docs.python.org/2/library/re.html#re.sub). To work around
that issue, you can compile your regular expression first. This is recommended
anyway if you plan to use your expression multiple times; and the module-level
functions do it anyway.
To do that, use
[`re.compile`](https://docs.python.org/2/library/re.html#re.compile). The
flags can be passed as the second argument:
regex = re.compile('^EVN\|A\d+', re.MULTILINE)
This gives you a regular expression object, and you can directly use its
[`sub`](https://docs.python.org/2/library/re.html#re.RegexObject.sub) method
to perform your replacement:
Message = regex.sub('EVN|A08', Message)
|
Create PySpark Profile for IPython
Question: I follow this link <http://ramhiser.com/2015/02/01/configuring-ipython-
notebook-support-for-pyspark/> in order to create PySpark Profile for IPython.
00-pyspark-setup.py
# Configure the necessary Spark environment
import os
import sys
spark_home = os.environ.get('SPARK_HOME', None)
sys.path.insert(0, spark_home + "\python")
# Add the py4j to the path.
# You may need to change the version number to match your install
sys.path.insert(0, os.path.join(spark_home, '\python\lib\py4j-0.8.2.1-src.zip'))
# Initialize PySpark to predefine the SparkContext variable 'sc'
execfile(os.path.join(spark_home, '\python\pyspark\shell.py'))
My problem when I type `sc` in ipython-notebook, I got `''` I should see
output similar to `<pyspark.context.SparkContext at 0x1097e8e90>.`
Any idea about how to resolve it ?
Answer: I was trying to do the same, but had problems. Now, I use `findspark`
(<https://github.com/minrk/findspark>) instead. You can install it with pip
(see <https://pypi.python.org/pypi/findspark/>):
$ pip install findspark
And then, inside a notebook:
import findspark
findspark.init()
import pyspark
sc = pyspark.SparkContext(appName="myAppName")
If you want to avoid this boilerplate, you can put the above 4 lines in
`00-pyspark-setup.py`.
(Right now I have Spark 1.4.1. and findspark 0.0.5.)
|
Python - Printing on Same Line
Question: I am very new and attempting to learn how to scrape tables. I have the
following code, but can not get the two variables to print on the same line;
they print on separate lines. What am I missing?
from lxml import html
from bs4 import BeautifulSoup
import requests
url = "http://www.columbia.edu/~fdc/sample.html"
r = requests.get(url)
soup = BeautifulSoup(r.content)
tables = soup.findAll('table')
for table in tables:
Second_row_first_column = table.findAll('tr')[1].findAll('td')[0].text
Second_row_second_column = table.findAll('tr')[1].findAll('td')[1].text
print Second_row_first_column + Second_row_second_column
Answer: The columns have a newline at the end, so if you want to print it without
them, you have to
[`.strip()`](https://docs.python.org/2/library/string.html#string.strip) them:
print Second_row_first_column.strip() + Second_row_second_column.strip()
If you want a space between the two columns, replace the plus with a comma.
|
Using Python 2.7 and matplotlib, how do I create a 2D Line using two different styles?
Question: Working on a personal project that draws two lines, each dashed (ls='--') for
the first two x-axis markings, then it is a solid line...thinking about
writing a tutorial since I've found no information on this. Anyhow, the trick
I'm stumped at, is to figure how many points are used to make the line for the
first two x-axis markings, so I can properly turn off the solid line up to
that point. I'm using the `Line.set_dashes()` method to turn off the solid
line, and I'm making an individual (non-connected) copy and setting the
linestyle to dash. This causes the lines to be drawn on top of each other, and
the solid to take precedence when ON. However, the `Line.set_dashes()` takes
"points" as arguments. I figured out where, but as you see, the second line
has different angles, thus length, so this point is further along the line.
Maybe there's a better way to set the line to two styles?
Here is an example plot --> <https://flic.kr/p/rin6Z5>
r = getPostData(wall)
if len(newTimes) < LIMIT:
LIMIT = len(newTimes)
yLim = int(round(max(r['Likes'].max(), r['Shares'].max()) * 1.2))
xLim = LIMIT
L1A = plt.Line2D(range(LIMIT), r['Likes'], color='b', ls='--')
L1B = plt.Line2D(range(LIMIT), r['Likes'], label='Likes', color='b')
L2A = plt.Line2D(range(LIMIT), r['Shares'], color='r', ls='--')
L2B = plt.Line2D(range(LIMIT), r['Shares'], label='Shares', color='r')
LNull = plt.Line2D(range(LIMIT), r['Shares'], ls='--', label='Recent Data\n(Early collection)', color='k')
dashes = [1,84,7000,1]
dashesNull=[1,7000]
fig = plt.figure()
ax = fig.add_subplot(111, ylim=(0,yLim), xlim=(0,xLim))
ax.add_line(L1A)
ax.add_line(L1B)
ax.add_line(L2A)
ax.add_line(L2B)
ax.add_line(LNull)
ax.legend(bbox_to_anchor=(1.5,1))
L1B.set_dashes(dashes)
L2B.set_dashes(dashes)
LNull.set_dashes(dashesNull)
Answer: I would write your self a helper function, something like:
import numpy as np
import matplotlib.pyplot as plt
def split_plot(ax, x, y, low, high, inner_style, outer_style):
"""
Split styling of line based on the x-value
Parameters
----------
x, y : ndarray
Data, must be same length
low, high : float
The low and high threshold values, points for `low < x < high` are
styled using `inner_style` and points for `x < low or x > high` are
styled using `outer_style`
inner_style, outer_style : dict
Dictionary of styles that can be passed to `ax.plot`
Returns
-------
lower, mid, upper : Line2D
The artists for the lower, midddle, and upper ranges
vline_low, vline_hi : Line2D
Vertical lines at the thresholds
hspan : Patch
Patch over middle region
"""
low_mask = x < low
high_mask = x > high
mid_mask = ~np.logical_or(low_mask, high_mask)
low_mask[1:] |= low_mask[:-1]
high_mask[:-1] |= high_mask[1:]
lower, = ax.plot(x[low_mask], y[low_mask], **outer_style)
mid, = ax.plot(x[mid_mask], y[mid_mask], **inner_style)
upper, = ax.plot(x[high_mask], y[high_mask], **outer_style)
# add vertical lines
vline_low = ax.axvline(low, color='k', ls='--')
vline_high = ax.axvline(high, color='k', ls='--')
hspan = ax.axvspan(low, high, color='b', alpha=.25)
return lower, mid, upper, vline_low, vline_high, hspan
Which can obviously be generalized to take 3 line style dictionaries and style
information for the vertical lines and the span. You use it like:
inner_style = {'color': 'r', 'lw': 5, 'ls':'--'}
outer_style = {'color': 'r', 'lw': 1, 'ls':'-'}
x = np.linspace(0, 2*np.pi, 1024)
y = np.sin(x)
low = np.pi / 2
high = 3*np.pi / 2
fig, ax = plt.subplots()
lower, mid, upper, vl_low, vl_high, hsp = split_plot(ax, x, y, low, high, inner_style, outer_style)
plt.show()

|
unable to submit spark python script
Question: I'm using the following script to submit a python script
#!/usr/bin/python
from pyspark.mllib.classification import LogisticRegressionWithSGD
from pyspark.mllib.regression import LabeledPoint
from numpy import array
from pyspark import SparkContext as sc, SparkConf
data = sc.textFile("hdfs:/dataset/parkinsons.data")
got this error:
data = sc.textFile("hdfs:/dataset/parkinsons.data")
TypeError: unbound method textFile() must be called with SparkContext instance as first argument (got str instance instead)
Answer: You must create a SparkContext at first, for example:
from pyspark import SparkContext
sc = SparkContext(appName="TestApp")
data = sc.textFile("hdfs:/dataset/parkinsons.data")
|
pandas dataframe to oracle - NotImplementedError
Question: I am trying to insert a pandas dataframe in to oracle table with the following
code:
tabl.to_sql('RESULT', cnxn, flavor='oracle', if_exists='replace');
however, I am running in to the following error:
Traceback (most recent call last):
File "./pp.py", line 125, in <module>
tabl.to_sql('RESULT', cnxn, flavor='oracle', if_exists='replace');
File "/opt/local/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 950, in to_sql
index_label=index_label)
File "/opt/local/anaconda/lib/python2.7/site-packages/pandas/io/sql.py", line 467, in to_sql
pandas_sql = pandasSQL_builder(con, flavor=flavor)
File "/opt/local/anaconda/lib/python2.7/site-packages/pandas/io/sql.py", line 521, in pandasSQL_builder
return PandasSQLLegacy(con, flavor, is_cursor=is_cursor)
File "/opt/local/anaconda/lib/python2.7/site-packages/pandas/io/sql.py", line 1017, in __init__
raise NotImplementedError
NotImplementedError
I've cx_oracle installed. Pandas version is 0.14.1 ( from Anaconda-2.1). Any
lights would be much appreciated.
Answer: Oracle is supported through SQLAlchemy (in fact, all database flavors that can
be used with SQLAlchemy are supported). Therefore you need to make a
[SQLAlchemy
engine](http://docs.sqlalchemy.org/en/latest/dialects/oracle.html#module-
sqlalchemy.dialects.oracle.cx_oracle):
from sqlalchemy import create_engine
engine = create_engine('oracle+cx_oracle://scott:tiger@tnsname')
tabl.to_sql('RESULT', engine, if_exists='replace')
See the explanation here: <http://pandas.pydata.org/pandas-
docs/stable/io.html#sql-queries>. You need at least pandas >= 0.14 for this.
Previously, through the `flavor` keyword, indeed only sqlite and mysql were
supported, as @cel points out. This `flavor` is now deprecated, and only
`sqlite` will remain supported without using sqlalchemy.
|
Best way to share global variables between files in Python
Question: I was wondering what the best way is to use global variables in a multi-script
python project. I've seen this question: [Using global variables between files
in Python?](http://stackoverflow.com/questions/13034496/using-global-
variables-between-files-in-python) \- and while the accepted answer works, the
solution seems clunky.
See the below set of scripts. Only main.py is ever called directly; the rest
are imported.
First, I've declared my global variables in a separate file:
#global_vars.py
my_string = "hello world"
The `main.py` prints the value of the string using a custom function, changes
the value of the global variable, and then prints the new value
#main.py
import global_vars
import do_things_module
#Print the instantiated value of the global string
do_things_module.my_function()
#Change the global variable globally
global_vars.my_string = "goodbye"
#Print the new value of the global string
do_things_module.my_function()
`do_things_module.py` contains our custom print function, and gets the string
straight from the global
#do_things_module.py
import global_vars
def my_function():
print(global_vars.my_string)
Having to keep referencing `global_vars.my_string` rather than just
`my_string` to ensure I'm always reading/writing to the global scoped variable
seems long-winded and not very 'pythonic'. Is there a better/neater way?
Answer: I would go with
import global_vars as g
Then you can refer to `my_string` from `global_vars` module as `g.my_string`
in your code.
It doesn't use a lot of space, but it is still clear, that `my_string` came
from `global_vars` and namespace isn't polluted
If you need only a few `global_vars` variables in your current module you can
import only them
from global_vars import my_string, my_int
and reference to them as `my_string` and `my_int`
|
Python Webdriver my script won't find the button inside the iFrame
Question: I am trying to verify if a button is present on a webpage after I have
successfully logged in. I am using Webdriver with Python. The button is in an
iFrame. This is my first webdriver python program using the a page object
model framework. Not bad so far i think.
The program successfully logs in but it won't find the iFrame. I need some
help please.
I receive the following error:
Error
Traceback (most recent call last):
File "C:\Users\riaz.ladhani\PycharmProjects\Selenium Webdriver\TestCore 01\LoginPage_TestCase.py", line 16, in test_login_valid_user
login_page.isAdministration_present()
File "C:\Users\riaz.ladhani\PycharmProjects\Selenium Webdriver\TestCore 01\page.py", line 44, in isAdministration_present
content_frame = self.driver.find_element(*MainPageLocators.contentFrame)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 664, in find_element
{'using': by, 'value': value})['value']
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 175, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 166, in check_response
raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: Unable to locate element: {"method":"id","selector":"testcore"}
My full code snipped it as follows:
# This class is where all my locators will be defined
from selenium.webdriver.common.by import By
class MainPageLocators(object):
GO_BUTTON = (By.ID, 'submit')
usernameTxtBox = (By.ID, 'unid')
passwordTxtBox = (By.ID, 'pwid')
submitButton = (By.ID, 'button')
AdministrationButton = (By.CSS_SELECTOR, 'div.gwt-HTML.firepath-matching-node')
AdministrationButtonXpath = (By.XPATH, '/body/div[2]/div[2]/div/div[2]/div/div[2]/div/div[7]/div/div')
AdministrationButtonCSS = (By.CSS_SELECTOR, '/body/div[2]/div[2]/div/div[2]/div/div[2]/div/div[7]/div/div')
contentFrame = (By.ID, 'testcore')
from element import BasePageElement
from locators import MainPageLocators
# This class is the base page class
class BasePage(object):
def __init__(self, driver):
self.driver = driver
# This class is the LoginPage. All the methods for the login page are defined here
class LoginPage(BasePage):
def click_go_button(self):
element = self.driver.find_element(*MainPageLocators.GO_BUTTON)
element.click()
def userLogin_valid(self):
userName_textbox = self.driver.find_element(*MainPageLocators.usernameTxtBox)
userName_textbox.clear()
userName_textbox.send_keys("user1")
password_textbox = self.driver.find_element(*MainPageLocators.passwordTxtBox)
password_textbox.clear()
password_textbox.send_keys("Pass1")
submitButton = self.driver.find_element(*MainPageLocators.submitButton)
submitButton.click()
# Is the Administration button present on the dashboard page
def isAdministration_present(self):
content_frame = self.driver.find_element(*MainPageLocators.contentFrame)
self.driver.switch_to.frame(content_frame)
administrationButtonCSS = self.driver.find_element(*MainPageLocators.AdministrationButtonCSS)
# This class is the TestCase test class for the Login page where all the test cases is defined
import unittest
from selenium import webdriver
import page
class LoginPage_TestCase(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.get("http://mypc:8080/testcore01")
def test_login_valid_user(self):
login_page = page.LoginPage(self.driver)
login_page.userLogin_valid()
login_page.isAdministration_present()
When i inspect the element in Firefox the HTML is as follows:
<body style="margin: 0px;">
<iframe id="__gwt_historyFrame" style="position: absolute; width: 0; height: 0; border: 0;" tabindex="-1" src="javascript:''"/>
<iframe id="testCore" src="javascript:''" style="position: absolute; width: 0px; height: 0px; border: medium none;" tabindex="-1"/>
<div style="position: absolute; z-index: -32767; top: -20cm; width: 10cm; height: 10cm; visibility: hidden;" aria-hidden="true"/>
<div class="gwt-TabLayoutPanelTab GEGQEWXCK" style="background-color: rgb(254, 255, 238);">
<div class="gwt-TabLayoutPanelTabInner">
<div class="gwt-HTML">Administration</div>
Answer: You have a typo in your selector.
contentFrame = (By.ID, 'testcore')
should be
contentFrame = (By.ID, 'testCore') # capital "C"
### Why?
According to your HTML:
<iframe id="testCore"...
|
"list_or_dict must be a list or a dict" when using append in openpyxl package of Python
Question: Based on this tutorial :
[LINK](https://openpyxl.readthedocs.org/en/latest/usage.html) we have this
structure:
from openpyxl import Workbook
from openpyxl.compat import range
wb = Workbook()
ws = wb.active
for row in range(1,3):
ws.append(range(100))
wb.save(finename ='mtest2.xlsx')
This returns below error for `ws.append(range(100))`:
TypeError: list_or_dict must be a list or a dict
What is the problem?
Answer: Evidently the argument to `ws.append` must be either a dictionary or a list.
Presumably you're using Python 3.x, where [`range` no longer returns a
list](https://docs.python.org/3/whatsnew/3.0.html#views-and-iterators-instead-
of-lists) (it now behaves like Python 2.x's `xrange`).
The simplest fix is to explicitly convert the `range` into a `list`:
for row in range(1, 3):
ws.append(list(range(100)))
|
Python command in python script from another python script
Question: I read already this [What is the best way to call a python script from another
python script?](http://stackoverflow.com/questions/1186789/what-is-the-best-
way-to-call-a-python-script-from-another-python-script)
In my case I don't want to call another python script in a python script, but
I want to call for example the ssylze.py with the specific options
$ python sslyze.py --regular www.target1.com
like consider in <https://code.google.com/p/sslyze/wiki/QuickStart>
So I have script test1.py and in that script I would like to use
sslyze.py --regular www.target1.com
how I do that?
Answer: Not sure if I've unscrambled the code from your comment ok and whether this is
what you are trying to do. As I don't know what sslyze.py is doing I haven't
tested it. However your problem might be due to not waiting for each
subprocess to terminate:
import subprocess
with open("ip.txt", "r") as file_in:
fname = "scan.txt"
with open("scan.txt","w") as file_out:
for line in file_in:
process = subprocess.Popen(["python", "sslyze.py", "--regular", line], stdout=subprocess.PIPE)
file_out.write(process.communicate()) # you might need to append \n to whatever you write
|
Python scapy show ip of the ping (echo) requests
Question: I want to grab and print the source address of the ping requests. I have the
following script:
pkt = sniff(filter="icmp", timeout =15, count = 15)
if pkt[ICMP].type == '8':
print pkt[IP].src
When a packet arrives script crashes with
AttributeError:'list' object has no attribute 'type'
However on the scapy console I can see clearly that this exist!
>>>packet=IP()/ICMP()/"AAAAAA"
>>>packet[ICMP].type
8
>>>
Any thoughts??
I changed for testing purposes (!) my script to the following:
pkts=sniff(filter="icmp", timeout=120,count=15)
for packet in pkts:
if packet.haslayer(IP) and str(packet.getlayer(IP).src)=="127.0.0.1"
print "packet arrived"
if packet.haslayer(ICMP) and str(packet.getlayer(ICMP).type)=="8":
print(packet[IP].src)
The above after doing a ping:
ping localhost -c 3
produces the following awkward result:
packet arrived
127.0.0.1
packet arrived
127.0.0.1
packet arrived
packet arrived
packet arrived
127.0.0.1
packet arrived
127.0.0.1
packet arrived
packet arrived
packet arrived
127.0.0.1
packet arrived
127.0.0.1
packet arrived
We can ignore the "packet arrived" multiple times because other packets are
reaching my host as well. But why I see 6 times the 127.0.0.1 when I sent 3
echo requests ? Even if I remove the for loop the same results are happening.
Answer: You have multiple packets so you can either index or iterate over:
from scapy.all import *
pkts = sniff(filter="icmp", timeout =15,count=15)
for packet in pkts:
if str(packet.getlayer(ICMP).type) == "8":
print(packet[IP].src)
Or using indexing to get the forst packet:
from scapy.all import *
pkts = sniff(filter="icmp", timeout =15,count=15)
if pkts and str(pkts[0].getlayer(ICMP).type) == "8":
print(pkts[0][IP].src)
|
django on jython using django-jython
Question: **I would appreciate it if you read my poor English**
**I use :**
> windows
>
> Jython 2.7rc2
>
> jdk-8u45
>
> django 1.8
>
> django-jython 1.7.0b2
I try `jython startproject mysite`, and succeed
then I try `jython manage.py runserver 8080` and fail
Detail:
In **settings.py** :
in DATABASES :
'ENGINE': 'doj.db.backends.sqlite3'
in INSTALLED_APPS:
I add 'doj',
The same with <https://pythonhosted.org/django-jython/index.html>
The results:
> raise
> ImproperlyConfigured(error_msg)django.core.exceptions.ImproperlyConfigured:'doj.db.backends.sqlite'
> isn't an a vailable database backend. Try using 'django.db.backends.XXX',
> where XXX is one of: u'base', u'mysql', u'oracle', u'postgresql_psycopg2',
> u'sqlite3' **Error was: cannot import name BaseDatabaseWrapper**
so I try **django.db.backends.sqlite** instead of **doj.db.backends.sqlite**
in **settings.py** at **DATABASES**
and unluckily:
> raise ImproperlyConfigured("Error loading either pysqlite2
> or sqlite3 modules (tried in that order): %s" % exc)
> django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2
> or sqlite3 modules (tried in that order): **No module** **named sqlite3**
and I also try **"doj.db.backends.postgresql_psycopg2"** and failed ,too
**Error was: cannot import name BaseDatabaseWrapper**
I have searched and try all day already but still can not solve.
thanks for your help!!!
Answer: Jpython has same problems about sqlite3 here is similar question and answer.
[sqlite3 module for
Jython](http://stackoverflow.com/questions/3875212/sqlite3-module-for-jython)
|
How to create a histogram of 2D arrays in ipython
Question: I have use the random number generator create a 1000*1000 2d arrays. How can i
create a histogram of those 2D arrays?
s1=np.random.rand(1000,1000)
Answer: Install and use `matplotlib`. Your code will look something like this:
import matplotlib.pyplot as plt
s1=np.random.rand(1000,1000)
plt.hist(s1)
`matplotlib` gives you a ton of useful options, you can read more about them
[here](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist).
|
Integration in python
Question: The code I have written to integrate is giving wrong results.I get the
c_0,c_1,...c_4 to be zeros! What am I doing wrong? I am using simply 0.7.6 on
a mac.
from numpy import *
from matplotlib.pyplot import *
from sympy import *
x = Symbol('x')
f = 1.0*sin(np.pi * x)
phi_0 = 1.0
phi_1 = 1.0*x
phi_2 = 1./2*(3*x**2-1)
phi_3 = 1./2*(5*x**3-3*x)
phi_4 = 1./8*(35*x**4-30*x**2+3)
c_0 = integrate(f*phi_0, (x, -1.0, 1.0))
c_1 = integrate(f*phi_1, (x, -1.0, 1.0))
c_2 = integrate(f*phi_2, (x, -1.0, 1.0))
c_3 = integrate(f*phi_3, (x, -1.0, 1.0))
c_4 = integrate(f*phi_4, (x, -1.0, 1.0))
print c_0
print c_1
print c_2
print c_3
print c_4
Answer: Other than the need to import numpy as np, I don't see any problems in the
most recent version (0.7.6). Some values are zero (as expected due to symmetry
consideration) but others are not:
>>> print c_0
0
>>> print c_1
0.636619772367581
>>> print c_2
0
>>> print c_3
-0.330926260628403
>>> print c_4
0
|
String filtering commas and numbers
Question: I want to filter a string in Python, to get only commas `,` and numbers
`[0-9]`.
import re
x="$HGHG54646JHGJH,54546654"
m=re.sub("[^0-9]","",x)
print(m)
The result is:
5464654546654
instead of:
54646,54546654
Answer: With your current code, you simply match `[0-9]`. Simply add a comma `,` as a
valid character, and use a backslash to escape to the literal (`\,`):
import re
x="$HGHG54646JHGJH,54546654"
m=re.sub("[^0-9\,]","",x)
print(m)
**Outputs:**
54646,54546654
[The docs](https://docs.python.org/3/library/re.html#regular-expression-
syntax) have further information regarding other special characters that must
be escaped with a backslash to acquire the literal, such as `?` and `*`.
|
App Engine Python - Sort db then put() index
Question: In my app, users earn a score and their details get stored in the datastore.
When the user logs in, I want to show their rank among all users(basically how
far away from the top score they are). So my solution was to sort the users'
profiles in descending order the put the index+1 to the Profile model and run
it in a cron.
However the cron fails. Any help or advise on a better way would be
appreciated:
from google.appengine.ext import db
def universal_rank(self):
users = Profile.all().filter('leaderboard =', l.key()).order('-score')
rank = 0
for user in users:
rank = rank + 1
user.rank = rank
db.put(users)
I'm using webapp2
Answer: I believe you have the wrong syntax for the filter query. From the docs,
<https://docs.djangoproject.com/en/1.8/topics/db/queries/>
It looks like what you need is something like this..
`users = Profile.objects.all().filter('leaderboard =',
l.key()).order('-score')`
Or, really, I don't think you need to the `.all()` in general.
`users = Profile.objects.filter('leaderboard =', l.key()).order('-score')`
I'm also not positive as to where you are getting `l.key()` but if you are
getting all users, I think that you could just do
`users = Profile.objects.all().order('-score')`
|
tor name not recognized in stem
Question: I am trying to follow the "to russia with love" tutorial
(<https://stem.torproject.org/tutorials/to_russia_with_love.html>) but I am
getting this error:
[1mStarting Tor:
[0m
Traceback (most recent call last):
File "C:\Users\gatsu\My Documents\LiClipse Workspace\TorCommunicator\tutorialStart.py", line 52, in <module>
init_msg_handler = print_bootstrap_lines,
File "C:\Python34\lib\site-packages\stem\process.py", line 244, in launch_tor_with_config
return launch_tor(tor_cmd, args, torrc_path, completion_percent, init_msg_handler, timeout, take_ownership)
File "C:\Python34\lib\site-packages\stem\process.py", line 83, in launch_tor
raise OSError("'%s' isn't available on your system. Maybe it's not in your PATH?" % tor_cmd)
OSError: 'tor' isn't available on your system. Maybe it's not in your PATH?
What am I missing? Do I need to import something to my project or add some Tor
PATH? I am using windows 8.1.
Answer: That means Stem doesn't know where the tor executable is located. Your PATH
tells applications like Stem where to look for executables and tor isn't
located in any of those locations.
You have a couple options...
a. Tell Stem explicitly where tor is located...
stem.process.launch_tor_with_config(tor_cmd='C:\path\to\tor', ...)
b. [Change your path to include
tor](http://www.computerhope.com/issues/ch000549.htm#windows8).
|
Python script just printing out blank page
Question: I am using xampp and I am able to run simple python script on it so xampp is
setup fine for python. I am trying to use pillow.
I have installed anaconda and did following in terminal
conda install pillow
If I run test.py below in terminal, it works fine. It prints format, size,
mode.
But if I try it from web browser I'm getting blank page.
Here is test.py
#!/Library/Frameworks/anaconda/bin/python
print("Content-Type: text/html")
print()
print("<html><head><title>Python</title></head><body>")
from PIL import Image, ImageFilter
original = Image.open("Lenna.png")
print("<h5>The size of the Image is: </h5>")
print("<h2>size " + original.format, original.size, original.mode + "</h2>")
if I use cgitb.enable() I get following error
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
/Applications/XAMPP/xamppfiles/cgi-bin/test7.py in ()
8 print("<html><head><title>Python</title></head><body>");
9 print("<h5>The size of the Image is: </h5>");
=> 10 from PIL import Image
11 original = Image.open("Lenna.png");
12 width, height = original.size;
PIL undefined, Image undefined
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/Image.py in ()
61 # Also note that Image.core is not a publicly documented interface,
62 # and should be considered private and subject to change.
=> 63 from PIL import _imaging as core
64 if PILLOW_VERSION != getattr(core, 'PILLOW_VERSION', None):
65 raise ImportError("The _imaging extension was built for another "
PIL undefined, _imaging undefined, core = <PIL.Image._imaging_not_installed object>
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/_imaging.so, 2): Library not loaded: @loader_path/.dylibs/libtiff.5.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/_imaging.so Reason: Incompatible library version: _imaging.so requires version 8.0.0 or later, but libtiff.5.dylib provides version 6.0.0
args = ('dlopen(/Library/Frameworks/Python.framework/Vers...later, but libtiff.5.dylib provides version 6.0.0',)
msg = 'dlopen(/Library/Frameworks/Python.framework/Vers...later, but libtiff.5.dylib provides version 6.0.0'
name = '_imaging'
path = '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/_imaging.so'
with_traceback = <built-in method with_traceback of ImportError object>
Answer: Kind of an anti-answer, but unless you are doing it this way for academic
reasons, you should try one of the more standard frameworks:
* [Flask](http://flask.pocoo.org/docs/0.10/quickstart/)
* [bottle.py](http://bottlepy.org/docs/dev/index.html)
The two frameworks I listed above are examples of minimalist frameworks that
do not get in your way. They take care of running your app and setting up
routes. The minimum to use Flask is this:
from flask import Flask
from PIL import Image, ImageFilter
app = Flask(__name__)
@app.route("/")
def myview():
original = Image.open("Lenna.png")
return """
<html><head><title>Python</title></head>
<body>
<h5>The size of the Image is: </h5>
<h2>size {format}, {size}, {mode}</h2>
</body></html>""".format(
format=original.format,
size=original.size,
mode=original.mode)
app.run()
Next, if you want to make your app available, you only need to setup a reverse
proxy in XAMPP (easy-peasy). I highly suggest using Flask; it comes with an
awesome in-page debugger, courtesy of its sister project
[Werkzeug](http://werkzeug.pocoo.org/) (lit. "toolbox").
## Werkzeug debugger:

|
Pandas file structure not supported error
Question: I get a `NotImplementedError: file structure not yet supported`when I run the
code below on this
[file](https://www.dropbox.com/s/nh117yurq6rk2g7/300113R1.DNC?dl=0)
import constants, pandas, pdb
from datetime import datetime, timedelta
df = pandas.read_csv('300113R1.DNC', skiprows = 11, delim_whitespace=True,usecols=['Y','M','D','PRCP'],
parse_dates={"datetime": [0,1,2]}, index_col="datetime",
date_parser=lambda x: pandas.datetime.strptime(x, '%Y %m %d'))
Any idea on what might be going wrong? Related query on a smaller sample of
this same dataset is here: [Date parse error in Python pandas while reading
file](http://stackoverflow.com/questions/29805372/date-parse-error-in-python-
pandas-while-reading-file?noredirect=1#comment47739746_29805372)
Answer: Thanks to @cosmoscalibur for spotting that your file is missing columns, one
solution is to skip parsing the header:
df = pandas.read_csv('300113R1.DNC', skiprows = 12, delim_whitespace=True,usecols=[0,1,2,3], header=None
parse_dates={"datetime": [0,1,2]}, index_col="datetime",
date_parser=lambda x: pandas.datetime.strptime(x, '%Y %m %d'))
this will require you to rename the single column from '3' to 'PRCP' after
loading:
df = df.rename(columns={3:'PRCP'})
|
Why use re.match(), when re.search() can do the same thing?
Question: From the documentation, it's very clear that:
* `match()` -> apply pattern match at the beginning of the string
* `search()` -> search through the string and return first match
And `search` with `'^'` and without `re.M` flag would work the same as
`match`.
Then why does python have `match()`? Isn't it redundant? Are there any
performance benefits to keeping `match()` in python?
Answer: The `pos` argument behaves differently in important ways:
>>> s = "a ab abc abcd"
>>> re.compile('a').match(s, pos=2)
<_sre.SRE_Match object; span=(2, 3), match='a'>
>>> re.compile('^a').search(s, pos=2)
None
`match` makes it possible to write a tokenizer, and ensure that characters are
never skipped. `search` has no way of saying "start from the earliest
allowable character".
Example use of match to break up a string with no gaps:
def tokenize(s, patt):
at = 0
while at < len(s):
m = patt.match(s, pos=at)
if not m:
raise ValueError("Did not expect character at location {}".format(at))
at = m.end()
yield m
|
pandas area plot interpolation / step style
Question: Is there a way to disable the interpolation in the pandas area plot? I would
like to get a "step-style" area plot. E.g. in the normal line plot it is
possible to specify:
import pandas as pd
df = pd.DataFrame({'x':range(10)})
df.plot(drawstyle = 'steps') # this works
#df.plot(kind = 'area', drawstyle = 'steps') # this does not work
I am using python 2.7 and pandas 0.14.1.
Many thanks in advance.
Answer: As far as I can tell, `df.plot(drawstyle="steps")` doesn't even store the
calculated step vertices;
out = df.plot(kind = 'line', drawstyle = 'steps') # stepped, not filled
stepline = out.get_lines()[0]
print(stepline.get_data())
> (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8,
> 9]))
so I think you'll have to roll your own. Which is just inserting
`(x[i+1],y[i])` directly after every `(x[i],y[i])` in the list of points:
df = pd.DataFrame({'x':range(10)})
x = df.x.values
xx = np.array([x,x])
xx.flatten('F')
doubled = xx.flatten('F') # NOTE! if x, y weren't the same, need a yy
plt.fill_between(doubled[:-1], doubled[1:], label='area')
ax = plt.gca()
df.plot(drawstyle = 'steps', color='red', ax=ax)

|
Python CSV Output Blank Cells
Question: I am trying to write the exact shell output of my python code into a csv file
(including the blank fields). My Python output looks like this. I have tried
to get my head around but for some reason, I am getting output that looks like
this.
contractNN
develop NN
manag NN
order NN
parti NN
suitabl NN
supplier NN
work NN
CSV Output Desired
[[(u'contract', 'NN'), (u'develop', 'NN'), (u'manag', 'NN'), (u'order', 'NN'), (u'parti', 'NN'), (u'suitabl', 'NN'), (u'supplier', 'NN'), (u'work', 'NN')]]
[[(u'microsoft', 'NN')]]
[[(u'hadoop', 'NN')]]
[[]]
[[(u'python', 'NN'), (u'python', 'NN')]]
[[]]
[[]]
My Python Code
import csv
import nltk
from nltk import pos_tag
from nltk.stem.snowball import SnowballStemmer
from nltk import stem
import numpy as np
output_file = open('examp_output.csv', 'w')
datawriter = csv.writer(output_file)
"""Bunch of NLTK Code"""
print [m]
datawriter.writerows(m)
output_file.close()
Answer: How about this instead of using CSVWriter
import os
output_file = open('example.txt','w') #use 'a' instead of 'w' to append instead of overwrite the text file if you're doing this in a loop
output_file.write(data_out)
os.rename('example.txt', 'example.csv')
|
swampy.TurtleWorld not working in python 3.4
Question: I m currently learning python using the ThinkPython book, am using python 3.4
and the Anaconda IDE. Part of what I need to continue is to install a module
called swampy. I installed it using pip, which worked very well. Importing the
module worked too together with tkinter, but I can't use any of the functions
in the module. I checked my lib folder, swampy is there and the functions too
are in the swampy folder. I can't figure out why its not working. Please I
really need help. If the question isn't clear enough please let me know. I
have included the code i tried to run and the error message I get each time I
try running it
The code i try to run (page 29, Chapter 4 of think Python the version for
python 3.4)
import tkinter
import swampy
world = swampy.TurtleWorld
bob = Turtle()
print(bob)
wait_for_user()
Error Message i got
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Mbaka1\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "C:\Users\Mbaka1\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Mbaka1/Documents/Python Scripts/test.py", line 28, in <module>
world = swampy.TurtleWorld
AttributeError: 'module' object has no attribute 'TurtleWorld'
Answer: The book shows these directions if you've downloaded the source code:
from TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
print(bob)
wait_for_user()
If you want to run the code after installing with pip, this should work:
from swampy.TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
print(bob)
wait_for_user()
The reason what you're doing isn't working is because `TurtleWorld` is a
module within the `swampy` package, which contains a functions with the same
name, i.e. `TurleWorld`. So when you do `import swampy` and then try calling
`swampy.TurtleWorld` you're trying to call a module rather than the function.
|
Python Pyserial Windows No Port Found
Question: I have just tried to connect to usb mobile to send sms through it using AT
commands. But when i use pyserial to connect to it in a windows os, i get
error could not open port, the file specified cannot be found.
>>> import serial
>>> ser = serial.Serial(0) # open first serial port
>>> print ser.name # check which port was really used
>>> ser.write("hello") # write a string
>>> ser.close()
even if i replace the 0 with any other value, like 0 -10 or 'com0','com1' etc,
i still get error file specified not found, port cannot be open.
There is a command listed in pyserial documentation which lists ports or
allows you to open a port
python -m serial.tools.miniterm
This command is supposed to list all serial ports. But it shows none.
I have 3 usb ports on my system. What is causing this issue.
Answer: Pyserial is _not_ guaranteed to detect all ports. This depends on how the
device and the OS communicate and if pyserial is designed to pick up on this.
For Example, pyserial could not detect a LabJack U3-LV or a EPSOM-POS receipt
printer I plugged in in a Win8 session (both could be detected using a linux
session).
Try **serial.tools.list_ports.comports()** and see what it gives you.
You could also look at the **pyusb** module for usb connections.
_Also_ : I recommend being careful when using numbers for ports, as the
mapping may not be "common-sense" logical (i.e. 0 may not map to COM0). Use
explicit string names instead.
|
What are python classes?
Question: I'm trying to learn programming and came across this in my core app.
from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
class SplashView(TemplateView):
template_name = "index.html"
What specifically does the above class do, in this context?
Answer: It does everything `TemplateView` does, plus has an attribute called
"template_name" with the value of "index.html".
|
Python -Why cannot change the value in the C callback function?
Question: I try to using python ctype to call C library (.so) , and this C library have
callback function. C source code:
* * *
int showHelloword(int *result)
{
*result = 1025;
return 55;
}
void BSP_SHOW(int time,int (*callback)(int *result))
{
int ret = 44;
int boo = 4;
while(time > 0){
--time;
if(time == 0){
if(callback) {
printf("boo %d\n",boo); // I expect boo=4
ret = callback(&boo);
printf("Outfunc=%d\n",boo); // I expect Outfunc=1025
printf("ret=%d\n",ret); // I expect ret=55
}
callback = 0;
}
sleep(1);
}
}
void main(){
BSP_SHOW( 2, &showHelloword);
}
The print rseult is :
boo=4
Outfunc=1025
ret=55
And it seem okay.
Makefile source :
gcc -c -fPIC -Wno-format-security -g main.c
gcc -shared -o libcall.so main.o
gcc main.o -o callback -ldl -lpthread -lrt
* * *
THEN, I try to using python ctype to call "BSP_SHOW" this function and get
callback into this function. Python source :
Python version : 2.6.6
* * *
import sys
import os
import time
from ctypes import *
import struct
from Queue import *
class callback_api(object):
def __init__(self):
CDLL("/usr/lib64/librt.so",mode=RTLD_GLOBAL)
path = "/root/workspace/callback/libcall.so" `C library path`
self.dll = cdll.LoadLibrary(path)
def BSP_SHOW(self,sec, cb_func):
self.dll.BSP_SHOW.restype = None
self.dll.BSP_SHOW.argtypes = [c_int, qa_cb_prototype]
self.dll.BSP_SHOW(c_int(sec),cb_func)
def qa_callback(result):
result = 1025 #it should change the value. but the result is not....
return 88
qa_cb_prototype = CFUNCTYPE( c_int, POINTER(c_int))
qa_cache_cb_func = qa_cb_prototype(qa_callback)
if __name__ == '__main__':
api = callback_api()
api.BSP_SHOW(2,qa_cache_cb_func) `got it callback`
* * *
The print result is.
cb=4
Outfunc=4 <---I expect it should be 1025,but not!
ret=88 <---return value have been change by python callback.
Have someone know is this a python ctype limitation or I use a wrong method?
Thanks!
Answer: The = operator reassigns a variable in python. In other words, you change what
the variable means.
You need to change what the variable is pointing to. Since it's a ctypes
pointer, you need to index it with 0 to do this.
def qa_callback(result):
result[0] = 1025
return 88
Note the `[0]` after result.
See also: <https://docs.python.org/2/library/ctypes.html#pointers>
|
Why Numpy.array is slower than build-in list for fetching sub list
Question: I'm going to improve the performance of my code snippet which will frequently
getting sub-array recursively.
So I used numpy.array instead of build-in list. Because, as I know, when
fetching the sub-array, numpy.array don't copy the orginal list.
But when I changed to numpy.array, the performance got worse. So I want to
know the reason. Thanks!
Following is my code snippet and the execution times by using the different
objects I got:
import timeit
stat = '''
import numpy
def func(a):
a[len(a)-1] += 1
if len(a) == 1:
return a[0]
else:
return func(a[1:len(a)])
a1=[1,2,3,4,5,6,7,8,9,10]
a2=numpy.array([1,2,3,4,5,6,7,8,9,10])
'''
if __name__ == "__main__":
print "Execution time with build-in list: {0}".format(timeit.timeit('func(a1)', setup = stat, number = 1000))
print "Execution time with Numpy array: {0}".format(timeit.timeit('func(a2)', setup = stat, number = 1000))
And on my 64-bit mac(Python 2.7.6 + Numpy 1.8.0rc1) the output is:
Execution time with build-in list: 0.00507998466492
Execution time with Numpy array: 0.0195469856262
Answer: You will get the same execution times if you modify your two last lines of
code as follows:
print "Execution time with build-in list: {0}".format(timeit.timeit(
'func(a1)', setup = stat, number = 1000), 'gc.enable()')
print "Execution time with Numpy array: {0}".format(timeit.timeit(
'func(a2)', setup = stat, number = 1000), 'gc.enable()')
where in both cases we allowed _timeit_ to switch on so-called _garbage
collection_ , i.e. the process of freeing memory when it is not used anymore.
The abovementioned modification returns, e.g.:
Execution time with build-in list: 0.00580596923828
Execution time with Numpy array: 0.00822710990906
to be of the same order of magnitude. According to the documentation of
_timeit_ "by default, it temporarily turns off garbage collection during the
timing. The advantage of this approach is that it makes independent timings
more comparable. This disadvantage is that garbage collection may be an
important component of the performance of the function being measured."
There is a thin understanding what method, i.e. with or without garbage
collection, should be used and when. Please also note, that you will obtain
much longer times if you apply time.time() block from _time_ module.
|
unix command execution with password via python
Question: I am trying to connect to mysql in unix from a python script. I provided the
password to connect to mysql in the script itself but terminal still prompts
for the password. This is what i have till now:
import os
from subprocess import Popen, PIPE
passwd = "user"
command = "mysql -u root -p"
proc = Popen(command.split(), stdin=PIPE)
proc.communicate(passwd+'\n')[1]
Can any one suggest what am i doing wrong here. Or is there a better way to do
this.
Answer: You can try this:
command = "mysql -u root -p" + passwd
|
Why only 1024 bytes are read in socketserver example
Question: I am reading through the documentation examples for python socketserver at
<https://docs.python.org/2/library/socketserver.html>
Why is the size specified as 1024 in the line `self.request.recv(1024)` inside
handle method. What happens if the data sent by the client is more than 1024
bytes ? Is it better to have a loop to read 1024 bytes until socket is empty ?
I have copied the example here :
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip() # why only 1024 bytes ?
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
Answer: When reading from a socket it's always required to make a loop.
The reason is that even if the source sent say 300 bytes over the network it's
possible for example that the data will arrive to the receiver as two separate
chunks of 200 bytes and 100 bytes.
For this reason when you specify a buffer size for `recv` you only say the
**maximum** amount you're willing to process, but the actual data amount
returned may be smaller.
There is no way to implement a "read until the end of the message" at the
Python level because the `send`/`recv` functions are simply wrappers of the
TCP socket interface and that is a **stream** interface, without message
boundaries (so there is no way to know if "all" the data has been received
from the source).
This also means that in many cases you will need to add your own boundaries if
you need to talk using messages (or you will need to use an higher-level
message-based network transport interface like [0MQ](http://zeromq.org/))
Note that "blocking mode" - when reading from a socket - only defines the
behavior when there is no data already received by the network layer of the
operating system: in that case, when blocking - the program will wait for a
chunk of data; if non-blocking instead - it will return immediately without
waiting. If there is any data already received by the computer, then the
`recv` call immediately returns even if the passed buffer size is bigger -
independently of the blocking/non-blocking setting.
Blocking mode doesn't mean that the `recv` call will wait for the buffer to be
filled.
**NOTE** : The Python documentation is indeed misleading on the behavior of
`recv` and hopefully will be fixed soon.
|
Is there a Python equivalent to the mahalanobis() function in R? If not, how can I implement it?
Question: I have the following code in R that calculates the mahalanobis distance on the
Iris dataset and returns a numeric vector with 150 values, one for every
observation in the dataset.
x=read.csv("Iris Data.csv")
mean<-colMeans(x)
Sx<-cov(x)
D2<-mahalanobis(x,mean,Sx)
I tried to implement the same in Python using
'scipy.spatial.distance.mahalanobis(u, v, VI)' function, but it seems this
function takes only one-dimensional arrays as parameters.
Answer: I used the Iris dataset from R, I suppose it is the same you are using.
First, these is my R benchmark, for comparison:
x <- read.csv("IrisData.csv")
x <- x[,c(2,3,4,5)]
mean<-colMeans(x)
Sx<-cov(x)
D2<-mahalanobis(x,mean,Sx)
Then, in python you can use:
from scipy.spatial.distance import mahalanobis
import scipy as sp
import pandas as pd
x = pd.read_csv('IrisData.csv')
x = x.ix[:,1:]
Sx = x.cov().values
Sx = sp.linalg.inv(Sx)
mean = x.mean().values
def mahalanobisR(X,meanCol,IC):
m = []
for i in range(X.shape[0]):
m.append(mahalanobis(X.ix[i,:],meanCol,IC) ** 2)
return(m)
mR = mahalanobisR(x,mean,Sx)
I defined a function so you can use it in other sets, (observe I use pandas
DataFrames as inputs)
Comparing results:
In R
> D2[c(1,2,3,4,5)]
[1] 2.134468 2.849119 2.081339 2.452382 2.462155
In Python:
In [43]: mR[0:5]
Out[45]:
[2.1344679233248431,
2.8491186861585733,
2.0813386639577991,
2.4523816316796712,
2.4621545347140477]
Just be careful that what you get in R is the squared Mahalanobis distance.
|
Fill pygame font with custom pattern
Question: I'm currently working on a (first) project in Python/Pygame and I'm trying to
display text with a pattern overlay. The pattern consists vertical lines (1
pixel width), 2 alternating colors .
I'm creating this pattern using pygame.draw.line(), and I can create
rectangles with a custom function I created. But now I want this pattern on my
font.
I'm new to Python and am wondering: is there a way to create some sort of mask
so that the pattern will appear on the font characters only, not outside of
them? I've searched the web for some time but cannot find anything.
Many thanks in advance!
Answer: You could make use of the different blend modes to get the effect you desire.
Here's a simple example (where `t.bmp` is the image with your pattern, but of
course you can just use any other surface):
import pygame
pygame.init()
screen = pygame.display.set_mode((490, 160))
font = pygame.font.SysFont('Arial', 150)
pattern = pygame.image.load('t.bmp').convert()
text = font.render('FooBar', True, (255, 255, 255), (0, 0, 0))
pattern.blit(text, (0, 0), special_flags = pygame.BLEND_MULT)
screen.blit(pattern, (0, 0))
pygame.display.flip();
while True:
if pygame.event.get(pygame.QUIT):
break
**Result:**

|
Python: Slicing a String based on Indicies and character
Question: I am essentially making a log file parsing program in Python. The issues I am
having is when I am trying to extract out a variable length thing, such as an
IP address.
FILE = importFile.readlines()
holderString = ''
cleanUp = []
for line in FILE:
holderString = line[51:63]
if holderString not in cleanUp:
cleanUp.append(holderString)
This block of code runs after I already parsed through the log file and have
extracted the lines that contain the keyword I am using. What I really want is
to be able to start at a specific indices, in this case column 51, as where an
IP address starts is predictable. Where it ends though, is the problem. Here
is an example line:
[02] Mon 01Jan15 00:00:00 - (1234567) Connected to 192.168.1.1 (local address 10.10.10.10, port 80)
The Index, Date, Time, dash, session ID and "Connected to" never change in
length nor their position, but the connecting IP address does change and thus
changes length (example: 19.18.1.1 (length of 9) or 192.168.100.100 (length of
15)).
How would I go about starting at a specific indices and end on a specific
character?
Answer: Slice the string from index 51 till the end, split it by spaces and use the
first element.
>>> line = "[02] Mon 01Jan15 00:00:00 - (1234567) Connected to 192.168.1.1 (local address 10.10.10.10, port 80)"
>>> line[51:].split()[0]
'192.168.1.1'
You can also do it without the slicing part by splitting the whole line at
spaces and taking the 9th splitted element as your ip address:
>>> line = "[02] Mon 01Jan15 00:00:00 - (1234567) Connected to 192.168.1.1 (local address 10.10.10.10, port 80)"
>>> line.split()[8]
'192.168.1.1'
An alternative way is to search for the ip address in your line with an regex:
>>> import re
>>> line = "[02] Mon 01Jan15 00:00:00 - (1234567) Connected to 192.168.1.1 (local address 10.10.10.10, port 80)"
>>> re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", line).group(0)
'192.168.1.1'
|
How to dynamically import variables after executing python script from within another script
Question: I want to extract a variable named `value` that is set in a second,
arbitrarily chosen, python script.
The process works when do it manually in pyhton's interactive mode, but when I
run the main script from the command line, `value` is not imported.
The main script's input arguments are already successfully forwarded, but
`value` seems to be in the local scope of the executed script.
I already tried to define `value` in the main script, and I also tried to set
its accessibility to global.
This is the script I have so far
import sys
import getopt
def main(argv):
try:
(opts, args) = getopt.getopt(argv, "s:o:a:", ["script=", "operations=", "args="])
except getopt.GetoptError as e:
print(e)
sys.exit(2)
# script to be called
script = ""
# arguments that are expected by script
operations = []
argv = []
for (opt, arg) in opts:
if opt in ("-o", "--operations"):
operations = arg.split(',')
print("operations = '%s'" % str(operations))
elif opt in ("-s", "--script"):
script = arg;
print("script = '%s'" % script)
elif opt in ("-a", "--args"):
argv = arg.split(',')
print("arguments = '%s'" % str(argv))
# script should define variable 'value'
exec(open(script).read())
print("Executed '%s'. Value is printed below." % script)
print("Value = '%s'" % value)
if __name__ == "__main__":
main(sys.argv[1:])
Answer: The `value` variable has been put into your locals dictionary by the `exec`,
but was not visible to the compiler. You can retrieve it like this:
print("Value = '%s'" % locals()['value'])
I would prefer an `import` solution
|
TypeError: unsupported operand type(s) for &: 'float' and 'float', but I have no &
Question: Here is part of my code:
import numpy as np
import pyfits
from astropy.io import ascii
def create_randoms(min_z,max_z,min_mass):
Do some calculations and use it to
write into a file
if (max_z == 1.0 and min_mass == 1e13):
ascii.write(data_1, '/home/Documents/0.0_zphot_1.0.dat', Writer=ascii.FixedWidthNoHeader, delimiter=None)
Exactly in the `if` statement, I get the error:
TypeError: unsupported operand type(s) for &: 'float' and 'float'
I call the function by:
create_randoms(0.0,1.0,1e13)
I don't know why it doesn't seem to like the values `1.0 and 1e13`. I am _not_
using the bitwise `&` here, and instead I am correctly using the logical
operator `and`. But still it is throwing me with the error.
Full error traceback:
TypeError Traceback (most recent call last)
<ipython-input-83-d5f507b12cc0> in <module>()
----> 1 create_randoms(0.0,1.0,1e13,0,0,1,0,0,0,0,1)
/home/ssridhar/Documents/PhD_materials/Python/correlation_func/100_Hband_halos/jackknife_random_creation.py in create_randoms(min_z, max_z, min_mass, r1, r2, r3, r4, d1, d2, d3, d4)
119 """ WRITING FILES ACCORDINGLY """
120
--> 121 if (max_z == '1.0' and min_mass == '1e13'):
122 ascii.write(data_1, '/home/ssridhar/Documents/PhD_materials/2pt_correlation_master_2/Input/100_Hband_halos/jackknife/M200>1e13/K1_100sq_M200>1e13_xyz_0.0<zphot0.001<1.0.dat', Writer=ascii.FixedWidthNoHeader, delimiter=None)
123
TypeError: unsupported operand type(s) for &: 'float' and 'float'
Answer: Python compiles your code to bytecode, then runs that. But bytecode doesn't
make for a readable error message. When an error occurs, Python loads the
original source code from disk to show what lines are causing the error.
So when you _edit your code_ , but don't reload the bytecode in Python or
restart the Python interpreter, your error messages will by out of sync. Old
code with the problem is run, but the traceback shows the new code.
In ipython, reload the code, or to be 100% sure, restart the interpreter.
|
Why am I getting this error? HTTP Error 407: Proxy Authentication Required
Question: I am using the following code found on post, [How to specify an authenticated
proxy for a python http
connection?](http://stackoverflow.com/questions/34079/how-to-specify-an-
authenticated-proxy-for-a-python-http-connection/3942980#3942980)
import urllib2
def get_proxy_opener(proxyurl, proxyuser, proxypass, proxyscheme="http"):
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, proxyurl, proxyuser, proxypass)
proxy_handler = urllib2.ProxyHandler({proxyscheme: proxyurl})
proxy_auth_handler = urllib2.ProxyBasicAuthHandler(password_mgr)
return urllib2.build_opener(proxy_handler, proxy_auth_handler)
if __name__ == "__main__":
import sys
if len(sys.argv) > 4:
url_opener = get_proxy_opener(*sys.argv[1:4])
for url in sys.argv[4:]:
print url_opener.open(url).headers
else:
print "Usage:", sys.argv[0], "proxy user pass fetchurls..."
I am using the proxy ip as specified in my wpad.dat file for argv[1]. (# for
confidentiality)
return "PROXY 138.84.###.###:####";
I am using my username and password for argval[2] and [3]. When I use
<http://google.com> it spits out the appropriate header information. When I
use <http://shipcsx.com/pub_sx_mainpagepublic_jct/sx.shipcsxpublic/Main> it
shows: HTTP Error 407: Proxy Authentication Required.
Answer: This may not be a question for StackExchange. You may need some visibility
into your proxy server to troubleshoot properly. With no other information,
I'll take an offhand guess that the Google domain (or part of it) is
configured as a trusted site at the proxy. This allows a request to bypass
proxy authentication entirely.
|
Django/Apache setup giving me a 'module not found' error
Question: So I have this AngularJS/Django/Apache project I was thrown on once a past
employee left. So far it's been pretty easy, but I'm at the point where I'm
trying to get Django/Apache to play well together and it's not working.
Since it's a 'module not found error' isn't there a chance that the my_report
directory isn't found on the path for some reason, or that there's a
permissions error?
I'm usually a Java/MySql developer and I'm used to Python as a backend
scripting language so this is a bit new to me :P
The whole project is located in the /var/www/html/CoreRubrics/DjangoBackend
directory with the following structure.
drwxr-xr-x. 2 apache users 5 Apr 21 16:01 CourseLists
-rw-r--r--. 1 apache users 250 Apr 21 16:01 manage.py
drwxr-xr-x. 2 apache users 4 Apr 21 16:01 scripts
drwxr-xr-x. 3 apache users 14 Apr 21 16:30 my_report
drwxr-xr-x. 2 apache users 3 Apr 21 17:04 apache
drwxr-xr-x. 2 apache users 8 Apr 23 11:19 my_proj
**I have apache serving up the front-end AngularJS perfectly fine, but Apache
is giving me the following error in the logs.**
[Thu Apr 23 11:15:23.230040 2015] [:info] [pid 15039] [client 172.16.75.13:57216] mod_wsgi (pid=15039, process='', application='<<url goes here>>|/corerubric/cr'): Loading WSGI script '/var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi'., referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803198 2015] [:error] [pid 15039] [client 172.16.75.13:57216] mod_wsgi (pid=15039): Target WSGI script '/var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi' cannot be loaded as Python module., referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803253 2015] [:error] [pid 15039] [client 172.16.75.13:57216] mod_wsgi (pid=15039): Exception occurred processing WSGI script '/var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi'., referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803304 2015] [:error] [pid 15039] [client 172.16.75.13:57216] Traceback (most recent call last):, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803346 2015] [:error] [pid 15039] [client 172.16.75.13:57216] File "/var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi", line 12, in <module>, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803670 2015] [:error] [pid 15039] [client 172.16.75.13:57216] application = get_wsgi_application(), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803704 2015] [:error] [pid 15039] [client 172.16.75.13:57216] File "/usr/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803784 2015] [:error] [pid 15039] [client 172.16.75.13:57216] django.setup(), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.803816 2015] [:error] [pid 15039] [client 172.16.75.13:57216] File "/usr/lib/python2.7/site-packages/django/__init__.py", line 21, in setup, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804003 2015] [:error] [pid 15039] [client 172.16.75.13:57216] apps.populate(settings.INSTALLED_APPS), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804044 2015] [:error] [pid 15039] [client 172.16.75.13:57216] File "/usr/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804376 2015] [:error] [pid 15039] [client 172.16.75.13:57216] app_config = AppConfig.create(entry), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804413 2015] [:error] [pid 15039] [client 172.16.75.13:57216] File "/usr/lib/python2.7/site-packages/django/apps/config.py", line 87, in create, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804624 2015] [:error] [pid 15039] [client 172.16.75.13:57216] module = import_module(entry), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804656 2015] [:error] [pid 15039] [client 172.16.75.13:57216] File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module, referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804744 2015] [:error] [pid 15039] [client 172.16.75.13:57216] __import__(name), referer: <<url goes here>>/
[Thu Apr 23 11:15:23.804797 2015] [:error] [pid 15039] [client 172.16.75.13:57216] ImportError: No module named my_report, referer: <<url goes here>>/
Here's the .wsgi file:
import os
import sys
from django.core.wsgi import get_wsgi_application
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
path='/var/www/html/CoreRubrics/DjangoBackend/my_proj'
if path not in sys.path:
sys.path.append(path)
application = get_wsgi_application()
So I tried running:
python /var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi
And then I get this error:
Traceback (most recent call last):
File "/var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi", line 12, in <module>
application = get_wsgi_application()
File "/usr/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application
django.setup()
File "/usr/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/usr/lib/python2.7/site-packages/django/apps/config.py", line 87, in create
module = import_module(entry)
File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named my_report
And here is my settings.py
# Django settings for my_proj project.
from mongoengine import connect
connect(<<super secret DB stuff>>)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('William Karavites', '[email protected]'),
)
MANAGERS = ADMINS
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
#'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
#'USER': '',
#'PASSWORD': '',
#'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
#'PORT': '', # Set to empty string for default.
# }
#}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/New_York'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '<super secret secret>'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
#'django.contrib.auth.middleware.RemoteUserMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
#AUTHENTICATION_BACKENDS = (
# 'django.contrib.auth.backends.RemoteUserBackend',
#)
ROOT_URLCONF = 'my_proj.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'my_proj.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'mongoengine.django.mongo_auth',
'my_report',
)
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User'
SESSION_ENGINE = 'mongoengine.django.sessions'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
Aaaaaaand just incase, here's my apache .conf file for the site:
#modified from anaylitics:/etc/httpd/conf.d/apache.conf
#<Directory /home/kimhuang/my_proj/apache>
#Order deny,allow
#Allow from all
#</Directory>
#WSGIPythonHome /home/kimhuang/my_proj_env
WSGIPythonPath /var/www/html/CoreRubrics/DjangoBackend/my_proj/:/var/www/html/CoreRubrics/DjangoBackend/my_report/
#WSGIScriptAlias /cr /home/kimhuang/my_proj/apache/django.wsgi
<VirtualHost <<ip>>>
ServerName <<url>>
ServerAlias <<url>>
<Location "/">
Order Allow,Deny
Allow from all
</Location>
DocumentRoot /var/www/html/CoreRubrics/FrontEnd
WSGIScriptAlias /corerubric/cr /var/www/html/CoreRubrics/DjangoBackend/apache/django.wsgi
ErrorLog logs/corerubrics_error_log
LogLevel debug
CustomLog logs/corerubrics_access_log combined
<Directory /var/www/html/CoreRubrics/DjangoBackend/apache/>
<Files django.wsgi>
Require all granted
</Files>
</Directory>
</VirtualHost>
Answer: The `my_report` app is not on the projects path.
Change the following lines inside your wsgi file:
os.environ['DJANGO_SETTINGS_MODULE'] = 'my_proj.settings'
path='/var/www/html/CoreRubrics/DjangoBackend/'
You should probably read about proper project structure, so here are a few
resources:
* [Best practices for Django project structure](http://stackoverflow.com/questions/22841764/best-practice-for-django-project-working-directory-structure)
* [Recommended Django Project Layout](http://www.revsys.com/blog/2014/nov/21/recommended-django-project-layout/)
|
Can libxmp be forced to register a namespace prefix when it won't take a suggested prefix?
Question: I'm handling xmp data with [python-xmp-
toolkit](https://code.google.com/p/python-xmp-toolkit/), which is a python
wrapping of the exempi C library.
We have an in-house namespace uri that we use in this data beginning with
"ns:oursite.com" rather than "http:oursite.com" or something else similar.
When I try to use the [register_namespace
method](http://www.spacetelescope.org/static/projects/python-xmp-
toolkit/docs/reference.html#libxmp.core.XMPMeta.register_namespace) to plug in
our namespace like this:
> new_xmp.register_namespace("ns:oursite.com/stuff", "foo")
it spits back a default "ns2:" prefix indicating that it refuses to register
the prefix I suggested.
I imagine it's doing some sort of validation on the uri name. Is there any way
to force around this? I have a hard time deducing what to do in this code
since it is a wrapping of C.
Answer: There may be another namespace registered under the same prefix but with a
different URI. Exempi allows neither duplicate namespaces nor duplicate
prefixes, unfortunately, and this is a limitation of the underlying Adobe XMP
SDK.
I found a workaround you could try to confirm it. The Exempi library can be
reloaded through the Python bindings, but there is a very small amount of time
(~100µs for me) during which another thread accessing Exempi _will_ crash.
Just run :
from libxmp import exempi
# Register a test namespace
exempi.register_namespace("http://test.com/test", "test")
# Release Exempi. Any XMP object initialized *before* this will be
# invalid and will segfault the interpreter...
exempi.terminate()
# Exempi is not initialized there, the Python interpreter will segfault
# if it is used. We have to call init() before being able to use it again.
exempi.init()
# Now you can register another URI with the same prefix
exempi.register_namespace("http://test.com/test/add", "test")
|
Python: Classes that use other classes
Question: So I have 2 files that work together using each other's classes.
I have
class Student:
"""A class to model a student with name, id and list of test grades"""
def __init__(self, name, id):
"""initializes the name and id number; sets list of grades to []"""
self.s_name = name
self.ident = id
self.tests=[]
def getID(self):
return self.ident
def get_name(self):
""" returns the student name"""
return self.s_name
def addtest(self,t):
"""adds a grade to the list of test grades """
self.tests.append(t)
def __str__(self):
"""returns the student name and the current list of grades"""
return self.s_name + " " + str(self.tests) + " "
def comp_av(self):
"""returns the average of the current set of grades or 'no grades'
if appropriate"""
if len(self.tests) > 0:
sum = 0.0
for item in self.tests:
sum = sum + item
average = float(sum)/len(self.tests)
return average
else:
return "no grades"
Which is completely done. I also have code that is from the teacher's point of
view. The students are not just represented by their names but by an object of
class `Student`. Each Student object has their name and ID number, but also a
list of test scores. Right now Course has only the constructor and the
`__str__` method.
from LabStudentClass import *
class Course:
""" A class to model a course which contains a list of students"""
def __init__(self,teacher):
"""Sets up a class to hold and update students"""
self.students = []
self.teacher = teacher
def __str__(self):
""" prints the course by listing each student in the class"""
result = self.teacher+"'s Class\n"
for s in self.students:
name = s.get_name()
result = result + name + '\n'
return result
c = Course("Dr. Bradshaw")
#print c
def AddStudent(name, id):
student1 = Student('Mary Comtpon', '3456')
student2 = Student('Billy Jo', '2345')
student3 = Student( 'Anne lou', '1090')
print student1
print student2
print student3
My goal is to create a method `AddStudent`: This method gets two parameters, a
student name and an ID. A new Student object is created and added to the
course.
Add 3 students to your class and print out the class to test it.
However, the students aren't printing and I'm not really sure what the problem
is.
Answer: Add this method to your `Course` class:
def addStudent(self, name, id):
student = new Student(name, id)
self.students.append(student)
Then, replace the function you wrote at the bottom with the following:
c.addStudent('Mary Comtpon', '3456')
c.addStudent('Billy Jo', '2345')
c.addStudent('Anne lou', '1090')
print c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.