text
stringlengths 226
34.5k
|
---|
Adding libraries to django nonrel
Question: I've a project in Django which I'm trying to port to Django-nonrel so that I
can upload it to Google app Engine. I've installed django-nonrel and other
required libraries by going through the
<http://djangoappengine.readthedocs.org/en/latest/installation.html>
namely: django-nonrel djangoappengine djangotoolbox django-autoload django-
dbindexer
that is by downloading their zip files and placing them in my app directory.
So, my app directory is: >
<app>/autoload
<app>/dbindexer
<app>/django
<app>/djangoappengine
<app>/djangotoolbox
I also have django in my project directory and have started the project by:
PYTHONPATH=. python django/bin/django-admin.py startproject \
--name=app.yaml --template=djangoappengine/conf/project_template app
If I am adding an external library with pip and adding it to the
**INSTALLED_APPS** of my app's **settings.py** , it is not recognised by my
django-nonrel which is pretty obvious considering the fact that django-nonrel
is not installed on my system. It gives me the following error
Traceback (most recent call last):
File "/usr/local/google_appengine/google/appengine/tools/devappserver2/module.py", line 1390, in _warmup
request_type=instance.READY_REQUEST)
File "/usr/local/google_appengine/google/appengine/tools/devappserver2/module.py", line 884, in _handle_request
environ, wrapped_start_response)
File "/usr/local/google_appengine/google/appengine/tools/devappserver2/request_rewriter.py", line 314, in _rewriter_middleware
response_body = iter(application(environ, wrapped_start_response))
File "/usr/local/google_appengine/google/appengine/tools/devappserver2/module.py", line 1297, in _handle_script_request
request_type)
File "/usr/local/google_appengine/google/appengine/tools/devappserver2/module.py", line 1262, in _handle_instance_request
request_type)
File "/usr/local/google_appengine/google/appengine/tools/devappserver2/instance.py", line 371, in handle
raise CannotAcceptRequests('Instance has been quit')
CannotAcceptRequests: Instance has been quit
(nonrel)apurva@apurva-HP-ProBook-6470b:~/project/flogin$ python manage.py runserver
INFO 2015-08-11 16:06:54,606 sdk_update_checker.py:229] Checking for updates to the SDK.
INFO 2015-08-11 16:06:55,511 sdk_update_checker.py:257] The SDK is up to date.
INFO 2015-08-11 16:06:55,633 api_server.py:205] Starting API server at: http://localhost:60055
INFO 2015-08-11 16:06:55,847 dispatcher.py:197] Starting module "default" running at: http://127.0.0.1:8080
INFO 2015-08-11 16:06:55,847 admin_server.py:118] Starting admin server at: http://localhost:8000
INFO 2015-08-11 16:06:58,966 __init__.py:52] Validating models...
ERROR 2015-08-11 16:06:59,045 wsgi.py:263]
Traceback (most recent call last):
File "/usr/local/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/usr/local/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/usr/local/google_appengine/google/appengine/runtime/wsgi.py", line 96, in LoadObject
__import__(cumulative_path)
File "/home/apurva/project/flogin/djangoappengine/main/__init__.py", line 66, in <module>
validate_models()
File "/home/apurva/project/flogin/djangoappengine/main/__init__.py", line 55, in validate_models
num_errors = get_validation_errors(s, None)
File "/home/apurva/project/flogin/django/core/management/validation.py", line 34, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/home/apurva/project/flogin/django/db/models/loading.py", line 196, in get_app_errors
self._populate()
File "/home/apurva/project/flogin/django/db/models/loading.py", line 75, in _populate
self.load_app(app_name, True)
File "/home/apurva/project/flogin/django/db/models/loading.py", line 97, in load_app
app_module = import_module(app_name)
File "/home/apurva/project/flogin/django/utils/importlib.py", line 42, in import_module
__import__(name)
ImportError: No module named oauth2_provider
However, I'm unsure on how to add external libraries to my project. So that my
django-nonrel recognises it. I've also tried google's documentation on how to
this i.e.
> Adding Third-party Packages to the Application
>
> You can add any third-party library to your application, as long as it is
> implemented in "pure Python" (no C extensions) and otherwise functions in
> the App Engine runtime environment. The easiest way to manage this is with a
> ./lib directory.
>
> Create a directory named lib in your application root directory:
>
> mkdir lib To tell your app how to find libraries in this directory, create
> (or modify) a file named appengine_config.py in the root of your project,
> then add these lines:
>
> from google.appengine.ext import vendor
>
> £ Add any libraries installed in the "lib" folder. vendor.add('lib') Use pip
> with the -t lib flag to install libraries in this directory:
>
> `$ pip install -t lib gcloud` Note: pip version 6.0.0 or higher is required
> for vendor to work properly.
>
> Tip: the appengine_config.py above assumes that the current working
> directory is where the lib folder is located. In some cases, such as unit
> tests, the current working directory can be different. To avoid errors, you
> can explicity pass in the full path to the lib folder using
> vendor.add(os.path.join(os.path.dirname(os.path.realpath(**file**)), 'lib'))
didn't work either.
Answer: So I had a very similar dilemma. Here is how I solved it:
Followed Google's instructions noted above, using `pip` and a `./lib`
directory. Make sure you have an updated version of `pip`:
sudo pip install --upgrade pip
Then, because of `pkg_resources` issues, I did this:
pip install -t lib setuptools
That was necessary, I am just not sure if that was the right place to install
setuptools or not. It certainly worked, though.
Then, I launched the local development server like this, in the project
directory:
PYTHONPATH=lib ./manage.py runserver
I hope that works for you!
|
Assertion failed (type == CV_32FC1 || type == CV_64FC1) in dct
Question: I am trying to take dct of an image. At first I was getting error
> The function/feature is not implemented (Odd-size DCT's are not implemented)
> in dct
So I pad the image with zeros to make it even sized
But now I get error:
> Assertion failed (type == CV_32FC1 || type == CV_64FC1) in dct
How can I solve this? Below is what I'm doing in python
img = cv2.imread(filepath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresholded = cv2.threshold(gray,200,255,cv2.THRESH_BINARY)
img = cv2.cvtColor(thresholded, cv2.COLOR_GRAY2BGR)
gray = thresholded
gray = gray.astype('float32')
#padding
BLUE = [255,0,0]
rows,cols = gray.shape
nrows = cv2.getOptimalDFTSize(rows)
ncols = cv2.getOptimalDFTSize(cols)
right = ncols - cols
bottom = nrows - rows
bordertype = cv2.BORDER_CONSTANT
gray = cv2.copyMakeBorder(img,0,bottom,0,right,bordertype, value = 0)
gray = gray.astype('float32')
dct=cv2.dct(gray)
Answer:
import cv2
import numpy as np
img = cv2.imread('imgColor.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresholded = cv2.threshold(gray,200,255,cv2.THRESH_BINARY)
img = cv2.cvtColor(thresholded, cv2.COLOR_GRAY2BGR)
gray = thresholded
gray = np.float32(gray)/255.0
dct=cv2.dct(gray)
#padding
# BLUE = [255,0,0]
# rows,cols = gray.shape
# nrows = cv2.getOptimalDFTSize(rows)
# ncols = cv2.getOptimalDFTSize(cols)
# right = ncols - cols
# bottom = nrows - rows
# bordertype = cv2.BORDER_CONSTANT
# gray = cv2.copyMakeBorder(img,0,bottom,0,right,bordertype, value = 0)
# gray = np.float32(gray)/255.0
# dct=cv2.dct(gray)
This worked for me ! Found this
[here](http://answers.opencv.org/question/9578/how-to-get-dct-of-an-image-in-
python-using-opencv/)
|
python: bandpass filter of an image
Question: I have a data image with an imaging artifact that comes out as a sinusoidal
background, which I want to remove. Since it is a single frequency sine wave,
it seems natural to Fourier transform and either bandpass filter or "notch
filter" (where I think I'd use a gaussian filter at +-omega).
[](http://i.stack.imgur.com/AacAP.png)
In trying to do this, I notice two things:
1) simply by performing the fft and back, I have reduced the sine wave
component, shown below. There seems to be some high-pass filtering of the data
just by going there and back?
import numpy as np
f = np.fft.fft2(img) #do the fourier transform
fshift1 = np.fft.fftshift(f) #shift the zero to the center
f_ishift = np.fft.ifftshift(fshift1) #inverse shift
img_back = np.fft.ifft2(f_ishift) #inverse fourier transform
img_back = np.abs(img_back)
This is an image of img_back:
[](http://i.stack.imgur.com/DKCEi.png)
Maybe the filtering here is good enough for me, but I'm not that confident in
it since I don't have a good understanding of the background suppression.
2) To be more sure of the suppression at the unwanted frequencies, I made a
boolean 'bandpass' mask and applied it to the data, but the fourier transform
ignores the mask.
a = shape(fshift1)[0]
b = shape(fshift1)[1]
ro = 8
ri = 5
y,x = np.ogrid[-a/2:a/2, -b/2:b/2]
m1 = x*x + y*y >= ro*ro
m2 = x*x + y*y <= ri*ri
m3=np.dstack((m1,m2))
maskcomb =[]
for r in m3:
maskcomb.append([any(c) for c in r]) #probably not pythonic, sorry
newma = np.invert(maskcomb)
filtdat = ma.array(fshift1,mask=newma)
imshow(abs(filtdat))
f_ishift = np.fft.ifftshift(filtdat)
img_back2 = np.fft.ifft2(f_ishift)
img_back2 = np.abs(img_back2)
Here the result is the same as before, because np.fft ignores masks. The fix
to that was simple:
`filtdat2 = filtdat.filled(filtdat.mean())`
Unfortunately, (but upon reflection also unsurprisingly) the result is shown
here:
[](http://i.stack.imgur.com/9Klkd.png)
The left plot is of the amplitude of the FFT, with the bandpass filter
applied. It is the dark ring around the central (DC) component. The phase is
not shown.
Clearly, the 'brickwall' filter is not the right solution. The phenomenon of
making rings from this filter is well explained here: [What happens when you
apply a brick-wall filter to a 1D
dataset.](http://dsp.stackexchange.com/questions/724/low-pass-filter-and-fft-
for-beginners-with-python/725#725)
So now I'm stuck. Perhaps it would be better to use one of the built in scipy
methods, but they seem to be for 1d data, as [in this implementation of a
butterworth filter](http://wiki.scipy.org/Cookbook/ButterworthBandpass).
Possibly the right thing to do involves using fftconvolve() as is done [here
to blur an
image.](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.fftconvolve.html#scipy.signal.fftconvolve)
My question about fftconvolve is this: Does it require both 'images' (the
image and the filter) to be in real space? I think yes, but in the example
they use a gaussian, so it's ambiguous (fft(gaussian)=gaussian). If so, then
it seems wrong to try to make a real space bandpass filter. Maybe the right
strategy uses convolve2d() with the fourier space image and a homemade filter.
If so, do you know how to make a good 2d filter?
Answer: So, one problem here is that your background sinusoid has a period not
terribly different from the signal components you are trying to preserve.
i.e., the spacing of the signal peaks is about the same as the period of the
background. This is going to make filtering difficult.
My first question is whether this background is truly constant from experiment
to experiment, or does it depend on the sample and experimental setup? If it
is constant, then background frame subtraction would work better than
filtering.
Most of the standard scipy.signal filter functions (bessel, chebychev, etc.)
are, as you say, designed for 1-D data. But you can easily extend them to
isotropic filtering in 2-D. Each filter in frequency space is a rational
function of f. The two representations are [a,b] which are the coefficiets of
the numerator and denominator polynomial, or [z,p,k] which is the factored
representation of the polynomial i.e.,: `H(f) = k(f-z0)*(f-z1)/(f-p0)*(f-p1)`
You can just take the polynomial from one of the filter design algorithms,
evaluate it as a function of sqrt(x^2+y^2) and apply it to your frequency
domain data.
Can you post a link to the original image data?
|
python3 for ubuntu can't find scapy?
Question: I'm trying to run a python script using scapy in Ubuntu 14.04. I downloaded
python3 with
sudo apt-get install python3
and I'm running the file I have with
sudo python3 <my filename>.py
As for importing scapy into my python file, I've tried
from scapy.all import *
and
import scapy.all
and other variations I've found while browsing the internet. However, none of
them work and I keep getting the "No module named 'scapy'" error.
My script worked when I ran it in python2 in the same environment using scapy,
but I've made changes specific to python3 in another development environment
and now need to run it in python3 in this environment.
Any ideas on how to get this working? I've tried updating python also, but I
can't get it to upgrade versions.
Answer: You have to install scapy library before using it. By what you write it seems
you just installed python3 and not scapy. Either:
* install pip3 and then `pip3 install scapy-python3` to install scapy library for all system
* (recommended) or use virtualenv and install the same way inside virtual environment, and then run your script inside the python virtual environment
On usage of virutalenv for python you can easily find many guides. Please,
comment if you need assistance on that.
|
Random numbers within Array in Python
Question: I'm new to Python. While reading, please mention any other suggestions
regarding ways to improve my Python code.
**Question:** How do I generate a 8xN dimensional array in Python containing
random numbers? **_The constraint is that each column of this array must
contain 8 draws without replacement from the integer set [1,8]_**. More
specifically, when N = 10, I want something like this.
[[ 6. 2. 3. 4. 7. 5. 5. 7. 8. 4.]
[ 1. 4. 5. 5. 4. 4. 8. 5. 7. 5.]
[ 7. 3. 8. 8. 3. 8. 7. 3. 6. 7.]
[ 3. 6. 7. 1. 5. 6. 2. 1. 5. 1.]
[ 8. 1. 4. 3. 8. 2. 3. 4. 3. 3.]
[ 5. 8. 1. 7. 1. 3. 6. 8. 1. 6.]
[ 4. 5. 2. 6. 2. 1. 1. 6. 4. 2.]
[ 2. 7. 6. 2. 6. 7. 4. 2. 2. 8.]]
To do this I use the following approach:
import numpy.random
import numpy
def rand_M(N):
M = numpy.zeros(shape = (8, N))
for i in range (0, N):
M[:, i] = numpy.random.choice(8, size = 8, replace = False) + 1
return M
In practice N will be ~1e7. The algorithm above is O(n) in time and it takes
roughly .38 secs when N=1e3. The time therefore when N = 1e7 is ~1hr (i.e.
3800 secs). There has to be a much more efficient way.
Timing the function
from timeit import Timer
t = Timer(lambda: rand_M(1000))
print(t.timeit(5))
0.3863314103162543
Answer: Create a random array of specified shape and then sort along the axis where
you want to keep the limits, thus giving us a vectorized and very efficient
solution. This would be based on this [`smart
answer`](http://stackoverflow.com/a/29156976/3293881) to [`MATLAB randomly
permuting columns
differently`](http://stackoverflow.com/questions/29156823/matlab-randomly-
permuting-columns-differently). Here's the implementation -
Sample run -
In [122]: N = 10
In [123]: np.argsort(np.random.rand(8,N),axis=0)+1
Out[123]:
array([[7, 3, 5, 1, 1, 5, 2, 4, 1, 4],
[8, 4, 3, 2, 2, 8, 5, 5, 6, 2],
[1, 2, 4, 6, 5, 4, 4, 3, 4, 7],
[5, 6, 2, 5, 8, 2, 7, 8, 5, 8],
[2, 8, 6, 3, 4, 7, 1, 1, 2, 6],
[6, 7, 7, 8, 6, 6, 3, 2, 7, 3],
[4, 1, 1, 4, 3, 3, 8, 6, 8, 1],
[3, 5, 8, 7, 7, 1, 6, 7, 3, 5]], dtype=int64)
Runtime tests -
In [124]: def sortbased_rand8(N):
...: return np.argsort(np.random.rand(8,N),axis=0)+1
...:
...: def rand_M(N):
...: M = np.zeros(shape = (8, N))
...: for i in range (0, N):
...: M[:, i] = np.random.choice(8, size = 8, replace = False) + 1
...: return M
...:
In [125]: N = 5000
In [126]: %timeit sortbased_rand8(N)
100 loops, best of 3: 1.95 ms per loop
In [127]: %timeit rand_M(N)
1 loops, best of 3: 233 ms per loop
Thus, awaits a **`120x`** speedup!
|
Python virtualbox api cannot add disk to SATA controller
Question: I'm having a hard time to ass a disk to a SATA controller with virtualbox API
when using a SAS controller everything works great but here I have a huge
traceback that I do not understand. Do I have to do something special with the
SATA controller? Thanks for helping
cheers,
import time
import os
import virtualbox
from virtualbox.library import StorageBus, IMachine
from virtualbox.library import IStorageController, LockType
from virtualbox.library import DeviceType, MediumVariant
from virtualbox.library import VBoxErrorObjectNotFound
from virtualbox.library import IStorageController, LockType, IVirtualBox
from virtualbox.library import IVirtualBox, AccessMode
session = virtualbox.Session()
sup = virtualbox.VirtualBox().find_machine("test_machine")
sup.lock_machine(session,LockType.write)
current_interface = IVirtualBox()
medium = current_interface.create_hard_disk("VDI", "/home/luffy/mine.vdi")
progress = medium.create_base_storage(1024*1024, [MediumVariant.fixed])
progress.wait_for_completion()
opened_medium = current_interface.open_medium("/home/luffy/mine.vdi", DeviceType.hard_disk, AccessMode.read_write,False)
session.machine.attach_device("SAS",2, 0, DeviceType.hard_disk,opened_medium) # This one works
session.machine.attach_device("SATA",2 ,0 ,DeviceType.hard_disk,opened_medium)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library.py", line 10264, in attach_device
in_p=[name, controller_port, device, type_p, medium])
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library_base.py", line 173, in _call
return self._call_method(method, in_p=in_p)
File "/usr/local/lib/python2.7/dist-packages/virtualbox/library_base.py", line 199, in _call_method
raise errobj
virtualbox.library.OleErrorInvalidarg: 0x80070057 (The port and/or device parameter are out of range: port=2 (must be in range [0, 0]), device=0 (must be in range [0, 0]))
#session.machine.save_settings()
session.unlock_machine()
Answer: First you have to set the max port count and then add the SATA hard disk
IStorageController sc = machine.getStorageControllerByName("SATA");
sc.setPortCount(sc.getMaxPortCount());
|
python + from <module> + how from - import know the PATH
Question: How the from in python know the PATH of the directory that all module are
exists?
For example
Under
/data_py/Python/modulespy
I have all the modules as:
Df.py
Tr.py
Sw.py
So how the following **from** syntax in python know to access the
**/data_py/Python/modulespy** folder and read all modules there
fromPymoduleeimport*
Answer:
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
This way you can find it out, which all path `python` will look for the
modules
**_Update as per the comment:_**
You can insert your path into the list. Index `0` has the first priority.
sys.path.insert(0, '/data-py/modules')
|
mod-wsgi get an error when trying to convert string params to json
Question: I get the following error:
File "C:\\Python34\\Lib\\json\\decoder.py", line 361, in raw_decode\r
raise ValueError(errmsg("Expecting value", s, err.value)) from None\r
ValueError: Expecting value: line 1 column 1 (char 0)\r, referer
when I send with xmlhttp the following params:
xmlhttp.send( "{ \"field1\": 'hello', \"field2\" : 'hello2'}" );
mod_wsgi code:
def application(environ, start_response):
output = ChildClass().getValue()
print( output)
request_body_size = int(environ['CONTENT_LENGTH'])
request_body = environ['wsgi.input'].read(request_body_size)
status = '200 OK'
strBody = str(request_body)
jsnBody = json.loads(strBody )
stroutput = '@' + strBody
for iterating_var in output:
values = ','.join(str(v) for v in iterating_var)
#str = ''.join(output[0])
print('second ' + values)
stroutput += '&&' + values
#print(str.encode('UTF-8'))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(stroutput)))]
start_response(status, response_headers)
return [stroutput.encode('UTF-8')]
The problematic lines:
strBody = str(request_body)
jsnBody = json.loads(strBody )
Answer: Python's json decoder raises that cryptic error when mixed quotes are used in
the string to be loaded.
import json
json.loads('{"thing": "value"}')
json.loads('{\'thing\': \'value\'}') #json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
json.loads('{"thing": \'value\'}') # json.decoder.JSONDecodeError: Expecting value: line 1 column 11 (char 10)is formatted with
json.loads("{\"thing\": 'value'}") # json.decoder.JSONDecodeError: Expecting value: line 1 column 11 (char 10)
Using `"` instead of `'` for strings in your json should resolve your error.
|
Python 3.4, TypeError for socket issues
Question: I don't quite understand the encode/decode in python. I've tried alsorts and
looked here to find similar but I cannot find some. This is the code in
question:
import sys
import socket
import threading
import time
QUIT = False
class ClientThread(threading.Thread): # Class that implements the client threads in this server
def __init__(self, client_sock): # Initialize the object, save the socket that this thread will use.
threading.Thread.__init__(self)
self.client = client_sock
def run(self): # Thread's main loop. Once this function returns, the thread is finished and dies.
global QUIT # Need to declare QUIT as global, since the method can change it
done = False
cmd = self.readline() # Read data from the socket and process it
while not done:
if b'quit' == cmd:
self.writeline('Ok, bye')
QUIT = True
done = True
elif b'bye' == cmd:
self.writeline('Ok, bye')
done = True
else:
self.writeline(self.name).encode('utf-8')
cmd = self.readline()
self.client.close() # Make sure socket is closed when we're done with it
return
def readline(self): # Helper function, read up to 1024 chars from the socket, and returns them as a string
result = self.client.recv(1024)
if None != result: # All letters in lower case and without and end of line markers
result = result.strip().lower()
return result
def writeline(self, text): # Helper func, writes the given string to the socket with and end of line marker at end
self.client.send(bytes(text.strip() + '\n'))
In this case, I get:
TypeError: string argument without an enconding.
This is on the line:
self.writeline('ok bye')
and also the line:
self.client.send(bytes(text.strip() + '\n'))
deleting the bytes part gives me another error:
TypeError: 'str' does not support the buffer interface
And also references the two lines from above. I've tried a combination of
`encode(utf-8)` on both with no help.
I think I'm grossly misunderstanding what is wrong here. I know that `bytes`
need to be sent, but when I do, it gives a concatenated error. Stuck in a vile
loop.
Any clarification would be greatly appreciated, thank you!
This is the full code with the additions from the community help thus far:
import sys
import socket
import threading
import time
QUIT = False
class ClientThread(threading.Thread): # Class that implements the client threads in this server
def __init__(self, client_sock): # Initialize the object, save the socket that this thread will use.
threading.Thread.__init__(self)
self.client = client_sock
def run(self): # Thread's main loop. Once this function returns, the thread is finished and dies.
global QUIT # Need to declare QUIT as global, since the method can change it
done = False
cmd = self.readline() # Read data from the socket and process it
while not done:
if b'quit' == cmd:
self.writeline('Ok, bye'.encode('utf-8'))
QUIT = True
done = True
elif b'bye' == cmd:
self.writeline('Ok, bye')
done = True
else:
self.writeline(str(self.name).encode('utf-8'))
cmd = self.readline()
self.client.close() # Make sure socket is closed when we're done with it
return
def readline(self): # Helper function, read up to 1024 chars from the socket, and returns them as a string
result = self.client.recv(1024)
if None != result: # All letters in lower case and without and end of line markers
result = result.strip().lower()
return result
def writeline(self, text): # Helper func, writes the given string to the socket with and end of line marker at end
self.client.send((text.strip() + '\n').encode("utf-8"))
class Server: # Server class. Opens up a socket and listens for incoming connections.
def __init__(self): # Every time a new connection arrives, new thread object is created and
self.sock = None # defers the processing of the connection to it
self.thread_list = []
def run(self): # Server main loop: Creates the server (incoming) socket, listens > creates thread to handle it
all_good = False
try_count = 0 # Attempt to open the socket
while not all_good:
if 3 < try_count: # Tried more than 3 times without success, maybe post is in use by another program
sys.exit(1)
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create the socket
port = 80
self.sock.bind(('127.0.0.1', port)) # Bind to the interface and port we want to listen on
self.sock.listen(5)
all_good = True
break
except socket.error:
print('Socket connection error... Waiting 10 seconds to retry.')
del self.sock
time.sleep(10)
try_count += 1
print('Server is listening for incoming connections.')
print('Try to connect through the command line with:')
print('telnet localhost 80')
print('and then type whatever you want.')
print()
print("typing 'bye' finishes the thread. but not the server",)
print("eg. you can quit telnet, run it again and get a different ",)
print("thread name")
print("typing 'quit' finishes the server")
try:
while not QUIT:
try:
self.sock.settimeout(0.500)
client = self.sock.accept()[0]
except socket.timeout:
time.sleep(1)
if QUIT:
print('Received quit command. Shutting down...')
break
continue
new_thread = ClientThread(client)
print('Incoming Connection. Started thread ',)
print(new_thread.getName())
self.thread_list.append(new_thread)
new_thread.start()
for thread in self.thread_list:
if not thread.isAlive():
self.thread_list.remove(thread)
thread.join()
except KeyboardInterrupt:
print('Ctrl+C pressed... Shutting Down')
except Exception as err:
print('Exception caught: %s\nClosing...' % err)
for thread in self.thread_list:
thread.join(1.0)
self.sock.close()
if "__main__" == __name__:
server = Server()
server.run()
print('Terminated')
In the traceback I get this exactly:
Exception in Thread-1:
Traceback (most recent call last):
File: "C:\Python34\liv\threading.py", line 920, in _bootstrap_inner
self.run()
File: "C:/Users/Savag/PycharmProjects/lds_system/Socketthread2.py", line 20 in run
self.writeline('Ok, bye'.encode("utf-8"))
File: "C:/Users/Savag/PycharmProjects/lds_system/Socketthread2.py", Line 40, in writeline
self.client.send((text.strip() + '\n').encode("utf-8"))
Answer: When you use `self.writeline('Ok bye'.encode('utf8'))` you are now passing a
`bytes` object to your `writeline()` method. In that method, you are then
concatenating another string to it `text.strip() + '\n'`, causing you to try
to concatenate a `bytes` and a `str` object.
Either have your `writeline` method handle the encoding, or have it handle
`bytes` only. If you do the latter, make sure your `readline()` method then
_decodes_ the data it reads from the socket, to be consistent.
In other words, pick an abstraction level at which you convert from text to
bytes, and use it consistently:
def readline(self):
"""Read up to 1024 bytes and return this as a string
Returns None if there was no data to read.
"""
result = self.client.recv(1024)
if result is not None:
result = result.strip().lower().decode('utf8')
return result
def writeline(self, text):
"""Write a string to the socket, followed by a newline"""
self.client.send(text.strip().encode('utf8') + b'\n')
Note that I used a `b'...'` bytes literal to create a `bytes` object for the
newline to concatenate.
Here `writeline` encodes, so pass in _string objects_ when you call the
object:
self.writeline('Ok, bye')
|
Authenticate Windows Security with Request library
Question: How can I authenticate in his Windows Security pop-up?
<http://imgur.com/1FSkbUF>
using requests and python?
from requests import session
with session() as c:
response = c.get('url', auth=('username', 'pass'),)
print(response.headers)
print(response.text)
but it does not work, it still prints error message source code
Answer: Ok, started working. It was just a internal server error. After several tries
I had to be blocked for a while.
|
Replace same line of pixels in dynamic images with Pillow in python
Question: I'm tring to work out an algorithm that does the following, input is left
image, output is right image:
IMPORTANT: Images are dynamically generated and the horizontal lines i need to
remove are always in the same position.
[](http://i.stack.imgur.com/7OcqS.jpg)
In the ouput i don't really care about the colors tho, it could be white, and
black like this, although that might be a little more complicated:
[](http://i.stack.imgur.com/ek8SR.jpg)
So far I've came up with this algorithm for modifying the images:
def modify_image(filename):
img = Image.open(filename)
img = img.convert('RGBA')
pixdata = img.load()
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y][0] in range(155, 190): #removes horizontal lines but doesn't change them to the vertical lines color
pixdata[x, y] = (255, 255, 255, 255)
if pixdata[x, y][0] < 135:
pixdata[x, y] = (0, 0, 0, 255)
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y][1] < 195:
pixdata[x, y] = (0, 0, 0, 255)
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y][2] > 0:
pixdata[x, y] = (255, 255, 255, 255)
img = img.resize((1000, 300), Image.NEAREST)
im2 = Image.new('P', img.size, 255)
im = img.convert('P')
img.save(base_path + "current.jpg")
modify_image (base_path + "image.gif")
This turns the images black and white and sometimes succeeds in isolating the
middile bar from the background, the thing is, it doesnt remove the horizontal
lines and it doesn't certainly change the color to the one of the vertical
line either.
bear in mind that the colors are merely illustrative and dynamic so think
about any possible color.
Any suggestions/approaches are greatly apreciated :)
UPDATE: managed to remove horizontal lines but not replace them with the
vertical lines color so that only partially solves the problem (or not at all)
Answer: I don't know how accurate this needs to be but, since the positions of the
horizontal bars are fixed, could you copy the pixel values from the row
immediately preceding each horizontal bar to each row of the horizontal bar.
This will not look perfect because of the gradient background, but it might be
enough for your purpose. Looking at the first example image, try this:
import os.path
from PIL import Image
HORIZONTAL_BAND_1_Y = range(37, 64)
HORIZONTAL_BAND_2_Y = range(125, 149)
img = Image.open(filename)
img = img.convert('RGBA')
pixdata = img.load()
for band in HORIZONTAL_BAND_1_Y, HORIZONTAL_BAND_2_Y:
for y in band:
for x in range(img.size[0]):
pixdata[x,y] = pixdata[x, band[0]-1]
new_filename = os.path.join(os.path.dirname(filename),
'new_{}'.format(os.path.basename(filename)))
img.save(new_filename)
**Sample ouput**
[](http://i.stack.imgur.com/ttiZx.png)
|
How to quit selenium driver when spider is closed
Question: I have a spider where I have to use Selenium to scrape dynamic data on page.
Here's what it looks like:
class MySpider(
name = 'myspider'
start_urls = ['http://example.org']
def __init__(self, *args, **kwargs):
super(, self).__init__(*args, **kwargs)
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(5)
dispatcher.connect(self.spider_closed, signals.spider_closed)
def spider_closed(self, spider):
if self.driver:
self.driver.quit()
self.driver = None
The problem here is that when I cancel job in Scrapyd it doesn't stop until I
manually close the window. I obviously won't be able to do that when I deploy
the spider to the real server.
Here's what I see in Scrapyd logs each time I hit "Cancel":
2015-08-12 13:48:13+0300 [HTTPChannel,208,127.0.0.1] Unhandled Error
Traceback (most recent call last):
File "/home/dmitry/.virtualenvs/myproject/local/lib/python2.7/site-packages/twisted/web/http.py", line 1731, in allContentReceived
req.requestReceived(command, path, version)
File "/home/dmitry/.virtualenvs/myproject/local/lib/python2.7/site-packages/twisted/web/http.py", line 827, in requestReceived
self.process()
File "/home/dmitry/.virtualenvs/myproject/local/lib/python2.7/site-packages/twisted/web/server.py", line 189, in process
self.render(resrc)
File "/home/dmitry/.virtualenvs/myproject/local/lib/python2.7/site-packages/twisted/web/server.py", line 238, in render
body = resrc.render(self)
--- <exception caught here> ---
File "/home/dmitry/.virtualenvs/myproject/local/lib/python2.7/site-packages/scrapyd/webservice.py", line 18, in render
return JsonResource.render(self, txrequest)
File "/home/dmitry/.virtualenvs/myproject/local/lib/python2.7/site-packages/scrapy/utils/txweb.py", line 10, in render
r = resource.Resource.render(self, txrequest)
File "/home/dmitry/.virtualenvs/myproject/local/lib/python2.7/site-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/home/dmitry/.virtualenvs/myproject/local/lib/python2.7/site-packages/scrapyd/webservice.py", line 55, in render_POST
s.transport.signalProcess(signal)
File "/home/dmitry/.virtualenvs/myproject/local/lib/python2.7/site-packages/twisted/internet/process.py", line 339, in signalProcess
raise ProcessExitedAlready()
twisted.internet.error.ProcessExitedAlready:
But the job is still in the job list and it's marked as "Running". So how can
I shutdown the driver?
Answer: Import `SignalManager`:
from scrapy.signalmanager import SignalManager
Then replace:
dispatcher.connect(self.spider_closed, signals.spider_closed)
With:
SignalManager(dispatcher.Any).connect(self.spider_closed, signal=signals.spider_closed)
|
Getting author's articles from Scopus using Scopus API (AUTHENTICATION_ERROR)
Question: I've registered at <http://www.developers.elsevier.com/action/devprojects>. I
created a project and got my scopus key:
[](http://i.stack.imgur.com/8wvbE.png)
Now, using this generated key, I would like to find an author by `firstname`,
`lastname` and `subjectarea`. I make requests from my university network,
which is allowed to visit Scopus (I have full manual access to Scopus search,
use it from Firefox with no problem). However, I wanted to automatize my
Scopus mining, by writing a simple script. I would like to find publications
of an author by giving his/her `firstname`, `lastname` and `subjectarea`.
Here's my code:
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
from scopus import SCOPUS_API_KEY
scopus_author_search_url = 'http://api.elsevier.com/content/search/author?'
headers = {'Accept':'application/json', 'X-ELS-APIKey': SCOPUS_API_KEY}
search_query = 'query=AUTHFIRST(%) AND AUTHLASTNAME(%s) AND SUBJAREA(%s)' % ('John', 'Kitchin', 'COMP')
# api_resource = "http://api.elsevier.com/content/search/author?apiKey=%s&" % (SCOPUS_API_KEY)
# request with first searching page
page_request = requests.get(scopus_author_search_url + search_query, headers=headers)
print page_request.url
# response to json
page = json.loads(page_request.content.decode("utf-8"))
print page
Where `SCOPUS_API_KEY` looks just like this: `SCOPUS_API_KEY="xxxxxxxx"`.
Although **I have full access to scopus from my university network** , I'm
getting such response:
> {u'service-error': {u'status': {u'statusText': u'Requestor configuration
> settings insufficient for access to this resource.', u'statusCode':
> u'AUTHENTICATION_ERROR'}}}
The generated link looks like this:
[http://api.elsevier.com/content/search/author?query=AUTHFIRST(John)%20AND%20AUTHLASTNAME(Kitchin)%20AND%20SUBJAREA(COMP)](http://ttp://api.elsevier.com/content/search/author?query=AUTHFIRST\(John\)%20AND%20AUTHLASTNAME\(Kitchin\)%20AND%20SUBJAREA\(COMP\))
and when I click it, it shows an XML file:
<service-error><status>
<statusCode>AUTHORIZATION_ERROR</statusCode>
<statusText>No APIKey provided for request</statusText>
</status></service-error>
Or, when I change the `scopus_author_search_url` to
`"http://api.elsevier.com/content/search/author?apiKey=%s&" %
(SCOPUS_API_KEY)` I'm getting:
`{u'service-error': {u'status': {u'statusText': u'Requestor configuration
settings insufficient for access to this resource.', u'statusCode':
u'AUTHENTICATION_ERROR'}}}` and the XML file:
<service-error>
<status>
<statusCode>AUTHENTICATION_ERROR</statusCode>
<statusText>Requestor configuration settings insufficient for access to this resource.</statusText>
</status>
</service-error>
What can be the cause of this problem and how can I fix it?
Answer: I have just registered for an API key and tested it first with this URL:
[http://api.elsevier.com/content/search/author?apikey=4xxxxxxxxxxxxxxxxxxxxxxxxxxxxx43&query=AUTHFIRST%28John%29+AND+AUTHLASTNAME%28Kitchin%29+AND+SUBJAREA%28COMP%29](http://api.elsevier.com/content/search/author?apikey=4xxxxxxxxxxxxxxxxxxxxxxxxxxxxx43&query=AUTHFIRST%28John%29+AND+AUTHLASTNAME%28Kitchin%29+AND+SUBJAREA%28COMP%29)
This works fine from my university network. I also tested a second API Key, so
have verified one with registered website on my university domain, one with
registered website <http://apitest.example.com>, ruling out the domain name
used to register as the source of your problem.
I tested this
1. in the browser,
2. using your python code both with the api key in the headers. The only change I made to your code is removing
from scopus import SCOPUS_API_KEY
and adding
SCOPUS_API_KEY ='4xxxxxxxxxxxxxxxxxxxxxxxxxxxxx43'
3. using your python code adapted to put the apikey in the URL instead of the headers.
In all cases, the query returns two authors, one at Carnegie Mellon and one at
Palo Alto.
I can't replicate your error message. If I try to use the API key from an IP
address unregistered with elsevier (e.g. my home computer), I see a different
error:
<service-error>
<status>
<statusCode>AUTHENTICATION_ERROR</statusCode>
<statusText>Client IP Address: xxx.yyy.aaa.bbb does not resolve to an account</statusText>
</status>
</service-error>
If I use a random (wrong) API key from the university network, I see
<service-error>
<status>
<statusCode>AUTHORIZATION_ERROR</statusCode>
<statusText>APIKey <mad3upa1phanum3r1ck3y> with IP address <my.uni.IP.add> is unrecognized or has insufficient privileges for access to this resource</statusText>
</status>
</service-error>
### Debug steps
As I can't replicate your problem - here are some diagnostic steps you can use
to resolve:
1. Use your browser at uni to actually submit the api query with your key in the URL (i.e. copy the URL above, paste it into the address bar, substitute your key and see whether you get the XML back)
2. If 1 returns the XML you expect, move onto submitting the request via Python - first, copy the exact URL straight into Python (no variable substitution via `%s`, no apikey in the header) and simply do a `.get()` on it.
3. If 2 returns correctly, ensure that your `SCOPUS_API_KEY` holds the exact key value, no more no less. i.e. `print 'SCOPUS_API_KEY'` should return your apikey: `4xxxxxxxxxxxxxxxxxxxxxxxxxxxxx43`
4. If 1 returns the error, it looks like your uni (for whatever reason) has not got access to the authors query API. This doesn't make much sense given that you can perform manual search, but that is all I can conclude
### Docs
For reference the authentication algorithm documentation [is
here](http://dev.elsevier.com/tecdoc_api_authentication.html), but it is not
very simple to follow. You are following authentication option 1 and your
method should just work.
N.B. The API is limited to [5000 author retrievals per
week](http://dev.elsevier.com/api_key_settings.html). If you have run a lot of
queries in a loop, even if they have failed, it is possible that you have
exceeded that...
|
non-NDFFrame object error using pandas.SparseSeries.from_coo() function
Question: I am trying to convert a COO type sparse matrix (from Scipy.Sparse) to a
Pandas sparse series. From the documentation(<http://pandas.pydata.org/pandas-
docs/stable/sparse.html>) it says to use the command
`SparseSeries.from_coo(A)`. This seems to be OK, but when I try to see the
series' attributes, this is what happens.
10x10 seems OK.
import pandas as pd
import scipy.sparse as ss
import numpy as np
row = (np.random.random(10)*10).astype(int)
col = (np.random.random(10)*10).astype(int)
val = np.random.random(10)*10
sparse = ss.coo_matrix((val,(row,col)),shape=(10,10))
pss = pd.SparseSeries.from_coo(sparse)
print pss
0 7 1.416631
9 5.833902
1 0 4.131919
2 3 2.820531
7 2.227009
3 1 9.205619
4 4 8.309077
6 0 4.376921
7 6 8.444013
7 7.383886
dtype: float64
BlockIndex
Block locations: array([0])
Block lengths: array([10])
But not 100x100.
import pandas as pd
import scipy.sparse as ss
import numpy as np
row = (np.random.random(100)*100).astype(int)
col = (np.random.random(100)*100).astype(int)
val = np.random.random(100)*100
sparse = ss.coo_matrix((val,(row,col)),shape=(100,100))
pss = pd.SparseSeries.from_coo(sparse)
print pss
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-790-f0c22a601b93> in <module>()
7 sparse = ss.coo_matrix((val,(row,col)),shape=(100,100))
8 pss = pd.SparseSeries.from_coo(sparse)
----> 9 print pss
10
C:\Users\ej\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\base.pyc in __str__(self)
45 if compat.PY3:
46 return self.__unicode__()
---> 47 return self.__bytes__()
48
49 def __bytes__(self):
C:\Users\ej\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\base.pyc in __bytes__(self)
57
58 encoding = get_option("display.encoding")
---> 59 return self.__unicode__().encode(encoding, 'replace')
60
61 def __repr__(self):
C:\Users\ej\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\sparse\series.pyc in __unicode__(self)
287 def __unicode__(self):
288 # currently, unicode is same as repr...fixes infinite loop
--> 289 series_rep = Series.__unicode__(self)
290 rep = '%s\n%s' % (series_rep, repr(self.sp_index))
291 return rep
C:\Users\ej\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\series.pyc in __unicode__(self)
895
896 self.to_string(buf=buf, name=self.name, dtype=self.dtype,
--> 897 max_rows=max_rows)
898 result = buf.getvalue()
899
C:\Users\ej\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\series.pyc in to_string(self, buf, na_rep, float_format, header, length, dtype, name, max_rows)
960 the_repr = self._get_repr(float_format=float_format, na_rep=na_rep,
961 header=header, length=length, dtype=dtype,
--> 962 name=name, max_rows=max_rows)
963
964 # catch contract violations
C:\Users\ej\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\series.pyc in _get_repr(self, name, header, length, dtype, na_rep, float_format, max_rows)
989 na_rep=na_rep,
990 float_format=float_format,
--> 991 max_rows=max_rows)
992 result = formatter.to_string()
993
C:\Users\ej\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\format.pyc in __init__(self, series, buf, length, header, na_rep, name, float_format, dtype, max_rows)
145 self.dtype = dtype
146
--> 147 self._chk_truncate()
148
149 def _chk_truncate(self):
C:\Users\ej\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\format.pyc in _chk_truncate(self)
158 else:
159 row_num = max_rows // 2
--> 160 series = concat((series.iloc[:row_num], series.iloc[-row_num:]))
161 self.tr_row_num = row_num
162 self.tr_series = series
C:\Users\ej\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\tools\merge.pyc in concat(objs, axis, join, join_axes, ignore_index, keys, levels, names, verify_integrity, copy)
752 keys=keys, levels=levels, names=names,
753 verify_integrity=verify_integrity,
--> 754 copy=copy)
755 return op.get_result()
756
C:\Users\ej\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\tools\merge.pyc in __init__(self, objs, axis, join, join_axes, keys, levels, names, ignore_index, verify_integrity, copy)
803 for obj in objs:
804 if not isinstance(obj, NDFrame):
--> 805 raise TypeError("cannot concatenate a non-NDFrame object")
806
807 # consolidate
TypeError: cannot concatenate a non-NDFrame object
I don't really understand the error message - I think I am following the
example in the documentation to the letter, just using my own COO matrix
(could it be the size?)
Regards
Answer: I have an older `pandas`. It has the sparse code, but not the `tocoo`. The
pandas issue that has been filed in connection with this is:
<https://github.com/pydata/pandas/issues/10818>
But I found on `github` that:
def _coo_to_sparse_series(A, dense_index=False):
""" Convert a scipy.sparse.coo_matrix to a SparseSeries.
Use the defaults given in the SparseSeries constructor. """
s = Series(A.data, MultiIndex.from_arrays((A.row, A.col)))
s = s.sort_index()
s = s.to_sparse() # TODO: specify kind?
# ...
return s
With a smallish sparse matrix I construct and display without problems:
In [259]: Asml=sparse.coo_matrix(np.arange(10*5).reshape(10,5))
In [260]: s=pd.Series(Asml.data,pd.MultiIndex.from_arrays((Asml.row,Asml.col)))
In [261]: s=s.sort_index()
In [262]: s
Out[262]:
0 1 1
2 2
3 3
4 4
1 0 5
1 6
2 7
[... mine]
3 48
4 49
dtype: int32
In [263]: ssml=s.to_sparse()
In [264]: ssml
Out[264]:
0 1 1
2 2
3 3
4 4
1 0 5
[... mine]
2 47
3 48
4 49
dtype: int32
BlockIndex
Block locations: array([0])
Block lengths: array([49])
but with a larger array (more nonzero elements) I get a display error. I'm
guessing it happens when the display for the (plain) series starts to use an
ellipsis (...). I'm running in Py3, so I get a different error message.
....\pandas\core\base.pyc in __str__(self)
45 if compat.PY3:
46 return self.__unicode__() # py3
47 return self.__bytes__() # py2 route
e.g.:
In [265]: Asml=sparse.coo_matrix(np.arange(10*7).reshape(10,7))
In [266]: s=pd.Series(Asml.data,pd.MultiIndex.from_arrays((Asml.row,Asml.col)))
In [267]: s=s.sort_index()
In [268]: s
Out[268]:
0 1 1
2 2
3 3
4 4
5 5
6 6
1 0 7
1 8
2 9
3 10
4 11
5 12
6 13
2 0 14
1 15
...
7 6 55
8 0 56
1 57
[... mine]
Length: 69, dtype: int32
In [269]: ssml=s.to_sparse()
In [270]: ssml
Out[270]: <repr(<pandas.sparse.series.SparseSeries at 0xaff6bc0c>)
failed: AttributeError: 'SparseArray' object has no attribute '_get_repr'>
I'm not sufficiently familiar with pandas code and structures to deduce much
more for now.
|
PicklingError: Can't pickle <type 'function'> with python process pool executor
Question: **util.py**
def exec_multiprocessing(self, method, args):
with concurrent.futures.ProcessPoolExecutor() as executor:
results = pool.map(method, args)
return results
**clone.py**
def clone_vm(self, name, first_run, host, ip):
# clone stuff
**invoke.py**
exec_args = [(name, first_run, host, ip) for host, ip in zip(hosts, ips)]
results = self.util.exec_multiprocessing(self.clone.clone_vm, exec_args)
The above code gives the pickling error. I found that it is because we are
passing instance method. So we should unwrap the instance method. But I am not
able to make it work.
Note: I can not create top level method to avoid this. I have to use instance
methods.
Answer: Let's start with an overview - why the error came up in the first place:
The `multiprocessing` must requires to pickle (serialize) data to pass them
along processes or threads. To be specific, `pool` methods themselves rely on
`queue` at the lower level, to stack tasks and pass them to threads/processes,
and `queue` requires everything that goes through it must be pickable.
The problem is, not all items are pickable - [list of
pickables](https://docs.python.org/2/library/pickle.html#what-can-be-pickled-
and-unpickled) \- and when one tries to pickle an unpicklable object, gets the
**`PicklingError`** exception - exactly what happened in your case, you passed
an instance method which is not picklable.
There can be various workarounds (as is the case with every problem) - the
solution which worked for me is [here by
Dano](http://stackoverflow.com/q/25156768/2073595) \- is to make `pickle`
handle the methods and register it with
[`copy_reg`](https://docs.python.org/2/library/copy_reg.html).
* * *
Add the following lines at the start of your module `clone.py` to make
`clone_vm` picklable (do `import` `copy_reg` and `types`):
def _pickle_method(m):
if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name)
else:
return getattr, (m.im_self, m.im_func.func_name)
copy_reg.pickle(types.MethodType, _pickle_method)
* * *
Other useful answers - by [Alex
Martelli](http://stackoverflow.com/questions/1816958/cant-pickle-type-
instancemethod-when-using-pythons-multiprocessing-pool-ma/1816969#1816969),
[mrule](http://stackoverflow.com/questions/3288595/multiprocessing-using-pool-
map-on-a-function-defined-in-a-class), by
[unutbu](http://stackoverflow.com/questions/8804830/python-multiprocessing-
pickling-error)
|
What is the correct way to format long lines of code in python?
Question: I've got some lines of code that return and assign multiple values from a
function, like below. This of course makes it one very long line. What's the
correct way to style/format a line of code like this? I've included a couple
of possibilities that I've come up with.
some_variable_1, \
some_variable_2, \
some_variable_3, \
some_variable_4, \
some_variable_5 = sort_of_long_function_name(parameter_1, parameter_2,
parameter_3, parameter_4)
some_variable_1, some_variable_2, some_variable_3, some_variable_4, \
some_variable_5 = sort_of_long_function_name(parameter_1, parameter_2,
parameter_3, parameter_4)
Edit: Thanks all for the answers. I can't upvote because I'm a noob heh(no
rep), so I just wanted to say that I appreciate it. I've read the style guide
before and typically I do avoid long lines like this. In this case, I feel I
need this function to calculate and return multiple stats. I think I will make
some of my naming a bit more concise and look into returning an object or
named tuple. Thanks!
Answer: You want to _avoid_ getting into that situation. If you have a tuple
assignment for that many names and you cannot even fit that on a line in 80
characters, it is time for a refactor.
For example, you could have your function return a [`namedtuple`
class](https://docs.python.org/2/library/collections.html#collections.namedtuple)
instead:
from collections import namedtuple
Result = namedtuple('Result', 'foo bar spam ham eggs')
def sort_of_long_function_name(arg1, arg2, arg3, arg4):
return Result(foo_result, bar_result, spam_result, ham_result, eggs_result)
result = sort_of_long_function_name(param1, param2, param3, param4, param5)
do_something_with(result.foo)
do_something_else_with(result.bar)
# etc.
Now instead of 5 variables, you have one with helpful named attributes.
This is what the parsing functions in the [`urlparse`
module](https://docs.python.org/2/library/urlparse.html) do, with the
`namedtuple` classes even having some additional methods to re-create the
parsed URL.
|
Python 2.7 read exported variables from bash
Question: I have a python2.7 script which is calling a bash script, inside the bash
script i'm exporting 2 variable i've tried with `declare -x` and with
`export`, then i'm trying to read this variables in the python script using
`os.getenv` and i also tried using `os.environ` but i'm getting a `None`type
each time. Here is a snippet from my scripts:
Python:
def set_perforce_workspace():
global workspace_path
global workspace_root_path
script_path = "somePath"
depot_name = "TestingTools"
dir_to_download = "vtf"
bash_command = "./createWorkspace.sh " + "-d " + depot_name + " -w " \
+ PerforceUtils.WORKSPACE_NAME + " -a " + dir_to_download
print bash_command
print os.getcwd()
try:
os.chdir(script_path)
except OSError as e:
print "Error: {0}".format(e)
print os.getcwd()
return_code = call([bash_command], shell=True)
test = os.getenv("workspace_path")
print "this is test {0}".format(test)
workspace_path = os.getenv("workspace_path")
workspace_root_path = os.getenv("workspace_root_path")
print "This is the return code {0}".format(return_code)
print "this is the workspace path: {0}".format(workspace_path)
print "this is the workspace root path: {0}".format(workspace_root_path)
return return_code
Bash:
declare -x workspace_root_path="$workspaceProjPath"
export workspace_path="$workspaceProjPathLocal"
Answer: From the documentation for
[`os.environ`](https://docs.python.org/2/library/os.html#os.environ):
> This mapping is captured the first time the os module is imported, typically
> during Python startup as part of processing site.py. Changes to the
> environment made after this time are not reflected in os.environ, except for
> changes made by modifying os.environ directly.
So basically when your bash script changes the environment and then goes back
to your python script the environment variables aren't refreshed. Pretty
annoying. As the docs say the best solution is to add your variables to the
environ list directly, like:
os.environ['PATH'] = '/bin/'
How you accomplish this is up to you, piping is a pretty decent way to do it.
Albeit annoying. Unfortunately there is no way to "refresh" the environment
list. In a lot of situations it might be best just to drop your bash script
and somehow adapt it to the python script.
|
Fire and forget task in asyncio
Question: When using Python's `asyncio` library, how can I fire off a task and then not
care about its completion?
## Example
@asyncio.coroutine
def f():
yield From(asyncio.sleep(1))
print("world!")
@asyncio.coroutine
def g():
desired_operation(f())
print("Hello, ")
yield From(asyncio.sleep(2))
>>> loop.run_until_complete(g())
'Hello, world!'
Answer: You're looking for
[`asyncio.ensure_future`](https://docs.python.org/3/library/asyncio-
task.html#asyncio.ensure_future) (or `asyncio.async` if your version of
`trollius`/`asyncio` is too old to have `ensure_future`):
from __future__ import print_function
import trollius as asyncio
from trollius import From
@asyncio.coroutine
def f():
yield From(asyncio.sleep(1))
print("world!")
@asyncio.coroutine
def g():
asyncio.ensure_future(f())
print("Hello, ", end='')
yield From(asyncio.sleep(2))
loop = asyncio.get_event_loop()
loop.run_until_complete(g())
Output:
Hello, world!
|
Django-nonrel with django app engine cannot access the admin interface
Question: I have a Django app which I am trying to get to Django-nonrel so that I can
get it on GAE. The problem though is that numerous times have I tried creating
superuser for the admin interface still when I do **syncdb** , it shows me:
> You just installed Django's auth system, which means you don't have any
> superusers defined.
everytime.Also, I am never able to login into my admin interface by the
created superuser. Also, when I do this:
python manage.py shell
>>> from django.contrib.auth.models import User
>>> User.objects.all()
[]
SO no users are created it seems. I tried to look for the solution and and had
a look at a few questions like these:
[django-nonrel and the admin
page](http://stackoverflow.com/questions/8498837/django-nonrel-and-the-admin-
page)
and a few others. Didn't help either. I would like to mention that I am using
zip downloaded version of django-nonrel 1.6 and djangoappengine by copying
them in my project directory
Just for reference my **settings.py** and **app.yaml** files are as follows:
Settings.py:
# Django settings for flogin project.
# Initialize App Engine and import the default settings (DB backend, etc.).
# If you want to use a different backend you have to remove all occurences
# of "djangoappengine" from this file.
from djangoappengine.settings_base import *
import sys
sys.path.insert(0, 'libs')
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
# Activate django-dbindexer for the default database
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': DATABASES['default']}
AUTOLOAD_SITECONF = 'indexes'
# 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/Chicago'
# 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 = False
# 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 = 'some key not shown here'
# 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 = (
# This loads the index definitions, so it has to come first
'autoload.middleware.AutoloadMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'flogin.urls'
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',
'oauth2_provider',
'social.apps.django_app.default',
'rest_framework_social_oauth2',
'flogin',
'djangoappengine',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'djangotoolbox',
'autoload',
'dbindexer',
# djangoappengine should come last, so it can override a few manage.py commands
)
# 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,
},
}
}
app.yaml
application: flogin
version: 1
runtime: python27
api_version: 1
threadsafe: yes
builtins:
- remote_api: on
inbound_services:
- warmup
handlers:
- url: /_ah/queue/deferred
script: djangoappengine.deferred.handler.application
login: admin
- url: /_ah/stats/.*
script: djangoappengine.appstats.application
- url: /media/admin
static_dir: django/contrib/admin/media
expiration: '0'
- url: /.*
script: djangoappengine.main.application
Answer: Ok, I had the same problem and I found a reason why it's happening. When you
run manage.py with any command except 'runserver' djangoappengine creates in-
memory database for that and I think it's a bug in djangoappengine here, so no
changes is made to local database for 'syncdb' or 'shell' or
'createsuperuser', btw I use v1.7.1 of djangoappengine. When you run
'runserver' command, it first creates in-memory database, but then recreates
it with proper local stored one.
So, how to fix it? The simpliest way is to patch djangoappengine/db/stubs.py,
In the method `def activate_stubs(self, connection):` replace
`self.activate_test_stubs(connection)`
with
`from .base import DATASTORE_PATHS self.activate_test_stubs(connection,
DATASTORE_PATHS['datastore_path'])`
|
using xlwt writing data into the excel but in this code not properly inserting into the column
Question:
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('python')
row = 0
f = open('newfile.txt')
for line in f:
L = line.strip().split()
for i,c in enumerate(L):
sheet.write(row,i,c)
row += 1
wbk.save('examp1.xls')
in this code it is inserted into columns but each column gets iterating not in
the same row
Answer: Remember that python is a language in which code blocks are defined by the
indentation level. If you want to put each field from a CSV into a separate
column in a spreadsheet, the second loop should be an inner loop of the first.
Unless I am very much mistaken you don't want to save the file after every
operation. That would cause a massive slow down.
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('python')
row = 0
f = open('newfile.txt')
for line in f:
L = line.strip().split()
for i,c in enumerate(L):
sheet.write(row,i,c)
row += 1
wbk.save('examp1.xls')
|
Tkinter ttk Combobox Default Value
Question: I'm building a Tkinter application and I came across an issue with setting a
default value to a combobox. I managed to fix the problem, but I am curious to
know why it worked and I would like to know if there is a better way to do it.
I have a `tk.Toplevel()` window pop up with a combobox using the fowling code:
class add_equation():
def __init__(self):
self.add_window = tk.Toplevel()
self.add_window.title("Add Equation Set")
self.add_window.resizable(width=False, height=False)
self.name_entry_var = tk.StringVar()
self.name_entry = ttk.Entry(self.add_window, textvariable=self.name_entry_var, width=30)
self.name_entry.grid(row=1, columnspan=2, stick="w")
self.equation_type_var = tk.StringVar()
self.equation_type = ttk.Combobox(self.add_window, textvariable=self.equation_type_var, values=("System", "Exact", "Import Point List..."), state="readonly", width=28, postcommand =lambda: self.add_window.update())
self.equation_type.current(0)
self.equation_type.grid(row=2, columnspan=2, sticky="w")
self.add_window.update()
The class `add_quation()` is called in the following bit of code:
import tkinter as tk
from tkinter import ttk
class Solver_App(tk.Tk, ttk.Frame):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
list_frame = ttk.Frame(self, height=50)
list_frame.pack(side="top", fill="y", expand=True, anchor="w")
# Button that will call the class add_equation that creates a new window.
add_button = ttk.Button(list_frame, text="Add Equation Set", command=add_equation)
add_button.pack(side="top", expand=False, fill="x", padx=10, pady=5, anchor="n")
app = Solver_App()
app.mainloop()
Looking back at the `add_equation()` class, if you remove
`self.equation_type.current(0)` or `postcommand =lambda:
self.add_window.update()`, the default value will no longer show, but with
both, it works just fine. Why is it working like this instead of only having
`self.equation_type.current(0)`?
I've tried to find a more elegant way of doing this, and I found something
related [over here](http://stackoverflow.com/questions/6876518/set-a-default-
value-for-a-ttk-combobox "Set a default value for a ttk Combobox"), but I had
no luck implementing that method and I assume calling `add_equation()` from a
button command may have something to do with that.
*I'm using Python 3.4 on Mac OS X Yosemite.
Answer: I think this is probably because you're creating a window by calling the
`add_equation` constructor, and that window is immediately garbage collected
(or atleast the python handle to it is) so never gets properly refreshed.
I'd rewrite it as something like this:
class Equation_Window(tk.Toplevel):
def __init__(self):
tk.Toplevel.__init__(self)
self.title("Add Equation Set")
self.resizable(width=False, height=False)
self.name_entry_var = tk.StringVar()
self.name_entry = ttk.Entry(self, textvariable=self.name_entry_var, width=30)
self.name_entry.grid(row=1, columnspan=2, stick="w")
self.equation_type_var = tk.StringVar()
self.equation_type = ttk.Combobox(self, textvariable=self.equation_type_var, values=("System", "Exact", "Import Point List..."), state="readonly", width=28)
self.equation_type.current(0)
self.equation_type.grid(row=2, columnspan=2, sticky="w")
def add_equation():
w = Equation_Window()
w.wait_window()
(everything else remains the same)
I've changed the your `add_equation` class to something derived from a
`tk.Toplevel` (and renamed it), which I think makes more sense. I've then made
`add_equation` a function, and called `wait_window` (which acts like
`mainloop` but just for one window). `wait_window` will keep `w` alive until
the window is closed, and so everything gets refreshed properly.
|
Program is not executing in python
Question: I am using a book for learning python :
There is a file recommendations.py in which I have all this code
When I execute command on command line
reload(recommendations)
>>> recommendations.sim_distance(recommendations.critics,
... 'Lisa Rose','Gene Seymour')
It gives me following error
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
reload(recommendations)
NameError: name 'recommendations' is not defined
Answer: You just need to import `recommendations` before running your script.
|
Installing issues in networkx
Question: I have run the following command
sudo apt-get install python-setuptools
I get `python-setuptools is already the newest version.
Now when I run `import networkx`
I get `ImportError: No module named networkx`
Please help.
Answer: You definitely should use `pip`. It allows you to install Python packages from
their names. Here is an example.
sudo apt-get install python-pip
sudo pip install networkx
Then `networkx` is installed :
$ python
>>> import networkx
>>>
|
Server(Python) - Client(Java) communication using sockets
Question: I try to send a message from server to a client, after client receives the
message, it sends back a message to the server and so on. The problem is with
receiving the message in python. The loop it's stuck there.
import socket
HOST = "localhost"
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
s.bind((HOST, PORT))
except socket.error as err:
print('Bind failed. Error Code : ' .format(err))
s.listen(10)
print("Socket Listening")
conn, addr = s.accept()
while(True):
conn.send(bytes("Message"+"\r\n",'UTF-8'))
print("Message sent")
data = conn.recv(1024)
print(data.decode(encoding='UTF-8'))
* * *
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Main {
static Thread sent;
static Thread receive;
static Socket socket;
public static void main(String args[]){
try {
socket = new Socket("localhost",9999);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sent = new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while(true){
System.out.println("Trying to read...");
String in = stdIn.readLine();
System.out.println(in);
out.print("Try"+"\r\n");
System.out.println("Message sent");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
sent.start();
try {
sent.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Answer: The Python code is fine. The problem is that calling `out.print` in the Java
code does not necessarily cause your message to be sent through the socket
immediately. Add
out.flush();
immediately after
out.print("Try"+"\r\n");
to force the message to be sent through the socket.
([`flush`](https://docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html#flush--)
"flushes" through the stream any data that has not yet been sent.) The Python
should then be able to receive it correctly.
|
Getting error for datetime in python
Question: I have a file named global.py and a function to create report :
import datetime
class customFail(Exception):pass
def createReport(myModule,iOSDevice,iOSVersion):
now=datetime.datetime.now()
resultPath="../Results"
resultFile="Result_%d_%d_%d_%d_%d_%d.html" % (now.day,now.month,now.year,now.hour,now.minute,now.second)
fileName="%s/%s" % (resultPath,resultFile)
fNameObj=open("../Results/resfileName.txt","w") #Writing result filename temporary
fNameObj.write(fileName) #in a file to access this filename by other functions (rePass,resFail)
fileObj=open(fileName,"w")
fileObj.write("<html>")
fileObj.write("<body bgcolor=\"Azure\">")
fileObj.write("<p> </p>")
fileObj.write("<table width=\"600\" border=\"5\">");
fileObj.write("<tr style=\"background-color:LemonChiffon;\">")
fileObj.write("<td width=\"40%\"><b>Module : </b>"+ myModule+"</td>")
fileObj.write("<td width=\"30%\"><b>Time : </b>"+ now.strftime("%d-%m-%Y %H:%M")+"</td>")
fileObj.write("</tr>")
fileObj.write("<tr>")
fileObj.write("</tr>")
fileObj.write("</table>")
fileObj.write("<table width=\"600\" border=\"5\">");
fileObj.write("<tr style=\"background-color:BurlyWood;\">")
fileObj.write("<td width=\"70%\"><b>Device : </b>"+ iOSDevice+" - <b> Version : </b>"+ iOSVersion+"</td>")
fileObj.write("</tr>")
fileObj.write("</table>")
#fileObj.write("<br>")
and a script file where i call this function called scripts.py
import os
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time
import sys
sys.path.append('/Users/admin/Desktop/_Suite/Global Scripts/')
from funcLib import *
from myGlobal import *
wd = deviceSelection();
iOSVersion="i7"
iOSDevice="iPhone"
modName="BAT"
suiteStartTime=0
def main():
start()
fntesttrial();
finish();
def start():
global modName,suiteStartTime
global appName,ctx_app,ctx_simulator
suiteStartTime=time.time();
createReport(modName,iOSDevice,iOSVersion)
stts=api_clr_acnt.fnClearAccount(myDict["UserName"],myDict["Password"],myDict["Environment"])
def fntesttrial():
try:
wd.find_element_by_name("Accept").click()
time.sleep(5)
wd.find_element_by_name("Sign In").click()
time.sleep(5)
wd.find_element_by_name("Need help?").click()
time.sleep(5)
wd.find_element_by_name("Close").click()
time.sleep(5)
finally:
wd.quit()
main()
When I run this i am getting error like :
now=datetime.datetime.now()
NameError: global name 'datetime' is not defined
I am not understanding why I am getting that error. Please help me since i am
new to python.
Answer: **I think you need to import datetime at the top of the script file (code
block 2).** It gives you the error because datetime is indeed undefined in the
script, as it hasn't been imported yet. When you call "createReport()", "now"
can't be defined, as it calls on the datetime module, which isn't imported.
If you wanted, you could write import datetime at the start of the method
definition, but if you called the method twice, it would import datetime
twice, so you're probably better off just importing it at the start of the
second codeblock.
|
python stemming words for local languages
Question: I've some problem to stem words in my local language using rule based
algorithm. so any body who are python literate can help me.
In my language some words are pluralized by repeating the first 2 or 3
characters(sounds).
For example
Diimaa (root word) ==> Diddiimaa(plural word)
Adii (root word) ==> Adadii(plural word)
so now i want my program to reject "Did" from the first example and "Ad" from
the second example
the following is my code and it did not return any result
`def compput(mm):
vv=1
for i in mm:
if seevowel(i)==1:
inxt=mm.index(i)+1
if inxt<len(mm)-1 and seevowel(mm[inxt])==0:
vv=vv+1
return vv
def stemm_maker(tkn):
for i in range(len(tkn)):
if (i[0] == i[2] and i[1] == i[3]):
stem = i[2:]
if compput(stem) > 0:
return stem
elif ((i[0] == i[2] or i[0]== i[3]) and i[1] == i[4]):
stem = i[3:]
if compput(self) > 0:
return stem
else:
return tkn
print(stem)`
Answer: One way to attack this problem is with regular expressions.
Looking at these pairs (found
[here](https://books.google.de/books?id=gTcMvCKcvhsC&lpg=PA230&ots=fHZQACe7xS&dq=%22Diddiimaa%22&pg=PA230#v=onepage&q=%22Diddiimaa%22&f=false)):
adadii adii
babaxxee baxxee
babbareedaa bareedaa
diddiimaa diimaa
gaggaarii gaarii
guguddaa guddaa
hahhamaa hamaa
hahapphii happhii
the rule appears to be
if the word starts with XY...
then the reduplicated word is either XYXY... or XYXXY...
In the regex language this can be expressed as
^(.)(.)\1?(?=\1\2)
which means:
char 1
char 2
maybe char 1
followed by
char 1
char 2
Complete example:
test = {
'adadii': 'adii',
'babaxxee': 'baxxee',
'babbareedaa': 'bareedaa',
'diddiimaa': 'diimaa',
'gaggaarii': 'gaarii',
'guguddaa': 'guddaa',
'hahhamaa': 'hamaa',
'hahapphii': 'happhii',
}
import re
def singularize(word):
m = re.match(r'^(.)(.)\1?(?=\1\2)', word)
if m:
return word[len(m.group(0)):]
return word
for p, s in test.items():
assert singularize(p) == s
|
Python handling .net exceptions makes PyQt unable to use OLE
Question: I have a large PyQt4 based Python program. In some places it needs to be able
to control a piece of hardware for which the manufacturer provides a .net
interface. I need to be able to load the relevant library if it's available,
and ignore it otherwise.
If the library is not present, and I try and report the exception, then Qt
reports an OLE initialization error, and all drag-and-drop and copy/paste
functionality in my program fails.
Here is a minimal example:
import clr
import sys
from PyQt4 import QtGui
import logging
logger = logging.getLogger(__name__)
try:
clr.AddReference('foo') #This doesn't exist
except Exception as e:
logger.info('Exception: {0}'.format(e))
app = QtGui.QApplication(sys.argv)
app.exec_()
This results in the Qt error:
Qt: Could not initialize OLE (error 80010106)
The program runs, but whenever I try and copy/paste, I get:
QClipboard::setMimeData: Failed to set data on clipboard ()
and drag-and-drop doesn't work at all.
If the library does exist, the code runs without a problem. Interestingly, if
I don't try and look at the exception, (i.e. replace the except block with
"pass"), the code also runs fine. Somehow, trying to see the exception messes
up the .net interface.
Is there a better way to check whether a library exists before trying to add
it as a reference? Is there any way to reset the .net connection before
running QApplication, to guarantee that this sort of thing doesn't happen in
the future? Any ideas why this problem happens?
Answer: There is a better way than try to `clr.AddReference()` \- the method is called
`clr.FindAssembly('DOT_NET_Assembly_Name')` which returns full path to
assembly or `None`.
|
Python Socket Timing out
Question: I am attempting to open a socket to google on port 80 but for the life of me I
can't figure out why this is timing out. If I don't set a timeout it just
hangs indefinitely.
I don't think my companies firewall is blocking this request. I can navigate
to google.com in the browser so there shouldn't be any hangups here.
import socket
HOST = '173.194.121.39'
PORT = 80
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.settimeout(20)
data = s.recv(1024)
print(data)
s.close()
Answer: This will work:
import socket
HOST = 'www.google.com'
PORT = 80
IP = socket.gethostbyname(HOST)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
message = b"GET / HTTP/1.1\r\n\r\n"
s.sendall(message)
data = s.recv(1024)
print(data.decode('utf-8'))
s.close()
What was wrong with you code: Your code was directly using the IP, i tried
looking up for the IP by hostname using `socket.gethostbyname()`. (_i dont
know why :P_)
You were expecting data to be returned without sending any. I used `s.sendall`
method to send a HTTP request (since you're using python3, the data must be
sent in bytes). Also decoded the data returned to print.
I hope, it will work for you too.
|
In Python, how can a function of a script be called from within a module that is imported by that script?
Question: I have a set of scripts that each have their own specialized termination
functions. Many of these scripts call a module of general functions. Some of
these module functions should direct the script to terminate.
I am aware that the standard approach would be to have the module functions
return values that are interpreted by the scripts (in this case, in a way that
causes the scripts to terminate), but I would like to know how to call the
terminate function of a script from the module.
Answer: Your scripts should register their special termination functions using
`atexit`. (See <https://docs.python.org/3.5/library/atexit.html>)
Then they will be called no matter why it terminates. Your general module can
then just use `sys.exit()`.
|
Python error for request.get
Question: I am trying to write a Python script which enables me to acces a webpage and
download a file from that page. My first attempt was to simply get to that
page and i tried the following code:
import requests
url = 'https://www.google.com/?gws_rd=ssl' #using google as an example
r = requests.get(url)
print(r.url)
I am given this error:
runfile('C:/Users/ME/Desktop/TMS502.py', wdir='C:/Users/ME/Desktop')
Traceback (most recent call last):
File "<ipython-input-23-bc585dcceef8>", line 1, in <module>
runfile('C:/Users/ME/Desktop/TMS502.py', wdir='C:/Users/ME/Desktop')
File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 585, in runfile
execfile(filename, namespace)
File "C:/Users/ME/Desktop/TMS502.py", line 16, in <module>
r = requests.get(url)
File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\requests\api.py", line 55, in get
return request('get', url, **kwargs)
File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\requests\api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\requests\sessions.py", line 456, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\requests\sessions.py", line 559, in send
r = adapter.send(request, **kwargs)
File "C:\Users\ME\AppData\Local\Continuum\Anaconda\lib\site-packages\requests\adapters.py", line 375, in send
raise ConnectionError(e, request=request)
ConnectionError: HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: /?gws_rd=ssl (Caused by <class 'socket.error'>: [Errno 10054] An existing connection was forcibly closed by the remote host)
Can someone please help me?
Answer: You are getting that error because the remote side (in this case Google) is
closing your requests or you are otherwise no longer able to establish a
connection to it.
From the error:
ConnectionError: HTTPSConnectionPool(host='www.google.com', port=443):
Max retries exceeded with url: /?gws_rd=ssl
(Caused by <class 'socket.error'>: [Errno 10054] An existing connection was forcibly closed by the remote host)
We can look into the
[source](https://github.com/kennethreitz/requests/blob/8b5e457b756b2ab4c02473f7a42c2e0201ecc7e9/requests/packages/urllib3/exceptions.py#L62-L78)
for a hint:
class MaxRetryError(RequestError):
"""Raised when the maximum number of retries is exceeded.
:param pool: The connection pool
:type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`
:param string url: The requested Url
:param exceptions.Exception reason: The underlying error
"""
def __init__(self, pool, url, reason=None):
self.reason = reason
message = "Max retries exceeded with url: %s (Caused by %r)" % (
url, reason)
RequestError.__init__(self, pool, url, message)
Try another example host and your code should work, such as
<https://example.org>.
The error message "An existing connection was forcibly closed by the remote
host" is coming from your operating system (Windows) and Requests is showing
you this text in an attempt to be helpful.
|
Python: Parse String as Date with Formatting
Question: A user can input a string and the string contains a date in the following
formats `MM/DD/YY` or `MM/DD/YYYY`. Is there an efficient way to pull the date
from the string? I was thinking of using RegEx for `\d+\/\d+\/\d+`. I also
want the ability to be able to sort the dates. I.e. if the strings contain
`8/17/15` and `08/16/2015`, it would list the 8/16 date first and then 8/17
Answer: you could also try strptime:
import time
dates = ('08/17/15', '8/16/2015')
for date in dates:
print(date)
ret = None
try:
ret = time.strptime(date, "%m/%d/%Y")
except ValueError:
ret = time.strptime(date, "%m/%d/%y")
print(ret)
* * *
**UPDATE**
update after comments:
this way you will get a valid date back or `None` if the date can not be
parsed:
import time
dates = ('08/17/15', '8/16/2015', '02/31/15')
for date in dates:
print(date)
ret = None
try:
ret = time.strptime(date, "%m/%d/%Y")
except ValueError:
try:
ret = time.strptime(date, "%m/%d/%y")
except ValueError:
pass
print(ret)
* * *
**UPDATE** **2**
one more update after the comments about the requirements.
this is a version (it only takes care of the dates; not the text before/after.
but using the regex group this can easily be extracted):
import re
import time
dates = ('foo 1 08/17/15', '8/16/2015 bar 2', 'foo 3 02/31/15 bar 4')
for date in dates:
print(date)
match = re.search('(?P<date>[0-9]+/[0-9]+/[0-9]+)', date)
date_str = match.group('date')
ret = None
try:
ret = time.strptime(date_str, "%m/%d/%Y")
except ValueError:
try:
ret = time.strptime(date_str, "%m/%d/%y")
except ValueError:
pass
print(ret)
|
Python vs Jython - MuleSoft
Question: I have a Python script that converts JSON to CSV successfully when run in
PyCharm. When I move that Python script into a Python Transformer in MuleSoft,
the script fails with the error:
> TypeError: unicode indices must be integers in at line number 10
> (javax.script.ScriptException). Message payload is of type: String
> (org.mule.api.transformer.TransformerMessagingException). Message payload is
> of type: String
What is the difference between Python and Jython in this context? I don't get
it!
Here is the Python:
import csv
import io
data = message.getInvocationProperty("my_JSON")
output = io.BytesIO()
writer = csv.writer(output)
for item in data:
writer.writerow(([item['observationid'], item['fkey_observation'], item['value'], item['participantid'], item['uom'], item['finishtime'], item['starttime'], item['observedproperty'], item['measuretime'], item['measurementid'], item['longitude'], item['identifier'], item['latitude']]))
result = output.getvalue()
`"my_JSON"` is a variable containing the JSON.
Answer: You seem to have forgotten to parse the JSON, like so: `data =
json.loads(data)`.
Without that, `data` is a `str`, `item` is a `str` of length 1, and
`item['observationid']` raises `TypeError`.
|
Django 1.8 template's URL tag TypeError
Question: I am trying to learn how to use the Django template's URL tag to make my code
more generic, but I am having some exception being raised.
Exception Type: TypeError
Exception Value: argument to reversed() must be a sequence
Here is my global urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls'))
]
Here is my app urls.py
from django.conf.urls import url
from . import views
urlpatterns = {
url(r'^$', views.index, name='index'),
url(r'^(?P<id>[0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<id>[0-9]+)/results/$', views.results, name='results'),
url(r'^(?P<id>[0-9]+)/vote/$', views.vote, name='vote')
}
And here is one template where I am trying to use the feature.
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{ question.content }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Traceback:
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/polydo_s/Projects/Modeling/app/polls/views.py" in index
11. return render(request, 'polls/index.html', context)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/shortcuts.py" in render
67. template_name, context, request=request, using=using)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/loader.py" in render_to_string
99. return template.render(context, request)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/backends/django.py" in render
74. return self.template.render(context)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/base.py" in render
209. return self._render(context)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/base.py" in _render
201. return self.nodelist.render(context)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/base.py" in render
903. bit = self.render_node(node, context)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/debug.py" in render_node
79. return node.render(context)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/defaulttags.py" in render
329. return nodelist.render(context)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/base.py" in render
903. bit = self.render_node(node, context)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/debug.py" in render_node
79. return node.render(context)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/defaulttags.py" in render
217. nodelist.append(node.render(context))
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/template/defaulttags.py" in render
493. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/core/urlresolvers.py" in reverse
579. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
433. self._populate()
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/core/urlresolvers.py" in _populate
308. for name in pattern.reverse_dict:
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/core/urlresolvers.py" in reverse_dict
338. self._populate()
File "/home/polydo_s/Projects/Modeling/venv/lib/python3.4/site-packages/django/core/urlresolvers.py" in _populate
285. for pattern in reversed(self.url_patterns):
I have been looking for this for hours, and I seem to follow all the
guidelines to make this work, but of course something must be wrong.
Answer: You've defined `urlpatterns` as a `set` \- `{` and `}`. You need a `list` \-
`[` and `]`.
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<id>[0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<id>[0-9]+)/results/$', views.results, name='results'),
url(r'^(?P<id>[0-9]+)/vote/$', views.vote, name='vote')
]
|
python mock default init argument of class
Question: I want to mock the default argument in a class constructor:
class A (object):
def __init__(self, connection=DefaultConnection()):
self.connection = connection
I want to mock `DefaultConnection` in my unittests, but it doesn't work when
passed in as a default value.
Answer: You can use patch to
[patch](https://docs.python.org/3/library/unittest.mock.html#patch) the
module, and then you can set the return value as a Mock.
# --- a.py (in package path x.y) --
from c import DefaultConnection
class A (object):
def __init__(self, connection=DefaultConnection()):
self.connection = connection
#---- a_test.py ----
from mock import patch
from a import A
@patch('x.y.a.DefaultConnection')
def test(def_conn_mock):
conn_mock = Mock()
def_conn_mock.return_value = conn_mock
a_obj = A()
....
|
Python sqrt() doubles runtime?
Question: I've recently started learning Python. My apologies if this is really obvious.
I am following along with the 2008 MIT open course on Computer Science and am
working on the problem of calculating the 1000th prime integer. Python 2.7.3,
Win7 lappy (cough, cough...)
Here's the code I came up with:
num = 3
primeList = [2]
while len(primeList) < 1000:
for i in primeList:
if num % i == 0:
break
else:
primeList.append(num)
num += 1
print "The 1,000th PRIME integer is", primeList[999]
One of the assignment conditions was to only check odd numbers. Given the
starting `num` is three, I figured it would be easy enough to simply change
`num+=1` to `num+=2`. Of note: I won't bore you with the detailed code I
composed, but while writing this I was using a very verbose mode of printing
out the results of each check, whether or not it was prime, which number was
being checked, which integer divided into it if it wasn't prime & such (again,
sorry - newB!)
At this point I became curious to test if this was actually taking less time
to compute - seemed like if half the numbers are being checked for primacy, it
should take half the time, no?
I imported the time module to check how long this was taking. Computing to the
1000th was pretty quick either way so I increased the number of primes I was
searching for to the 10,000th and didn't see any significant difference.
between `num+=1` & `num+=2`
import time
start = time.time()
num = 3
primeList = [2]
while len(primeList) < 10000:
for i in primeList:
if num % i == 0:
break
else:
primeList.append(num)
num += 2
print "The 10,000th PRIME integer is", primeList[9999]
end = time.time()
print "That took %.3f seconds" % (end-start)
Sometimes the `n+=2` even took a couple milliseconds longer. ?. I thought this
was odd and was wondering if someone could help me understand why - or, more
to the point: how?
Furthermore, I next imported the sqrt() function thinking this would reduce
the number of integers being checked before confirming primacy, but this
doubled the runtime =^O.
import time
start = time.time()
from math import sqrt
num = 3
primeList = [2]
while len(primeList) < 100000:
for i in primeList:
if i <= sqrt(num):
if num % i == 0:
break
else:
primeList.append(num)
num += 2
print "The 100,000th PRIME integer is",primeList[99999]
end = time.time()
print 'that took', end - start, "seconds, or", (end-start)/60, "minutes"
Certainly - it might be the way I've written my code! If not, I'm curious what
exactly I am invoking here that is taking so long?
Thank you!
Answer: Two things.
First, you're calculating `sqrt(n)` on every loop iteration. This will add
work, because it's something else your code now has to do on every pass
through the loop.
Second, the way you're using `sqrt` doesn't reduce the number of numbers it
checks, because you don't exit the loop even when `i` is bigger than
`sqrt(n)`. So it keeps doing a do-nothing loop for all the higher numbers.
Try this instead:
while len(primeList) < 100000:
rootN = sqrt(num)
for i in primeList:
if i <= rootN:
if num % i == 0:
break
else:
primeList.append(num)
break
else:
primeList.append(num)
num += 2
This finds 100,000 primes in about 3 seconds on my machine.
|
How to connect Twilio python program to local server?
Question: So I saw this amazing hackathon project, and I would like to test it out.
Here is the link for your reference: <https://github.com/ionambrinoc/oxhack>
I know how to run android apps. Just run it on Android Eclipse, and it works
as I expected. It sends the messages to the twilio backend. I got the project
from github, and I want to try it, but their twilio IDs expired. So I got a
new twilio account, and I tried to replace their ids with mine. And I assumed
that App SIDs are the same as App Secret Keys. (Are they?)
I tried to run my code with `python hello.py` on terminal but I got this HUGE
error.
`TypeError TypeError: expected string or buffer ... The debugger caught an
exception in your WSGI application. You can now look at the traceback which
led to the error... You can execute arbitrary Python code in the stack frames
and there are some extra helpers available for introspection: dump() shows all
variables in the frame dump(obj) dumps all that's known about the object`
I also have some questions about my code. I put the questions in comments in
my python code. Questions are in CAPS
from flask import Flask, session, redirect, url_for, escape, request
from twilio.rest import TwilioRestClient
import twilio.twiml
import requests
import json
import httplib
account_sid = "SOME_ACCOUNT_SID"
auth_token = "SOME_AUTH_TOKEN"
client = TwilioRestClient(account_sid, auth_token)
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST']) #WHAT DOES THIS MEAN?
def index():
phonenumber = request.values.get('From', None)
body = request.values.get('Body', None)
print(body)
action = json.loads(body)
current = action['current']
desired = action['desired']
lang = action['lang']
payload={'current':current,'desired':desired,'lang':lang}
url='http://school/index.php' #The dev used this link. WHAT DOES IT MEAN?
r = requests.post(url,data=payload)
print(payload)
print(r.text)
response=r.text
message = client.messages.create(body=response,
to=phonenumber,
from_="+1408MYTWILIO")
return message.sid
# IS THE APP SID SAME AS APP SECRET KEY?
app.secret_key = 'MY_APP_SECRET_KEY'
if __name__ == '__main__':
app.run(debug=True)
If you can answer any of these questions, your help will be greatly
appreciate. As I am still learning, and I really want to see how this
hackathon project works.
Answer: Twilio developer evangelist here.
I can explain some of what is going on there, but probably not all of it I'm
afraid.
Firstly:
@app.route('/', methods=['GET', 'POST']) #WHAT DOES THIS MEAN?
This is a decorator function in python. In the context of this application it
applies to the method below `def index():`. It means that when the Flask
application receives a `GET` or `POST` request to `'/'` (the root path) it
will execute the `index` method.
# IS THE APP SID SAME AS APP SECRET KEY?
app.secret_key = 'MY_APP_SECRET_KEY'
The secret key for the application is not any of the credentials you get from
Twilio. The secret key should be a long random string. It is used with
sessions in Flask and the secret key is used to sign the session
cryptographically. There is more information on this in the [Flask
documentation on
settings](http://flask.pocoo.org/docs/0.10/quickstart/#sessions).
The following lines however:
payload={'current':current,'desired':desired,'lang':lang}
url='http://school/index.php' #The dev used this link. WHAT DOES IT MEAN?
r = requests.post(url,data=payload)
including the odd `http://school/index.php`, I can't really explain. What I do
know is that the hack used the [Esri API](https://developers.arcgis.com/en/)
to find directions between two points. It looks as though this section is
trying to do that. I have no idea what was behind that URL for the team, it
looks as though it may have been some sort of proxy. In order to get this
running again, you may need to look through the [Esri API
documentation](https://developers.arcgis.com/documentation/) and find out how
to get the text description for a route between two places. If you need help
with that, I suggest you give [James
Milner](https://twitter.com/jameslmilner), Esri developer evangelist, a shout.
Hope this helps!
|
Unable to download binascii
Question: Hi i am a newbie in python. I have installed python 2.7.10 in windows(64 bit).
I tried installing certain packages like binascii and zlib for my program but
it is throwing the following error: Could not find a version that satisfies
the requirement binascii (from versions: ) No matching distributions found for
binascii. I used the command: pip install binascii But I have successfully
used pip command to install packages like requests suitcase etc.. How to
rectify this error?
Answer: Python 2.x and 3.x has binascii built-in. You should have `#import binascii`
at the start of your code if you want to use it.
|
speech recognition python code not working
Question: I am running the following code in Python 2.7 with pyAudio installed.
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source: # use the default microphone as the audio source
audio = r.listen(source) # listen for the first phrase and extract it into audio data
try:
print("You said " + r.recognize(audio)) # recognize speech using Google Speech Recognition
except LookupError: # speech is unintelligible
print("Could not understand audio")
The output gives a blinking pointer. That's it. Please help, as I am new to
this.
Answer: The possible reason could be that the `recognizer_instance.energy_threshold`
property is probably set to a value that is too high to start off with. You
should decrease this threshold, or call
`recognizer_instance.adjust_for_ambient_noise(source, duration = 1)`. You can
learn more about it at [Speech
Recognition](https://github.com/Uberi/speech_recognition)
|
Plotting bar chart -colors python
Question: I have a pandas dataframe that I want to plot as a barchart the data has the
following form;
Year ISO Value Color
2007 GBR 500 0.303
DEU 444 0.875
FRA 987 0.777
2008 GBR 658 0.303
USA 432 0.588
DEU 564 0.875
2009 ... etc
i tried to iterate over the data in the follow way;
import matplotlib.pyplot as plt
import matplotlib.cm as cm
conditions=np.unique[df['Color']]
plt.figure()
ax=plt.gca()
for i,cond in enumerate(conditions):
print 'cond: ',cond
df['Value'].plot(kind='bar', ax=ax, color=cm.Accent(float(i)/n))
minor_XT=ax.get_xaxis().get_majorticklocs()
df['ISO']=minor_XT
major_XT=df.groupby(by=df.index.get_level_values(0)).first()['ISO'].tolist()
df.__delitem__('ISO')
plt.xticks(rotation=70)
ax.set_xticks(minor_XT, minor=True)
ax.set_xticklabels(df.index.get_level_values(1), minor=True, rotation=70)
ax.tick_params(which='major', pad=45)
_=plt.xticks(major_XT, (df.index.get_level_values(0)).unique(), rotation=0)
plt.tight_layout()
plt.show()
But it all out in one color, any suggestions as to what I am doing wrong?
Answer: Since `df['Value'].plot(kind='bar')` will plot all your bars, you do not need
to iterate over you `conditions`. Also, as `plot(kind='bar')` essentially
calls `matplotlib.pyplot.bar`, we can feed it a list of colors of the same
length as our data array, and it will color each bar using those colors.
Here's a slightly simplified example (I'll leave you to figure out the ticks
and tick labels):
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
df = pd.DataFrame([
[2007,'GBR',500,0.303],
[2007,'DEU',444,0.875],
[2007,'FRA',987,0.777],
[2008,'GBR',658,0.303],
[2008,'USA',432,0.588],
[2008,'DEU',564,0.875]],
columns=['Year','ISO','Value','Color'])
colors = cm.Accent(df['Color']/len(df['Color']))
fig=plt.figure()
ax=fig.add_subplot(111)
df['Value'].plot(kind='bar',ax=ax,color=colors)
plt.show()
[](http://i.stack.imgur.com/LL3FK.png)
|
Python 3.4 - 'module' has no attribute 'send_sms'
Question: For some reason I cannot execute the function of another script even though i
imported that module.
The relevant code for 'master_module.py' goes like this:
import sms_values
class ClientThread(threading.Thread): # Class that implements the client threads in this server
def __init__(self, client_sock): # Initialize the object, save the socket that this thread will use.
threading.Thread.__init__(self)
self.client = client_sock
def run(self): # Thread's main loop. Once this function returns, the thread is finished and dies.
global QUIT # Need to declare QUIT as global, since the method can change it
done = False
cmd = self.readline() # Read data from the socket and process it
while not done:
if 'quit' == cmd:
self.writeline('Ok, bye. Server shut down')
QUIT = True
done = True
elif 'bye' == cmd:
self.writeline('Ok, bye. Thread closed')
done = True
elif 'send' == cmd:
sms_values.send_sms()
self.writeline('text should be sent')
done = True
else:
self.writeline(self.name)
cmd = self.readline()
self.client.close() # Make sure socket is closed when we're done with it
return
Notes:
The entire code is omitted for clarfication of where the error is
There is no `__name__ == '__main__'` block in `sms_values.py.`
`send_sms()` is not defined inside a class
No indentation on define line, so it's module-level.
Here I'm trying to execute a function from another module in a threaded
continuously run server with the conditional 'send' written in user console.
And this is the code i'm running contained in sms_values.py:
def send_sms():
try:
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 80
ss.connect((127.0.0.1, port))
a = url.encode('ascii') # string needed to change into bytecode
print(sys.stderr, 'sending "%s"' % a)
ss.sendall(a)
amount_recieved = 0
amount_recieved = len(a)
while amount_recieved < amount_expected:
data = ss.recv(180)
amount_recieved += len(data)
print(sys.stderr, 'closing socket')
ss.close()
Note: The entire code is omitted for clarfication of what function i'm
calling.
Fairly straight forward, I just want to send a http POST / GET command to a
router when someone types send in the continuous run server. However traceback
flags up this:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python34\lib\threading.py, line 920, in_bootstrap_inner
self.run()
File "C:\Users\Savag\PycharmProjects\master_module.py", in line 29, in run
sms_values.send_sms()
AttributeError: 'module object has no attribute 'send_sms'
Can anyone please shine some light on this?
I sort of suspect it's because i'm working within a class on another module?
I'm not sure if that even matters. Other module/attributeerror answers have
either not been answered or don't help this situation.
Now I have imported the other module, `from sub_module import sms_values` also
doesn't work for me.
Answer: So yet again i've answered my own question. All that needed to happen was that
the module needed to be stored to a value. Adding:
`z = sms_values`
then `z.sendsms()` in the `elif 'send' = cmd:` loop, worked.
|
Python not recalling variable (pycharm)
Question: Does Anyone Know whats wrong with calling the input at the beginning of the
code where i ask someone to input the number they wish to proceed to for some
reason it doesn't want to do it
__author__ = 'kowalczk'
print ("Welcome to my Program")
print ("It has many functions. If you wish to:")
print ("- Interact with the PC - Press 1")
print ("- Add, Subtract, Multiply Or Divide two numbers - Press 2")
print ("- Put any number of words in alphabetical order - Press 3")
print ("- Display the exact date and time - Press 4")
print ("- Count to any number you like - Press 5")
print ("- Cycle through the whole program - Press 6")
Command = float(input())
if Command == "1":
negative = "angry","depressed","confused","helpless","irritated","lousy","upset","incapable","frustrated","resentful","disgusting","distrustful","distressed","inflamed","abominable","misgiving","woeful","provoked","terrible","lost","pathetic","incensed","in despair","unsure","tragic","infuriated","sulky","uneasy","in a stew","cross","bad","pessimistic","dominated","worked up","a sense of loss","tense","boiling","fuming","indignant","indifferent","afraid","hurt","sad","insensitive","fearful","crushed","tearful","dull","terrified","tormented","sorrowful","nonchalant","suspicious","deprived","pained","neutral","anxious","pained","grief","reserved","alarmed","tortured","anguish","weary","panic","dejected","desolate","bored","nervous","rejected","desperate","preoccupied","scared","injured","pessimistic","cold","worried","offended","unhappy","disinterested","frightened","afflicted","lonely","lifeless","timid","aching","grieved","shaky","victimized","mournful","restless","heartbroken","dismayed","doubtful","agonized","threatened","appalled","cowardly","humiliated","quaking","wronged","menaced","alienated","wary"
positive = "open","happy","alive","good","understanding","great","playful","calm","confident","gay","courageous","peaceful","reliable","joyous","energetic","at ease","easy","lucky","liberated","comfortable","amazed","fortunate","optimistic","pleased","free","delighted","provocative","encouraged","sympathetic","overjoyed","impulsive","clever","interested","gleeful","free","surprised","satisfied","thankful","frisky","content","receptive","important","animated","quiet","accepting","festive","spirited","certain","kind","ecstatic","thrilled","relaxed","satisfied","wonderful","serene","glad","free and easy","cheerful","bright","sunny","blessed","merry","reassured","elated","jubilant","love","interested","positive","strong","loving","concerned","eager","impulsive","considerate","affected","keen","free","affectionate","fascinated","earnest","sure","sensitive","intrigued","intent","certain","tender","absorbed","anxious","rebellious","devoted","inquisitive","inspired","unique","attracted","nosy","determined","dynamic","passionate","snoopy","excited","tenacious","admiration","engrossed","enthusiastic","hardy","warm","curious","bold","secure","touched","brave","sympathy","daring","close","challenged","loved","optimistic","comforted","re-enforced","drawn toward","confident","hopeful"
print ("Please tell me your name")
name = input()
print ("So", name, ",how are you feeling today?")
feeling = input().lower()
while feeling is "":
print ("How are you feeling today?")
reason = input()
if feeling in negative:
print ("Why is that", name)
reason = input()
while reason is "":
print ("Why is that?")
reason = input()
elif feeling in positive:
print ("That's great", name)
elif Command == "2":
print ("In this section of my program i will calculate anything that you need me to, press enter to continue")
input()
print ("If you wish to add press 1, subtract press 2, multiply press 3 or divide press 4. If you wish to exit press enter")
operation = input()
if operation == "1":
print ("Input first number")
n1 = float(input())
print ("Input second number")
n2 = float(input())
print (n1, "add", n2, "is", n1 + n2)
if operation == "2":
print ("Input first number")
n1 = float(input())
print ("Input second number")
n2 = float(input())
print (n1, "takeaway", n2, "is", n1 - n2)
if operation == "3":
print ("Input first number")
n1 = float(input())
print ("Input second number")
n2 = float(input())
print (n1, "times by", n2, "is", n1 * n2)
if operation == "4":
print ("Input first number")
n1 = float(input())
print ("Input second number")
n2 = float(input())
print (n1, "divided by", n2, "is", n1 / n2)
elif Command == "3":
print ("Now i will put some words in order for you. please tell me how much words you wish me to put in order for you")
amount = int(input())
#create a list
mywords = list()
#use a simple counter
counter = 0
# loop through
while counter < amount:
#get input from user
word = input('Enter word: ')
#add the word to the list
mywords.append(word)
#add one to the counter
counter = counter + 1
#get creative with sort etc.
print (sorted(mywords))
elif Command == "4":
print ("This is the exact date and time. In the form yyyy-mm-dd and hh-mm-ss-ms")
print("Press enter to show")
input()
#This code prints date and time originally in the form yyyy-mm-dd
#hh:mm:ss.ssssss
from datetime import datetime
now = datetime.now()
print (now)
print("This is the date in the form dd-mm-yyyy")
print("Press enter to show")
input()
#This shows date in the format dd-mm-yyyy
print (now.day, - now.month, - now.year)
elif Command == "5":
print ("Now i will count to any number you wish me to count to")
print("Press enter to continue")
input()
print ("Tell me what number you wish me to count to")
CountTo = float(input())
x = 0
while x < CountTo:
x = x + 1
print (x)
Im also getting an error regarding the if feeling in positive: for some reason
i cant get that to work asswell
Answer: You are converting your `input()` return to float , in the line -
Command = float(input())
And then you are checking this `Command` against strings, in lines like -
if Command == "1":
They will not match, since strings would never be equal to `float` . You do
not need to do the float convertsion -
Command = input()
* * *
Also, you should fix the indentation, indentation is very important in Python,
it is used to define blocks.
Each separate block should be indented at a particular level from the previous
block , the recommended indentation is 4 spaces.
* * *
For the second issue said in the comments -
> line 29 elif feeling in positive: ^ SyntaxError: invalid syntax
The issue is in lines -
if feeling in negative:
print ("Why is that", name)
reason = input()
while reason is "":
print ("Why is that?")
reason = input()
elif feeling in positive:
This is occuring because you have an `elif` part without an if part. Most
probably, you want to indent the `while` part inside the `if` block, if so
_indent_ it.
|
py2neo Can't run GraphServer
Question: I've problems using the server from the py2neo package.
Here is what I try:
from py2neo.server import GraphServer
server = GraphServer()
This leads to the following exception:
FileNotFoundError: [Errno 2] No such file or directory: '.\\conf\\neo4j-server.properties'
So I looked up the installation:
server = GraphServer("C:\Program Files (x86)\\Neo4j Community\\bin")
where I get the same Exception:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Program Files (x86)\\Neo4j Community\\bin\\conf\\neo4j-server.properties'
I looked where the neo4j-server.properties is. It's in
C:/Users/Me/AppData/Roaming/Neo4j_Community/ but if I use that, it's not
working either...
py2neo version: 2.0.7. neo4j version 2.2.1 Python 3.4 Windows 10.
I figure there must be something wrong with the path, but I didn't found
anything to fix that.
What I'm trying to achieve: I want a function that shuts down the server if it
is running and start a new process with a database that I use only for testing
(and end the server and restart the old Graph after running the tests). Until
now I do that manualy...
Thanks a lot
Answer: As mentioned on the server page in the docs, this module is built on Linux and
will likely only work there. I don't support this functionality under Windows.
<http://py2neo.org/2.0/server.html>
|
Python Read selected Excel columns into arrays
Question: I have an excel spreadsheet that I need to read the values into arrays as
follows
A[0] to A[24] needs to have the values of E4 to E28
B[0] to B[24] needs to have the values of H4 to H28
C[0] to C[24] needs to have the values of K4 to K28
and so on where I am reading every 3rd column for a total of 7 columns.
How would I do this in Python 2.7? Any suggestions or help would be great. I
have worked out how to read a single cell into a variable, but need to make
this a less manual process than have to manually read and assign 175 cells.
Answer: You can use [`openpyxl`](https://bitbucket.org/openpyxl/openpyxl). A simple
example follows.
If you have this excel document, say `Workbook1.xlsx`:
[](http://i.stack.imgur.com/3ZM8u.png)
import openpyxl as px
W = px.load_workbook('Workbook1.xlsx', use_iterators = True)
p = W.get_sheet_by_name(name = 'Sheet1')
print p['A1'].value
print [ p['A%s'%i].value for i in range(1,10) ]
will print:
1
[1, 2, 3, 4, 5, 6, 7, 8, 9]
|
How to delete a particular key(for current session) from Flask-KVSession?
Question: I am using Flask kvsession to avoid replay attacks, as the client side cookie
based session used by Flask-login are prone to it. Eg: If on /index page your
cookie in the header is set for your app header like myapp_session : 'value1'
and if you navigate to /important page you will get a new header like
myapp_session : 'value2' so if a hacker gets 'value1' he can perform replay
attacks and misuse it, as it is never invalidated.
To solve this I am using flask-kvsession which stores the session cookie
header value in a cache or some backend. SO basically only one myapp_session
is generated and invalidated when you logout. But the problem is :-
__init__.py
from simplekv.memory.redisstore import RedisStore
import redis
store = RedisStore(redis.StrictRedis())
#store = memcache.Client(['127.0.0.1:11211'], debug =0)
store.ttl_support = True
app = create_app(__name__)
current_kvsession = KVSessionExtension(store, app)
If you look at the cleanup_session part of the code for kv-session
<http://pythonhosted.org/Flask-
KVSession/#flask_kvsession.KVSessionExtension.cleanup_sessions>
It only deletes the expired sessions. But If I want to explicitly delete the
value for the current myapp_session for a particular user on logout, how do I
do that?
@app.before_request
def redirect_if_logout():
if request.path == url_for('logout'):
for key in app.kvsession_store.keys():
logger.debug(key)
m = current_kvsession.key_regex.match(key)
logger.debug('found %s', m)
app.kvsession_store.delete(key)
But this deletes all the keys as I don`t know what the unique key for the
current session is.
Q2. Also, how to use memcache instead of redis as it doesn`t have the
app.kvsession_store.keys() function and gives i/o error.
Answer: I think I just figured the 1st part of your question on how you can delete the
specific key on logout.
As mentioned in the docs:
> Internally, Flask-KVSession stores session ids that are serialized as
> KEY_CREATED, where KEY is a random number (the sessions “true” id) and
> CREATED a UNIX-timestamp of when the session was created.
Sample cookie value that gets created on client side (you can check with that
cookie manager extenion for firefox):
> c823af88aedaf496_571b3fd5.4kv9X8UvyQqtCtNV87jTxy3Zcqc
and session id stored in redis as key:
> c823af88aedaf496_571b3fd5
So on logout handler, you just need to read the cookie value, split it and use
the first part of the string:
Sample Code which worked for me:
import redis
from flask import Flask
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
store = RedisStore(redis.StrictRedis())
app = Flask(__name__)
KVSessionExtension(store, app)
#Logout Handler
@app.route('/logout', methods=['GET'])
def logout():
#here you are reading the cookie
cookie_val = request.cookies.get('session').split(".")[0]
store.delete(cookie_val)
and since you have added ttl_support:
store.ttl_support = True
It will match the TTL(seconds) value from permanent_session_lifetime, if you
have set that in config file or in the beginning of your app.py file.
For example, in my application I have set in the beginning of app.py file as:
session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)
now, when I logout, it deletes the key in redis but it will not be removed
until TTL for that turns to 0 from 300 (5 Min as mentioned in
permanent_session_lifetime value ).
If you want to remove it from redis immediately, for that you can manually
change the app.permanent_session_lifetime to 1 second, which will in turn
change TTL for redis.
import redis
import os
from flask import Flask
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
store = RedisStore(redis.StrictRedis())
app = Flask(__name__)
KVSessionExtension(store, app)
#Logout Handler
@app.route('/logout', methods=['GET'])
def logout():
cookie_val = request.cookies.get('session').split(".")[0]
app.permanent_session_lifetime = timedelta(seconds=1)
store.delete(cookie_val)
Using the above code, I was able to thwart session replay attacks.
**and solution to your 2nd question:**
3 possible mistakes that I can see are:
1: In the beginning of your code you have created:
store = RedisStore(redis.StrictRedis())
but in the loop you are using it as kvsession_store instead of just store:
app.kvsession_store.keys()
2. To use it without any errors/exceptions you can use it as `store.keys()` instead of app.store.keys():
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
store = RedisStore(redis.StrictRedis())
for key in store.keys():
print key
3. `store.delete(key)` is not deleting the all keys, you are running it inside the loop which is one by one deleting all keys.
|
python xlwt - search for a specific value
Question: I made a script using xlrd to extract multiple data from multiple cells in
multiple excel files, and used xlwt to write these data to a new excel file.
In the new excel file I added two additional rows with Formulas that will
compute the average and the ttest. Now I'm trying to add a script that will
search through the ttest line and all the values that are under 0.05 to be
colored in red. On stackoverflow I found some help but I still receive an
error. (For the color, I'm using this source:
<https://pypi.python.org/pypi/xlwt>)
Could you please help me ?
Thanks !
from xlwt import *
style = xlwt.easyxf('font: colour red, bold on')
wb=xlwt.Workbook()
wbs=wb.add_sheet("sheet_to_write")
w=xlrd.open_workbook("file_to_read.xlsx")
ws=w.sheet_by_name("sheet_to_read")
c=ws.cell(2,6).value
wbs.write(46,1,c)
... #same as the last two lines, extracting different cells from the sheet_to_red and writing them in the sheet_to_write
wbs.write(61,1,Formula("TTEST($B3:$B18, $B19:$B57, 2, 2)"))
Old code:
for p in range(61):
p.append(str(sheet.cell(row,col).value))
if p.value < 0.05:
cell.color =='22'
code 2:
for row in range(61):
for col in range(wbs.nrows):
cell=ws.cell(row,col)
try:
if float(cell.value) < 0.05:
cell.color =='22'
except ValueError: pass
AttributeError: 'Cell' object has no attribute 'color'
code 3:
for row in range(61):
for col in range(wbs.nrows):
search=wbs.cell(row,col)
try:
if float(search.value) < 0.05:
wbs.write(row, col, search.value, style)
except ValueError: pass
ERROR:
AttributeError: 'Worksheet' object has no attribute 'cell',
My Conclusion: this method won't work, because xlwt has no attribute cell, or
nrows, these attibutes are specific for xlrd. Hence, the only method that
would work is to create another file that will use xlrd, search for the
specific value, and write it to a new file. Thanks Pyrce and tmrlvi for your
help !
Answer: You're trying to append a string to an integer when you just want an
assignment. I'm guessing you meant to do something like this:
# Generate a color style for writing back into xlwt
xlwt.add_palette_colour("my_color", 0x22)
style = xlwt.easyxf('font: colour my_color;')
for row in range(61):
cell = input_sheet.cell(row, col)
try:
if float(cell.value) < 0.05:
output_sheet.write(row, col, cell.value, style)
except ValueError: pass
Also as you can see the color assignment is a little different in xlwt than
you might expect. You may also need to iterate over all cells and copy them
over to the output sheet, or share the same sheet that was read to make this
do exactly what you want.
|
python - complex sorting of nested data
Question: I am retrieving data from postgres (jsonb type) and I need to return an
OrderedDict that has a predictable order for human and machine consumption.
There are some common(ish) keys that should be used to direct precedence of
values of common types (based on a predefined order) [if sort_order is
defined]. Otherwise, sort order should fall back to key based lexicographic
ordering.
The general intent is to have a predictable, 'sane', represenation of
composite dicts.
**The basic algorithm is:**
1. dicts come before lists
2. values that are NOT iterables or mapping take precedence over objects that are.
3. values of the same type whose keys are not in sort_order are considered equal and should be sorted lexicographically.
4. Obj A takes precedence over Obj B if type(A[0]) == type(B) AND A[0] in sort_order and not B[0] in sort_order
5. if all([type(A[1](http://bit.ly/1LcGdHk)) == type(B[1](http://bit.ly/1LcGdHk)), A[0] in sort_order, B[0] in sort_order]) then the index position of the object key is the precedence determinant.
I have attempted several implementations, but I have not been able to come up
with anything that I would consider pythonic/elegant.
**Here is the latest incarnation**
# -*- coding: utf-8 -*-
import json
from collections import OrderedDict
def dict_sort(obj, sort_order=None):
def seq(s, o=None, v=None):
return str(s) + str(o) + str(v) if o is not None else str(s)
order_seq = None
if sort_order is not None and obj[0] in sort_order:
order_seq = [i for i, v in enumerate(sort_order) if v == obj[0]][0]
if isinstance(obj[1], dict):
return seq(2, order_seq, obj[0]) if order_seq else seq(3)
elif isinstance(obj[1], list):
return seq(4, order_seq, obj[0]) if order_seq else seq(5)
else:
return seq(0, order_seq, obj[0]) if order_seq else seq(1)
def comp_sort(obj, sort_order=None):
data = OrderedDict()
if isinstance(obj, dict):
for key, value in sorted(obj.items(), key=lambda d: dict_sort(d, sort_order)):
if isinstance(value, dict) or isinstance(value, list):
data[key] = comp_sort(value, sort_order)
else:
data[key] = value
elif isinstance(obj, list):
try:
return sorted(obj)
except:
items = []
for value in obj:
if isinstance(value, dict) or isinstance(value, list):
items.append(comp_sort(value, sort_order))
else:
items.append(value)
return items
return data
# thx herk
[**Here is a sample data set**](http://bit.ly/1LcGdHk)
Answer: It took some stewing, but I was finally able to come up a solution that
satisfies all the requirements. It is a bit slow, but it works.
Feedback would be appreciated!
# -*- coding: utf-8 -*-
from __future__ import print_function
from functools import cmp_to_key
import collections
import urllib2
import json
def sort_it(obj=None, sort_order=None):
"""Sort a composite python object.
:param obj: Python object
:param sort_order: optional custom sort order
:rtype: OrderedDict
:returns: Sorted composite object.
"""
# TODO: Refactor to use key rather than cmp (cmp is not supported in python3)
# using cmp_to_key as transitional solution
text_types = (basestring, int, float, complex)
iterable_types = (list, tuple, set, frozenset)
def cmp_func(a, b):
"""Function passed as `cmp` arg to sorted method
Basic Algorithm
- text_types take precedence over non text_types
- Mapping types take precedence over iterable container types
- Values of the same (or similar) type:
- if sort_order is defined
- if both keys are in sort order, the key index position determines precedence
- if only one of the keys are in sort order then it takes precedence
- if neither keys are in sort_order their lexicographic order is the determinant
- otherwise, fall back to lexicographic ordering
:param a: first arg passed to sorted's cmp arg
:param b: second arg passed to sorted's cmp arg
:rtype: int
:return: int to determine which object (a/b) should take precedence
"""
# ensure a and b are k/v pairs
if not any([len(a) == 2, len(b) == 2]):
return 0
# text_types take precedence over non-text types
elif isinstance(a[1], text_types) and not isinstance(b[1], text_types):
return -1
elif not isinstance(a[1], text_types) and isinstance(b[1], text_types):
return 1
# Mappings take precedence over iterable types
elif isinstance(a[1], collections.Mapping) and isinstance(b[1], iterable_types):
return -1
elif isinstance(b[1], collections.Mapping) and isinstance(a[1], iterable_types):
return 1
# if type of values are of the same/similar type
elif any([isinstance(a[1], text_types) and isinstance(b[1], text_types),
isinstance(a[1], iterable_types) and isinstance(b[1], iterable_types),
isinstance(a[1], collections.Mapping) and isinstance(b[1], collections.Mapping),
isinstance(a[1], type(b[1])),
]):
if sort_order:
if any([a[0] in sort_order, b[0] in sort_order]):
if a[0] in sort_order and b[0] not in sort_order:
return -1
if b[0] in sort_order and a[0] not in sort_order:
return 1
if a[0] in sort_order and b[0] in sort_order:
if sort_order.index(a[0]) > sort_order.index(b[0]):
return 1
else:
return -1
# no sort_order ( or keys not in sort_order) -- sort lexicographically
if sorted([a[0].lower(), b[0].lower()]).index(a[0].lower()) == 0:
return -1
elif sorted([a[0].lower(), b[0].lower()]).index(a[0].lower()) == 1:
return 1
else:
raise ValueError('Unhandled condition for values %s, %s' % (a, b))
if isinstance(obj, collections.Mapping):
return collections.OrderedDict(
(key, sort_it(value, sort_order=sort_order)) for key, value in
sorted(obj.items(), key=cmp_to_key(cmp_func)))
elif isinstance(obj, iterable_types):
return type(obj)([sort_it(value, sort_order=sort_order) for value in obj])
else:
return obj
sort_order = [
'id',
'rn',
'dn',
'vendor',
'model',
'serial',
'name',
'description',
'tray'
'presence'
]
sample_data_uri = 'https://bit.ly/1jOpQF2'
### EXAMPLE - Sans sort order
print(json.dumps(sort_it(json.loads(urllib2.urlopen(sample_data_uri).read())), indent=4))
### EXAMPLE - with sort_order
print(json.dumps(sort_it(json.loads(urllib2.urlopen(sample_data_uri).read()), sort_order=sort_order), indent=4))
|
Pygments import Lex error
Question: I tried to import lex using this code:
from pygments import lex
but it only returned an error:
Traceback (most recent call last):
File "D:\samp.py", line 1, in <module>
from pygments import lex
File "C:\Python32\lib\site-packages\pygments-2.0.2-py3.2.egg\pygments\__init__.py", line 37, in <module>
from pygments.util import StringIO, BytesIO
File "C:\Python32\lib\site-packages\pygments-2.0.2-py3.2.egg\pygments\util.py", line 226
return u'[%s-%s]' % (unichr(a), unichr(b))
^
SyntaxError: invalid syntax
**(I'm using Python 3.2.3 on IDLE)**
Is the any solution to this?
Answer: Seems like someone had already logged this as a bug
[here](https://bitbucket.org/birkenfeld/pygments-main/issues/1054/syntaxerror-
on-python-32-using-unicode-u).
Resolution is that -
> Pygments 2.0 requires Python 3.3+.
You should install Python 3.3 or above and then install pygment on that.
|
How to get POST parameters with Python?
Question: I would like to call my Python script from different location ( FIY: I will
call it later from my paypal registration process).
My configuration: I am running my website on AmazonWebServices. IIS8. Python3
I am calling to my python with this simple HTML file:
<form role="form" action="http://www.mywebsite.nz/cgi-bin/mypythonfile.py" method="post">
<label for="person_name">Person name</label>
<input id="person_name" type="text" name="person_name">
<label for="email_address">Email address</label>
<input id="email_address" type="text" name="email_address">
<button id="submit_button" type="submit" >submit</button>
</form>
Here is what I have in my mypythonfile.py:
import cgi, cgitb
#Create instance of FieldStorage
form = cgi.FieldStorage()
cgitb.enable()
#Here I will collect all parameters
variable = ""
value = ""
allFields = ""
for key in form.keys():
variable = str(key)
value = str(form.getvalue(variable))
allFields += variable + ":" + value + " "
print(allFields)
But the result I get is with empty values:
<email_address>:<None> <person_name>:<None>
p.s. When calling the .py from the same place where the HTML file is -
everything works perfectly. The problem happens when I call the .py file from
an external HTML.
How can I fix it? (maybe it is some sort of configuration I have to add e.g.
to IIS?)
Answer: You are sending it as POST. To obtain POST superglobal variables, try
replacing:
form = cgi.FieldStorage()
with this:
form = cgi.FieldStorage(environ="post")
Or you can try this:
import sys, urllib
query_string = sys.stdin.read()
multiform = urllib.parse.parse_qs(query_string)
And now you can use this:
multiform["email_address"]
|
How to fix: "RuntimeWarning: Model <my_model> was already registered."
Question: Since upgrading Django, I've been getting this error in iPython when I do
imports:
> RuntimeWarning: Model 'docket.search' was already registered. Reloading
> models is not advised as it can lead to inconsistencies, most notably with
> related models.
I'm guessing this is some automatic feature of iPython, but is there an easy
solution? Is this something I even need to solve?
Answer: I have gotten this error because of automatic imports I had in my
`__init__.py`. I had some old code that imported by signals there, and moving
that import code to AppConfig instead fixed it.
|
Python Beautiful Soup Error : list index out of range
Question: I am getting the following error with the script, i want to do is,
if i get a correct URL, i want it to check with BeautifulSoup if there is a
form with value button "Send"
Traceback (most recent call last): File "tester.py", line 27, in if
viewstate[0]['value'] == "Send": IndexError: list index out of range
#!/usr/bin/env python
import urllib2
import sys
import os
url = sys.argv[1]
open_dir_list = open("dirlist.txt",'r')
dirs = open_dir_list.read().split("\n")
open_dir_list.close()
for dir in dirs:
uri = url+"/"+dir
try:
from BeautifulSoup import BeautifulStoneSoup
response = urllib2.urlopen(uri)
if response.getcode() == 200:
s = uri
soup = BeautifulStoneSoup(uri)
viewstate = soup.findAll("input", {"type": "submit"})
if viewstate[0]['value'] == "Send":
print("Yay!!!")
else:
print("There's nothing here")
except urllib2.HTTPError, e:
if e.code == 401:
print "[!] Authorization Required %s " % (uri)
elif e.code == 403:
print "[!] Forbidden %s " % (uri)
elif e.code == 404:
print "[-] Not Found %s " % (uri)
elif e.code == 503:
print "[!] Service Unavailable %s " % (uri)
else:
print "[?] Unknwon"
print "\n:. FINISH :.\n"
It is working fine with this script, but it only checks only a given path
import urllib
f = urllib.urlopen("http://xxx.xxx.xxx.xxx/button.jsp")
s = f.read()
f.close()
from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(s)
viewstate = soup.findAll("input", {"type": "submit"})
if viewstate[0]['value'] == "Send":
print(" Yay!!!")
else:
print("No Submit Button")
Answer: Apart from what I mentioned in a comment you are not passing the returned html
you are passing `uri = url+"/"+dir` instead of `response.read()` to
`BeautifulSoup` so you are searching for the tag in `uri` which I imagine
certainly does not contain any tags. You need to pass `read` as below:
response = urllib2.urlopen(uri)
if response.getcode() == 200:
soup = BeautifulStoneSoup(response.read())
If you want the first match use `.find` using `if viewstate` to make sure it
matched something, you can also iterate over the file object getting a line at
a time:
from BeautifulSoup import BeautifulStoneSoup
import urllib2
import sys
url = sys.argv[1]
with open("dirlist.txt",'r') as f:
for dir in f:
uri = url + "/" + dir.rstrip()
try:
response = urllib2.urlopen(uri)
if response.getcode() == 200:
soup = BeautifulStoneSoup(response.read())
viewstate = soup.find("input", {"type": "submit"})
if viewstate and viewstate.get("value") == "Send":
print("Shell is found!! Yay!!!")
else:
print("There's nothing here")
except urllib2.HTTPError, e:
if e.code == 401:
print "[!] Authorization Required %s " % (uri)
elif e.code == 403:
print "[!] Forbidden %s " % (uri)
elif e.code == 404:
print "[-] Not Found %s " % (uri)
elif e.code == 503:
print "[!] Service Unavailable %s " % (uri)
else:
print "[?] Unknwon"
print "\n:. FINISH :.\n"
|
How to use Values in a multiprocessing pool with Python
Question: I want to be able to use the Values module from the multiprocessing library to
be able to keep track of data. As far as I know, when it comes to
multiprocessing in Python, each process has it's own copy, so I can't edit
global variables. I want to be able to use Values to solve this issue. Does
anyone know how I can pass Values data into a pooled function?
from multiprocessing import Pool, Value
import itertools
arr = [2,6,8,7,4,2,5,6,2,4,7,8,5,2,7,4,2,5,6,2,4,7,8,5,2,9,3,2,0,1,5,7,2,8,9,3,2,]
def hello(g, data):
data.value += 1
if __name__ == '__main__':
data = Value('i', 0)
func = partial(hello, data)
p = Pool(processes=1)
p.map(hello,itertools.izip(arr,itertools.repeat(data)))
print data.value
Here is the runtime error i'm getting:
RuntimeError: Synchronized objects should only be shared between processes through inheritance
Does anyone know what I'm doing wrong?
Answer: I don't know why, but there seems to be some issue using the `Pool` that you
don't get if creating subprocesses manually. E.g. The following works:
from multiprocessing import Process, Value
arr = [1,2,3,4,5,6,7,8,9]
def hello(data, g):
with data.get_lock():
data.value += 1
print id(data), g, data.value
if __name__ == '__main__':
data = Value('i')
print id(data)
processes = []
for n in arr:
p = Process(target=hello, args=(data, n))
processes.append(p)
p.start()
for p in processes:
p.join()
print "sub process tasks completed"
print data.value
However, if you do basically the same think using `Pool`, then you get an
error "RuntimeError: Synchronized objects should only be shared between
processes through inheritance". I have seen that error when using a pool
before, and never fully got to the bottom of it.
An alternative to using `Value` that seems to work with `Pool` is to use a
Manager to give you a 'shared' list:
from multiprocessing import Pool, Manager
from functools import partial
arr = [1,2,3,4,5,6,7,8,9]
def hello(data, g):
data[0] += 1
if __name__ == '__main__':
m = Manager()
data = m.list([0])
hello_data = partial(hello, data)
p = Pool(processes=5)
p.map(hello_data, arr)
print data[0]
|
cannot write file with full path in Python
Question: I am using Pandas on Mac, to read and write a CSV file, and the weird thing is
when using full path, it has error and when using just a file name, it works.
I post my code which works and which not works in my comments below, and also
detailed error messages. Anyone have any good ideas?
sourceDf = pd.read_csv(path_to_csv)
sourceDf['nameFull'] = sourceDf['nameFirst'] + ' ' + sourceDf['nameLast']
sourceDf.to_csv('newMaster.csv') # working
sourceDf.to_csv('~/Downloads/newMaster.csv') # not working
Traceback (most recent call last):
File "/Users/foo/PycharmProjects/DataWranglingTest/CSVTest1.py", line 36, in <module>
add_full_name(path_to_csv, path_to_new_csv)
File "/Users/foo/PycharmProjects/DataWranglingTest/CSVTest1.py", line 28, in add_full_name
sourceDf.to_csv('~/Downloads/newMaster.csv')
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/frame.py", line 1189, in to_csv
formatter.save()
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/format.py", line 1442, in save
encoding=self.encoding)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/common.py", line 2831, in _get_handle
f = open(path, mode)
IOError: [Errno 2] No such file or directory: '~/Downloads/newMaster.csv'
Tried to use prefix r, but not working,
path_to_csv = r'~/Downloads/Master.csv'
path_to_new_csv = r'~/Downloads/Master_new.csv'
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/frame.py", line 1189, in to_csv
formatter.save()
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/format.py", line 1442, in save
encoding=self.encoding)
File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/common.py", line 2831, in _get_handle
f = open(path, mode)
IOError: [Errno 2] No such file or directory: '~/Downloads/Master_new.csv'
thanks in advance, Lin
Answer: Try using `os.path.join()`.
import os
(...)
output_filename = 'newMaster.csv'
output_path = os.path.join('Downloads', output_filename)
(...)
sourceDf.to_csv(output_path)
Use the same methodology to point `pandas.read_csv()` in the right direction.
|
mysql file import with multiple lines of string
Question: I have 3 sql files migrated from sqlite3 dump. Unfortunately they have string
values of multiple lines. So when I `mysql -p dbname <- dbname.sql` it returns
syntax errors at specific lines:
ERROR 1064 (42000) at line 87194: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '15052','53663423259319','21:35:45','FALSE','536625' at line 1
These lines may look like this (lines have been edited for masking):
87193 INSERT INTO `tbl` VALUES('15052','53663968185392','21:57:25','FALSE','53634933924616','79886','','','','','79886','rado','simple','');
87194 INSERT INTO `tbl` VALUES('15052','53663466948450','21:37:30','FALSE','53653949005223','62487','','','','','62487','Nopa','oh, i dunno:
87195
87196 ☺
87197 /|\ /()\
87198 /\ / \','');
87199 INSERT INTO `tbl` VALUES('15052','53663423259319','21:35:45','FALSE','53662542442479','28086','','','','','28086','ESOS','AHAHAHAHAHAHAHA ','');
How can I import these sql files and let mysql understand that if a string
doesn't end with single quote there's another line below? I searched for some
args for mysql but didn't find any.
I also tried to use <http://www.redmine.org/attachments/8273/sqlite3-to-
mysql.py> and redo the migration, as it says the python script handles this
multiple line trouble. However every time the console says "Killed", I guess
because of the temp file operation (the sqlite3 db files are over 100Gb). I
changed `tempfile.tempdir = "/home/username/sqlite_to_mysql/`, hoping it can
provide enough space for the temp file (6Tb free) but still the console
returned "Killed". I don't know other ways to solve it before the sql file is
created.
Thanks a lot for any help!
Answer: The problem is not the spacing of the lines, but rather the quoting of the
content.
On the line mentioned in the error message, the text content has `\'` as the
last character; which ends up escaping the `'` and causing the parser to
consider the rest of the line as one single string.
The end effect is when it encounters the _next_ `'`, it has already chopped
off the start of the query statement and thus your error.
To prevent this, you need to disable `\` as an escape character; which can you
can do by setting the
[`NO_BACKSLASH_ESCAPES`](https://dev.mysql.com/doc/refman/5.0/en/sql-
mode.html#sqlmode_no_backslash_escapes) sql mode.
Add the following to the start of your file:
SET sql_mode = 'NO_BACKSLASH_ESCAPES';
|
PUT json data to Elasticsearch cluster Python
Question: I'm trying to PUT data to an Elasticsearch server. I can manually PUT the
data, but I can't seem to automate it.
jsonValue = json.dumps(data).encode('utf8')
req = urllib2.Request("http://[Elastic IP Address]/cities", jsonValue, {'Content-Type': 'application/json'})
req.get_method = lambda: 'PUT'
f = urllib2.urlopen(req)
response = f.read()
f.close()
The error that I am getting:
Traceback (most recent call last):
File "import_elastic.py", line 27, in <module>
f = urllib2.urlopen(req)
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 437, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 550, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 475, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 558, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 400: Bad Request
The first value that I am PUTing:
{"name": "Tia Juana River", "country": "US", "alternate": "Rio Tiajuana,Rio Tijuana,R\u00edo Tijuana,Tia Juana River", "long": "-117.12865", "lat": "32.55668", "timezone": "America/Los_Angeles", "id": "3981608", "population": "0"}
Answer: You need to put the type name too
http://[Elastic IP Address]/cities/city
The above URL should work. Between there is a Elasticsearch client for python
, feel free to try out that too.
|
Creating a watermark in Python
Question: I'm trying to figure out how to create this kind of watermark, **especially
the one that's in the center** (it's not an ad, it's just a perfect example of
what I want to accomplish):
[](http://i.stack.imgur.com/GnnOs.jpg)
[](http://i.stack.imgur.com/x0rKo.jpg)
Answer: Python's [wand](http://docs.wand-py.org/en/0.4.1/index.html) library has a
[Image.watermark](http://docs.wand-
py.org/en/0.4.1/wand/image.html#wand.image.BaseImage.watermark) method that
can simplify common watermark operations.
from wand.image import Image
with Image(filename='background.jpg') as background:
with Image(filename='watermark.png') as watermark:
background.watermark(image=watermark, transparency=0.75)
background.save(filename='result.jpg')
|
How to add a tally?
Question: I need some help in creating a tally for the following code:
import random
def number_to_name(selection):
# convert number to a name using if/elif/else
if selection == 0: return "rock"
elif selection == 1: return "Spock"
elif selection == 2: return "paper"
elif selection == 3: return "lizard"
elif selection == 4: return "scissors"
else: return None
def name_to_number(name):
# convert name to number using if/elif/else
if name == "rock": return 0
elif name == "Spock": return 1
elif name == "paper": return 2
elif name == "lizard": return 3
elif name == "scissors": return 4
else: return None
def rpsls(name):
# convert name to player_number using name_to_number
# compute random guess for comp_number using random.randrange()
# compute difference of player_number and comp_number modulo five
# use if/elif/else to determine winner
# convert comp_number to name using number_to_name
# print results
player_number = name_to_number(name)
comp_number = random.randrange(0, 5)
difference = (player_number - comp_number) % 5
print "\nComputer 2 chooses", name
print "Computer 1 chooses", number_to_name(comp_number)
#print "Score was:", difference # XXX
if difference == 0: print "Computer 2 and Computer 1 tie!"
elif difference <= 2: print "Computer 2 wins!"
else: print "Computer 1 wins!"
print
# test code
print "Welcome to..."
import sys
import time
line = "Rock! Paper! Scissors! Lizard! Spock!."
for char in line:
sys.stdout.write(char)
time.sleep(0.02)
print "\n<Follow the enter key prompts!>"
raw_input("\n\nPress the enter key to continue.")
rpsls("rock")
raw_input("\n\nPress the enter key to continue.")
rpsls("Spock")
raw_input("\n\nPress the enter key to continue.")
rpsls("paper")
raw_input("\n\nPress the enter key to continue.")
rpsls("lizard")
raw_input("\n\nPress the enter key to continue.")
rpsls("scissors")
raw_input("\n\nPress the enter key to continue.")
rpsls("rock")
raw_input("\n\nPress the enter key to continue.")
rpsls("Spock")
raw_input("\n\nPress the enter key to continue.")
rpsls("paper")
raw_input("\n\nPress the enter key to continue.")
rpsls("lizard")
raw_input("\n\nPress the enter key to continue.")
rpsls("scissors")
raw_input('\n\nPress the enter key to exit')
After each individual game (of rock paper scissors lizard spock) I need a
tally to calculate the wins losses and draws of each 'Computer'.
e.g. Computer 2 chooses rock
Computer 1 chooses paper
Computer 1 wins!
> <Computer 1 : Draws = 1
> Wins = 3
> Losses = 2
>
> Computer 2 : Draws = 1
> Wins = 2
> Losses = 3>
Or something along those lines, the simpler the better.
Please help, I've only just started python, all help is greatly appreciated.
Answer: As well as adding some score-keeping code I've made your program more compact
by using lists, loops, and a dictionary. I've also made it more modular by
putting the test code into a `main()` function.
#!/usr/bin/env python
""" Rock Spock Paper Lizard Scissors
Written by Zinc & PM 2Ring 2015.08.16
See http://stackoverflow.com/q/32034190/4014959
"""
import sys
import time
import random
#Build a list to convert move numbers to names
move_names = "rock Spock paper lizard scissors".split()
#Build a dict to convert move names to numbers
move_numbers = dict((name, num) for num, name in enumerate(move_names))
win_messages = [
"Computer 2 and Computer 1 tie!",
"Computer 1 wins!",
"Computer 2 wins!",
]
def rpsls(name):
# convert Computer 1 name to player_number
player_number = move_numbers[name]
# generate random guess Computer 2
comp_number = random.randrange(0, 5)
# compute difference modulo five to determine winner
difference = (player_number - comp_number) % 5
print "\nComputer 2 chooses", name
print "Computer 1 chooses", move_names[comp_number]
#print "Score was:", difference # XXX
#Convert difference to result number.
#0: tie. 1: Computer 1 wins. 2:Computer 2 wins
if difference == 0:
result = 0
elif difference <= 2:
result = 2
else:
result = 1
return result
def main():
banner = "! ".join([word.capitalize() for word in move_names]) + "!.\n"
print "Welcome to..."
for char in banner:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.02)
print "\n<Follow the enter key prompts!>"
#A list of moves for Computer 1
computer1_moves = [
"rock",
"Spock",
"paper",
"lizard",
"scissors",
"rock",
"Spock",
"paper",
"lizard",
"scissors",
]
#Create a list to hold the scores
scores = [0, 0, 0]
for name in computer1_moves:
result = rpsls(name)
scores[result] += 1
print result, win_messages[result], scores
raw_input("\n\nPress the enter key to continue.")
print "\nFinal scores"
print "Computer 1 wins:", scores[1]
print "Computer 2 wins:", scores[2]
print "Ties:", scores[0]
raw_input("\n\nPress the enter key to exit")
if __name__ == "__main__":
main()
**typical output**
Welcome to...
Rock! Spock! Paper! Lizard! Scissors!.
<Follow the enter key prompts!>
Computer 2 chooses rock
Computer 1 chooses rock
0 Computer 2 and Computer 1 tie! [1, 0, 0]
Press the enter key to continue.
Computer 2 chooses Spock
Computer 1 chooses lizard
1 Computer 1 wins! [1, 1, 0]
Press the enter key to continue.
Computer 2 chooses paper
Computer 1 chooses paper
0 Computer 2 and Computer 1 tie! [2, 1, 0]
Press the enter key to continue.
Computer 2 chooses lizard
Computer 1 chooses rock
1 Computer 1 wins! [2, 2, 0]
Press the enter key to continue.
Computer 2 chooses scissors
Computer 1 chooses scissors
0 Computer 2 and Computer 1 tie! [3, 2, 0]
Press the enter key to continue.
Computer 2 chooses rock
Computer 1 chooses lizard
2 Computer 2 wins! [3, 2, 1]
Press the enter key to continue.
Computer 2 chooses Spock
Computer 1 chooses rock
2 Computer 2 wins! [3, 2, 2]
Press the enter key to continue.
Computer 2 chooses paper
Computer 1 chooses scissors
1 Computer 1 wins! [3, 3, 2]
Press the enter key to continue.
Computer 2 chooses lizard
Computer 1 chooses lizard
0 Computer 2 and Computer 1 tie! [4, 3, 2]
Press the enter key to continue.
Computer 2 chooses scissors
Computer 1 chooses lizard
2 Computer 2 wins! [4, 3, 3]
Press the enter key to continue.
Final scores
Computer 1 wins: 3
Computer 2 wins: 3
Ties: 4
Press the enter key to exit
|
Tornado crashed with assert error
Question: According to official doc <http://tornado.readthedocs.org/en/latest/gen.html>,
I'm using async feature of tornado like this:
@tornado.web.asynchronous
@tornado.gen.coroutine
def get(self):
...
response = yield calendar.events()
self.write(json.dumps(response, default=json_util.default))
self.finish()
`calendar.events()` is database operation, it crashed with below assert error,
is there anything wrong?
HTTPServerRequest(protocol='http', host='xxxx:9999', method='GET', uri='/event_list?calendar_guid=6', version='HTTP/1.1', remote_ip='xxxx', headers={'Host': 'xxxx:9999', 'User-Agent': 'Mozilla/5.0 (apple-x86_64-darwin14.4.0) Siege/3.1.0', 'Connection': 'close', 'Accept': '*/*', 'Accept-Encoding': 'gzip'})
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1369, in _stack_context_handle_exception
raise_exc_info((type, value, traceback))
File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1572, in wrapper
result = method(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 242, in wrapper
Runner(result, future, yielded)
File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 817, in __init__
if self.handle_yield(first_yielded):
File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 956, in handle_yield
self.future = convert_yielded(yielded)
File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 1022, in convert_yielded
return multi_future(yielded)
File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 643, in multi_future
assert all(is_future(i) for i in children)
AssertionError
Answer: To be used with the `yield` statement in a Tornado coroutine, a method must be
specifically written for this purpose. Looks like the `calendar.events` method
you call does not return a Tornado `Future` object, so I infer it's not
designed for use as a non-blocking method within a Tornado coroutine.
You can call it without the `yield` keyword, but you'll have to accept that
you're blocking the event loop while `events` executes. Alternatively, use a
ThreadPoolExecutor. Tornado's maintainer Ben Darnell has a nice example of
this here:
<https://groups.google.com/d/msg/python-tornado/35BiBKdSCNw/zx561l-sABIJ>
If `calendar` is a MySQLdb object, try:
from concurrent.futures import ThreadPoolExecutor
from tornado.process import cpu_count
# global threadpool
pool = ThreadPoolExecutor(cpu_count())
class Handler(RequestHandler):
@tornado.gen.coroutine
def get(self):
response = yield pool.submit(calendar.events)
self.write(json.dumps(response, default=json_util.default))
Final notes: with `gen.coroutine`, the `asynchronous` decorator is not needed,
nor is `self.finish`.
|
How to encode UTF-8 strings with only "A-Z","a-z","0-9", and "_" in Python
Question: I need to build a python encoder so that I can reformat strings like this:
import codecs
codecs.encode("Random UTF-8 String ☑⚠⚡", 'name_of_my_encoder')
The reason this is even something I'm asking stack overflow is, the encoded
strings need to pass this validation function. This is a hard constraint,
there is no flexibility on this, its due to how the strings have to be stored.
from string import ascii_letters
from string import digits
valid_characters = set(ascii_letters + digits + ['_'])
def validation_function(characters):
for char in characters:
if char not in valid_characters:
raise Exception
Making an encoder seemed easy enough, but I'm not sure if this encoder is
making it harder to build a decoder. Heres the encoder I've written.
from codecs import encode
from string import ascii_letters
from string import digits
ALPHANUMERIC_SET = set(ascii_letters + digits)
def underscore_encode(chars_in):
chars_out = list()
for char in chars_in:
if char not in ALPHANUMERIC_SET:
chars_out.append('_{}_'.format(encode(char.encode(), 'hex').decode('ascii')))
else:
chars_out.append(char)
return ''.join(chars_out)
This is the encoder I've written. I've only included it for example purposes,
theres probably a better way to do this.
Edit 1 - Someone has wisely pointed out just using base32 on the entire
string, which I can definitely use. However, it would be preferable to have
something that is 'somewhat readable', so an escaping system like
<https://en.wikipedia.org/wiki/Quoted-printable> or
<https://en.wikipedia.org/wiki/Percent-encoding> would be preferred.
Edit 2 - Proposed solutions must work on Python 3.4 or newer, working in
Python 2.7 as well is nice, but not required. I've added the python-3.x tag to
help clarify this a little.
Answer: This seems to do the trick. Basically, alphanumeric letters are left alone.
Any non-alphanumeric character in the ASCII set is encoded as a `\xXX` escape
code. All other unicode characters are encoded using the `\uXXXX` escape code.
However, you've said you can't use `\`, but you can use `_`, thus all escape
sequences are translated to start with a `_`. This makes decoding extremely
simple. Just replace the `_` with `\` and then use the `unicode-escape` codec.
Encoding is slightly more difficult as the `unicode-escape` codec leaves ASCII
characters alone. So first you have to escape the relevant ASCII characters,
then run the string through the `unicode-escape` codec, before finally
translating all `\` to `_`.
Code:
from string import ascii_letters, digits
# non-translating characters
ALPHANUMERIC_SET = set(ascii_letters + digits)
# mapping all bytes to themselves, except '_' maps to '\'
ESCAPE_CHAR_DECODE_TABLE = bytes(bytearray(range(256)).replace(b"_", b"\\"))
# reverse mapping -- maps `\` back to `_`
ESCAPE_CHAR_ENCODE_TABLE = bytes(bytearray(range(256)).replace(b"\\", b"_"))
# encoding table for ASCII characters not in ALPHANUMERIC_SET
ASCII_ENCODE_TABLE = {i: u"_x{:x}".format(i) for i in set(range(128)) ^ set(map(ord, ALPHANUMERIC_SET))}
def encode(s):
s = s.translate(ASCII_ENCODE_TABLE) # translate ascii chars not in your set
bytes_ = s.encode("unicode-escape")
bytes_ = bytes_.translate(ESCAPE_CHAR_ENCODE_TABLE)
return bytes_
def decode(s):
s = s.translate(ESCAPE_CHAR_DECODE_TABLE)
return s.decode("unicode-escape")
s = u"Random UTF-8 String ☑⚠⚡"
#s = '北亰'
print(s)
b = encode(s)
print(b)
new_s = decode(b)
print(new_s)
Which outputs:
Random UTF-8 String ☑⚠⚡
b'Random_x20UTF_x2d8_x20String_x20_u2611_u26a0_u26a1'
Random UTF-8 String ☑⚠⚡
This works on both python 3.4 and python 2.7, which is why the
`ESCAPE_CHAR_{DE,EN}CODE_TABLE` is a bit messy `bytes` on python 2.7 is an
alias for `str`, which works differently to `bytes` on python 3.4. This is why
the table is constructed using a `bytearray`. For python 2.7, the `encode`
method expects a `unicode` object not `str`.
|
Python 3.4 import gcm raise a SystemError: Parent module '' not loaded, cannot perform relative import
Question: I'm trying to import gcm as following:
from . import gcm
And i get:
SystemError: Parent module '' not loaded, cannot perform relative import
I tried also called:
from gcm import GCM
by `pip install python-gcm` but i get the follwoing error: module' object has
no attribute 'GCM
Answer: Don't use the relative import syntax, `from . import gcm`. Instead, put the
library where the Python interpreter can find it (via `pip install python-
gcm`) and call `from gcm import GCM` in your program.
However, if you still get an error while attempting to import, you should add
a comment to the project's [open Python3 import issue thread on
GitHub](https://github.com/geeknam/python-gcm/issues/65) and let them know,
since there still appears to be some ambiguity if this bug has been fixed yet
or not.
|
Mastermind Game in Python
Question: I have already looked at this thread [Python Mastermind Game
Troubles](http://stackoverflow.com/questions/15648407/python-mastermind-game-
troubles) on your website but the question I am asking is slightly different
as I have been given a different task.
This is the question:
**Generate a random four digit number. The player has to keep inputting four
digit numbers until they guess the randomly generated number. After each
unsuccessful try it should say how many numbers they got correct, but not
which position they got right. At the end of the game should congratulate the
user and say how many tries it took.**
I have made this so far:
from random import randint
n1 = randint (1,9)
n2 = randint (1,9)
n3 = randint (1,9)
n4 = randint (1,9)
numberswrong = 0
print (n1,n2,n3,n4)
guess1 = input("guess the first number")
guess2 = input("guess the second number")
guess3 = input("guess the third number")
guess4 = input("guess the fourth number")
guess1 = int (guess1)
guess2 = int (guess2)
guess3 = int (guess3)
guess4 = int (guess4)
if guess1 != n1:
numberswrong +=1
else:
numberswrong +=0
if guess2 != n2:
numberswrong +=1
else:
numberswrong +=0
if guess3 != n3:
numberswrong +=1
else:
numberswrong +=0
if guess4 != n4:
numberswrong +=1
else:
numberswrong +=0
print ("you got",numberswrong, "numbers wrong")
if numberswrong == 0:
print ("Well done")
while numberswrong != 0:
guess1 = input("guess the first number")
guess2 = input("guess the second number")
guess3 = input("guess the third number")
guess4 = input("guess the fourth number")
guess1 = int (guess1)
guess2 = int (guess2)
guess3 = int (guess3)
guess4 = int (guess4)
if guess1 != n1:
numberswrong +=1
else:
numberswrong +=0
if guess2 != n2:
numberswrong +=1
else:
numberswrong +=0
if guess3 != n3:
numberswrong +=1
else:
numberswrong +=0
if guess4 != n4:
numberswrong +=1
else:
numberswrong +=0
print ("you got",numberswrong, "numbers wrong")
print ("Well done")
The print (n1,n2,n3,n4) is just to test the code and won't be there in the
real code. I am having two problems. Firstly, if you guess the number first
time, two "Well done"'s are shown and second how do I clear the numberswrong
variable without ruining the while loop.If I don't do anything the
numberswrong variable goes up everytime you get an incorrect guess well past
four so even when you guess right, you don't get the well done message as
numberswrong equals like 25 or something similar. Also, if you just say
numberswrong=0 at the end of the while loop the while loop thinks you got it
correct and says well done. I don't know what the solution is. A loop counter
maybe?
Help would be appreciated
Edit: I see why the "Well Done" is printed twice. As for the second query.
Still can't see it.
Edit No.2: @moose. I will answer this as best as I can. When I press run the
program says the number asks me what numbers 1-4 are and then tells me the
number of numbers I have got wrong. Only problem is the number of numbers goes
up and isn't cleared. Lets say I got all the numbers wrong 3 times. On the
third time it says you got 12 numbers wrong. Obviously I can't get 12 numbers
wrong because there is only 4 numbers to guess. I see what is happening the
while loop is not clearing after each pass. I think I know the solution. Say
somewhere numberswrong=0 to clear the loop. But I don't know where to put this
statement.
Answer: Here is the updated code! I’ve used a variable c to keep track of the number
of tries. I also break out of the infinite loop when the user has correctly
guessed the number.
from random import randint
n1 = randint(1,9)
n2 = randint(1,9)
n3 = randint(1,9)
n4 = randint(1,9)
c = 1
while True:
print (n1,n2,n3,n4)
guess1 = input("guess the first number")
guess2 = input("guess the second number")
guess3 = input("guess the third number")
guess4 = input("guess the fourth number")
guess1 = int(guess1)
guess2 = int(guess2)
guess3 = int(guess3)
guess4 = int(guess4)
numberswrong = 0
if guess1 != n1:
numberswrong += 1
if guess2 != n2:
numberswrong += 1
if guess3 != n3:
numberswrong += 1
if guess4 != n4:
numberswrong += 1
if numberswrong == 0:
print('Well Done!')
print('It took you ' + str(c) + ' ries to guess the number!')
break
else:
print('You got ' + str(4-numberswrong) + ' numbers right.')
c += 1
|
Starting Another Activity - Activity not showing my message
Question: I'm new to android developing but have experience with python and java, so I
decided I want to make apps, thus i began the tutorial from
developer.android.com.
I'm in the Build your first app > Starting Another Activity section.
I made it to the final step without errors, BUT the message I type in is not
showing up in the second activity created when i press the send button!
(<https://developer.android.com/training/basics/firstapp/starting-
activity.html#DisplayMessage>) if you click that link to see the tutorial, and
you scroll down to the bottom, you should see that the message you type should
pop up, and with a bigger font size. The message i find when i type ANYTHING
is the small font, default "Hello world!"
Here's my MyActivity.java
package com.example.android.myfirstapp;
import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
public class MyActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* Called when the user clicks the Send button */
public void SendMessage(View view) //View must be the parameter of onClick, View is what is pressed.
{
// Do something in response
Intent intent = new Intent(this, DisplayMessageActivity.class); //A Context as its first parameter (this is used because the Activity class is a subclass of Context)
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Here is the DisplayMessageActivity.java
package com.example.android.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I'm not sure if you guys would need AndroidManifest.xml, activity_my.xml, or
strings.xml but it's better to be safe than sorry!
AndroidManifest.xml below:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.myfirstapp" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DisplayMessageActivity"
android:label="@string/title_activity_display_message" >
</activity>
</application>
</manifest>
activity_my.xml below:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation = "horizontal">
<EditText
android:id = "@+id/edit_message"
android:layout_weight = "1"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:hint = "@string/edit_message"
/>
<Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@string/button_send"
android:onClick = "SendMessage"
/>
strings.xml below:
<resources>
<string name="app_name">My First App!</string>
<string name = "edit_message">Enter a Message!</string>
<string name = "button_send">Send</string>
<string name="action_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="title_activity_display_message">DisplayMessageActivity</string>
<string name="hello_world">Hello</string>
</resources>
I apologize some of the things are not indented properly if they didn't indent
properly when I copy pasted them over here.
If you could help me, I would really appreciate it, so i can continue becoming
an android developer!
Again, the app is a simple type a message and send, to see your message pop up
with bigger font size in another activity. Though mine is only showing the
default, small-font-sized "Hello world!" when the new activity pops up when i
press send.
Thank you for your time, and sorry for the long post!
Answer: First of all, replace
intent.putExtra(EXTRA_MESSAGE, message);
with
intent.putExtra("EXTRA_MESSAGE", message);
in your `MyActivity.java`
as the first argument for `putExtra()` should be a String name, which is used
further in the application. Please refer the
[docs](<http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String>,
android.os.Bundle))
Now, in your `DisplayMessageActivity.java`
write your `onCreate()` as follows
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set your parent view
setContentView(R.layout.disp_msg_layout);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra("EXTRA_MESSAGE");
// Get the reference to the TextView and update it's content
TextView textView = (TextView)findViewById(R.id.my_text_view);
textView.setText(message);
}
and declare an xml file named `disp_msg_layout` in your layouts and it should
be like
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
android:id="@+id/my_text_view"/>
|
Create base docker centos image with python 2.7.8
Question: I've found [this](http://drewcdecker.me/2014/10/creating-a-centos-65-base-
docker-image/) which walks you through creating a base bare-metal centos
image. I want to however install some additional yum packages, download Python
2.7.8 and build it.
I had this in a dockerfile and already working like:
# Set the base image to Ubuntu
FROM centos:7
# File Author / Maintainer
MAINTAINER Sam Mohamed
# Update the sources list
RUN yum -y update
RUN yum install -y zlib-dev openssl-devel sqlite-devel bzip2-devel xz-libs gcc g++ build-essential make
# Install Python 2.7.8
RUN curl -o /root/Python-2.7.9.tar.xz https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tar.xz
RUN tar -xf /root/Python-2.7.9.tar.xz -C /root
RUN cd /root/Python-2.7.9 && ./configure --prefix=/usr/local && make && make altinstall
# Copy the application folder inside the container
ADD `pwd` /opt/iws_project
# Download Setuptools and install pip and virtualenv
RUN wget https://bootstrap.pypa.io/ez_setup.py -O - | /usr/local/bin/python2.7
RUN /usr/local/bin/easy_install-2.7 pip
RUN /usr/local/bin/pip2.7 install virtualenv
# Create virtualenv and install requirements:
RUN /usr/local/bin/virtualenv /opt/iws_project/venv && source /opt/iws_project/bin/activate && pip install -r /opt/iws_project/requirements.txt
How can I convert the above into a base image?
Answer: You are probably better off building the given Dockerfile and using the
resulting image as the base for future images. This is much easier to maintain
and doesn't really cost anything in terms of resource use.
But if you really want to create a single-layer "base image", the steps are as
follows:
1. Install everything you want into some directory (`docker-centos-65/` in the linked tutorial).
* You can modify the `febootstrap` command from the tutorial you linked to install additional `yum` packages by specifying more `-i` flags.
* You can perform any other custom installs (e.g. Python) manually, just make sure everything ends up in the same root directory
2. Create a `tar` archive of the directory where everything is installed, and pipe this to the [`docker import`](https://docs.docker.com/reference/commandline/import/) command:
tar c -C docker-centos-65/ . | docker import - my-base-image
|
Nose/Unittest different tests dependent on Python version
Question: I am writing [a nose test](https://travis-ci.org/pydata/pandas/jobs/75838430)
for an API addition to pandas I'm writing. They use Travis CI to run their
test suites.
In the version of Python I'm using (Python 2.7.6, numpy 1.9.2) the following
raises a `TypeError`:
>>> numpy.round([1.23, 1.132], 2.5)
TypeError: integer argument expected, got float
But in a version being tested against by Travis CI (Python 2.6.9, numpy 1.9.2)
the same command raises a warning:
>>> numpy.round([1.23, 1.132], 2.5)
/home/some_user/anaconda/envs/py26/lib/python2.6/site-packages/numpy/core/fromnumeric.py:45: DeprecationWarning: integer argument expected, got float
result = getattr(asarray(obj), method)(*args, **kwds)
array([ 1.23, 1.13])
This means that my `assertRaises(TypeError)` test fails.
How can I write a test which will either check for `TypeError` or do
`assert_produces_warning(DeprecationWarning)` depending on what Python version
is being tested?
Answer: There seem to be two ways to do this, used in the pandas testing source.
There are several (very similar) variants on this approach:
if sys.version_info < (2, 7):
And the rather more delightful:
from distutils.version import LooseVersion
if sys.version < LooseVersion('2.7'):
which has the entertaining comment in its docstring:
> Version numbering for anarchists and software realists.
I don't know of either way being preferred over the other.
|
python web crawler with ticket authentication
Question: The website I'm trying to crawl have an login page like:
<form method="post" action="/login" enctype="multipart/form-data">
<table><tbody><tr><td>Name</td>
<td><input type="text" name="user"></td>
</tr>
<tr><td>Password</td>
<td><input type="password" name="password"></td>
</tr>
</tbody>
</table>
<input type="hidden" name="request_uri" value="/index.html">
<input type="submit" name="Log In" value="Log In">
<p></p></form>
An access ticket will be generated by the server after the login data (account
and password) have been successfully validated, containing information that
will grant access to restricted areas of the site.
This ticket, along with additional data, will be wrapped into a cookie and
sent to the browser. This cookie does not contain any life-time or expiration
information, and will thus be discarded when the session ends.
How can I login like an user by python?
Answer: Use the `requests` module and a POST to login in, then save the cookie. I
would recommend using `Fiddler2` to capture the traffic to the website and
then build your response such that the payload in your Python code matches the
payload expected by the server. Your code would look something like this:
import requests
url = 'http://mywebsite.com'
payload = {'user': 'my_usersname', 'password': 'my_password'}
r = requests.post(url, params=payload)
print r.text # for Python 3.x use print(r.text)
print r.cookies
|
Issue in Writing the contents of a variable to a file
Question: I'm trying to get the `SPF records` of a `domains` and the domains are read
from a file.When i am trying to get the spf contents and write it to a file
and the code gives me the results of last domain got from input file.
Example `Input_Domains.txt`
blah.com
box.com
marketo.com
The output,I get is only for the `marketo.com`
#!/usr/bin/python
import sys
import socket
import dns.resolver
import re
def getspf (domain):
answers = dns.resolver.query(domain, 'TXT')
for rdata in answers:
for txt_string in rdata.strings:
if txt_string.startswith('v=spf1'):
return txt_string.replace('v=spf1','')
with open('Input_Domains.txt','r') as f:
for line in f:
full_spf=getspf(line.strip())
my_file=open("out_spf.txt","w")
my_file.write(full_spf)
my_file.close()
How can i solve this by writing all the spf contents of domains which i got it
to file,Any suggestions please ?
Answer: It is because you are rewriting `full_spf` all the time so only last value is
stored
with open('Input_Domains.txt','r') as f:
for line in f:
full_spf=getspf(line.strip())
**Modification:**
with open('Input_Domains.txt','r') as f:
full_spf=""
for line in f:
full_spf+=getspf(line.strip())+"\n"
|
How do you format a string in python to given precision?
Question: I need to return a string in a program, which is finding value of e to nth
precision. I tried doing `'%f' % (n,e)`. Please suggest the right syntax.
Answer: You can manually set the precision by importing `decimal` module.
Here's the code:
from decimal import *
getcontext().prec = 40 # Decimal precision you require
value = Decimal(1).exp()
string_value = str(value) # Convert to string
Here's the working example:
>>> from decimal import *
>>> getcontext().prec = 40
>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471352662497757')
>>> data = Decimal(1).exp()
>>> str(data)
'2.718281828459045235360287471352662497757'
>>>
Here's for 2000 decimal places:
>>> from decimal import *
>>> getcontext().prec = 2000
>>> value = Decimal(1).exp()
>>> str(value)
'2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190115738341879307021540891499348841675092447614606680822648001684774118537423454424371075390777449920695517027618386062613313845830007520449338265602976067371132007093287091274437470472306969772093101416928368190255151086574637721112523897844250569536967707854499699679468644549059879316368892300987931277361782154249992295763514822082698951936680331825288693984964651058209392398294887933203625094431173012381970684161403970198376793206832823764648042953118023287825098194558153017567173613320698112509961818815930416903515988885193458072738667385894228792284998920868058257492796104841984443634632449684875602336248270419786232090021609902353043699418491463140934317381436405462531520961836908887070167683964243781405927145635490613031072085103837505101157477041718986106873969655212671546889570350354021234078498193343210681701210056278802351930332247450158539047304199577770935036604169973297250886876966403555707162268447162560798826517871341951246652010305921236677194325278675398558944896970964097545918569563802363701621120477427228364896134225164450781824423529486363721417402388934412479635743702637552944483379980161254922785092577825620926226483262779333865664816277251640191059004916449982893150566047258027786318641551956532442586982946959308019152987211725563475463964479101459040905862984967912874068705048958586717479854667757573205681288459205413340539220001137863009455606881667400169842055804033637953764520304024322566135278369511778838638744396625322498506549958862342818997077332761717839280349465014345588970719425863987727547109629537415211151368350627526023264847287039207643100595841166120545297030236472549296669381151373227536450988890313602057248176585118063036442812314965507047510254465011727211555194866850800368532281831521960037356252794495158284188294787610852639814'
>>>
Hope this helps.
|
Run scrapy from Flask application
Question: I have a crawler which I want to run everytime a person goes to the link.
Since all the other modules are in Flask, I was told to build this in Flask
also. I have installed scrapy and selenium both in the virtual environment and
globally on the machine with root.
When I run the crawler through the terminal, everything works fine. When I
start the Flask application and visit `xx.xx.xx.xx:8080/whats` in the browser,
this also works fine and runs my crawler and gets me the file. But as soon as
I go live so that anytime a person goes to the link, it gives me internal
error in browser.
In order to run crawler, we have to type "scrapy crawl
whateverthespidernameis" in the terminal. I did this using Python's `os`
module.
Here is my flask code:
import sys
from flask import request, jsonify, render_template, url_for, redirect, session, abort,render_template_string,send_file,send_from_directory
from flask import *
#from application1 import *
from main import *
from test123 import *
import os
app = Flask(__name__)
filename = ''
app = Flask(__name__)
@app.route('/whats')
def whats():
os.getcwd()
os.chdir("/var/www/myapp/whats")
//cmd = "scrapy crawl whats"
cmd = "sudo scrapy crawl whats"
os.system(cmd)
return send_file("/var/www/myapp/staticcsv/whats.csv", as_attachment =True)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080,debug=True)
This is the error recorded in the log file when I run through live link:
sh: 1: scrapy: not found**
This is the error recorded in the log file when I use sudo in the command
(variable `cmd`):
sudo: no tty present and no askpass program specified**
I am using uwsgi and nginx.
How can I run this crawler so that when anyone goes to "xx.xx.xx.xx/whats" the
crawler runs and returns the csv file?
Answer: When you use `sudo` the shell this starts will ask for a password on the tty -
it specifically doesn't read standard input for this information. Since
`flask` and other web applications typically run detached from a terminal,
`sudo` has no way to ask for a password, so it looks for a program that can
provide the password. You can find more information on this topic in [this
answer](http://stackoverflow.com/questions/21659637/how-to-fix-sudo-no-tty-
present-and-no-askpass-program-specified-error).
The reason you aren't finding `scrapy` is most likely because of differences
in your `$PATH` between the interactive shells you used in testing and the
process that's running `flask`. The easiest way to get around this is to give
the full path to the `scrapy` program in your command.
|
Running a continous while loop in python along with Flask app
Question: I am working on writing a code in raspberry pi using python where i want the
user to input the set temperature and fan mode via web page i'm using flask
for that and the values are returned successfully but i also want to run a
infinite while loop along with the flask app which will compare the set
temperature with the current temperature from a sensor.. how do i achieve this
without interrupting the flask app?
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
import time
temp = ""
t = ""
fan_High = 0
fan_Med = 0
fan_Low =0
fanspeed = ""
app = Flask(__name__)
@app.route('/form', methods=['POST'])
def aziz():
global temp ,fanspeed
fanspeedlocal = ''
if request.form['settemp'] != "":
temp = request.form['settemp']
templocal = temp
else:
templocal = temp
if request.form['speed'] == "null":
fanspeedlocal = fanspeed
else:
if request.form['speed'] == "High":
fan_Med = False
fan_Low = False
fan_High = True
fanspeed = "High"
fanspeedlocal = fanspeed
elif request.form['speed'] == "Med":
fan_High = False
fan_Low = False
fan_Med = True
fanspeed = "Medium"
fanspeedlocal = fanspeed
elif request.form['speed'] == "Low":
fan_High = False
fan_Med = False
fan_Low = True
fanspeed = "Low"
fanspeedlocal = fanspeed
print 'Settemp = %s' %temp
print 'fanspeed = %s' %fanspeed
return render_template('Output.html',temp=templocal,currtemp=strct,time=t,fanspeed=fanspeedlocal
@app.route('/')
def start():
global t , fanspeed
t = time.strftime("%H:%M:%S")
return render_template('Start.html',temp=temp,currtemp=strct,time=t,fanspeed=fanspeed)
if __name__ == '__main__':
app.debug = False
app.run(host = '192.168.1.101')
var = 1
while var == 1:
inttemp = int(temp)
if currtemp >= inttemp:
#set GPIO to high
else:
#set GPIO to low
if fanspeed == 'High':
#set GPIO to high
elif fanspeed == 'Med':
#set GPIO to high
elif fanspeed == 'LOW':
#set GPIO to high
time.sleep(10)
Answer: I think, you just input the while command inside the:
@app.route('/')
def start():
or in some place which you like
|
Python script erroneously erases created chart in .xlsx file
Question: I tried to write a script using Python which takes some specific values from
all the .csv files stored in a hierarchy of folders. These values are copied
at some specific cells in a destination file (.xlsx) which has already been
created. The destination file also has some existing empty charts (in separate
sheets) which are to be populated with the values provided by the script.
Unfortunately, after I run the script, although it works and I have the
desired values copied in the cells, for some reason, the charts disappear. I
haven't managed to understand why, giving the fact that I didn't work with
anything that implied manipulating charts in my script.
Seeing that I couldn't find any solution to this problem, I came to the
conclusion that I should implement the plotting of the charts in my script,
using the values I have. However, I would like to know if you have any idea
why this happens.
Below is my code. I have to mention that I am new to Python. Any suggestions
about the problem or about a better writing of the code would be greatly
appreciated.
# -*- coding: utf-8 -*-
import os
import glob
import csv
import openpyxl
from openpyxl import load_workbook
#getting the paths
def get_filepaths(directory):
file_paths = [] # array that will contain the path for each file
# going through the folder hierarchy
for root, directories, files in os.walk(directory):
for filename in files:
if filename.endswith('.csv'):
filepath = os.path.join(root, filename) #concatenation
file_paths.append(filepath) # filling the array
print filepath
#print file_paths[0]
return file_paths
#extraction of the value of interest from every .csv file
def read_cell(string, paths):
with open(paths, 'r') as f:
reader = csv.reader(f)
for n in reader:
if string in n:
cell_value = n[1]
return cell_value
#array containing the path extracted for each file
paths_F = get_filepaths('C:\Dir\mystuff\files')
#destination folder
dest = r'C:\Dir\mystuff\destination.xlsx'
#the value of interest
target = "something"
#array that will contain the value for each cell
F30 = [];
#obtaining the values
for selection_F in paths_F:
if '30cm' in selection_CD:
val_F30 = read_cell(target, selection_F); F30.append(val_F30)
#print val_F30
wb = load_workbook(dest)
#the sheet in which I want to write the values extracted from the files
ws3EV = wb.get_sheet_by_name("3EV")
cell_E6 = ws10EV.cell( 'E6' ).value = int(F30[0])
cell_E7 = ws10EV.cell( 'E7' ).value = int(F30[1])
Answer: I have been able to recreate your problem. After simply loading and saving an
existing xlsx file using openpyxl, my chart was lost without making any
changes.
Unfortunately, according to the [documentation for
openpyxl](https://openpyxl.readthedocs.org/en/latest/charts.html#charts):
> Warning
>
> Openpyxl currently supports chart creation within a worksheet only. Charts
> in existing workbooks will be lost.
It does though support the creation of a limited number of charts:
* Bar Chart
* Line Chart
* Scatter Chart
* Pie Chart
You could possibly recreate the required chart using these.
|
Eclipse/CDT Pretty Printing With Remote Debugging
Question: I'm trying to add pretty printing for STL objects in my Eclipse/CDT (Mars
release) to remote debug application running in an ARM board.
I can succesfully debug my application using Eclipse and gdbserver. For this
purpose I use the following gdbinit file:
set sysroot remote:/
Then I'm trying to follow the steps available in teh Eclipse Wiki to have the
pretty printing for STL structures: <http://wiki.eclipse.org/CDT/User/FAQ>
I downloaded successfully the files from SVN, and added the indicated lines to
my gdbinit file, which became:
set sysroot remote:/
python
import sys
sys.path.insert(0, '/home/rvcpu/prettyprinting')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (None)
end
When I start the Debug session I get the following error on the gdb trace:
418,226 12-gdb-set target-wide-charset UTF-32
418,227 12^done
418,227 (gdb)
418,228 13-gdb-set dprintf-style call
418,228 13^done
418,228 (gdb)
418,232 14source /home/rvcpu/CodeSourcery/Sourcery_G++_Lite/bin/gdbinit
418,232 &"source /home/rvcpu/CodeSourcery/Sourcery_G++_Lite/bin/gdbinit\n"
418,232 =cmd-param-changed,param="sysroot",value="remote:/"
I believe I must indicate to GDB, somehow, that the python script is located
on my host computer, not the target. Does anyone know how to do that?
Thanks, Bernardo
Answer: You should add that lines to .gdbinit on host machine and python directory
with "libstdcxx" library should be on host machine too. And if you have python
directory in subdirectory "prettyprinting", you should set that directory
which contain libstdcxx directory. So if you has printers here:
/home/rvcpu/prettyprinting/python/libstdcxx/v6/
you need to insert
/home/rvcpu/prettyprinting/python/
to your sys.path in python code of .gdbinit.
|
How can I see name of failed tests if setUpClass is failed?
Question: please help me. How to see name of failed tests if setUpClass is failed?
EXAMPLE:
import unittest
import nose
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
print "Execute setup class!"
assert 10 != 10
def test_1(self):
"""Test # 1"""
pass
def test_2(self):
"""Test # 2"""
pass
if __name__ == "__main__":
nose.run(argv=[" ", "work_temp.py", "--verbosity=2", "--nocapture"])
* * *
If some assertion in SetUp fails - I have bad output like this (can't see test
name):
======================================================================
ERROR: test suite for <class 'tests.work_temp.Test'>
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/nose/suite.py", line 209, in run
self.setUp()
.....................................................................
return func()
File "/home/temp/PycharmProjects/Safo/tests/work_temp.py", line 9, in setUpClass
assert 10 != 10
AssertionError
----------------------------------------------------------------------
Ran 0 tests in 0.001s
FAILED (errors=1)
I expected to see something like this:
>
> Test # 1 ... FAILED
> Test # 2 ... FAILED
>
Answer: You are throwing an assert exception when you are creating the container class
for your test methods, and the only logical behaviour in this case is not to
run underlying tests. This is what nose does, but it does so to be compliant
with [python unittest
specifications](https://docs.python.org/2/library/unittest.html#setupclass-
and-teardownclass):
> If an exception is raised during a setUpClass then the tests in the class
> are not run and the tearDownClass is not run.
If you are willing to step outside of unittest library, you can get the
behaviour that you want by modifying your code something like this:
from nose.tools import with_setup
def setup_func():
print "Execute setup class!"
assert 10 != 10
@with_setup(setup_func)
def test_1():
"""Test # 1"""
pass
@with_setup(setup_func)
def test_2():
"""Test # 2"""
pass
|
Connect two source files in python?
Question: I was trying to split
[this](http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod,_part_13_code)
into some smaller files, but its really hard for me becouse of complicated
class-global_variable-function relations. Is there any way to connect two
files like they were one file in python?
Sorry if this was unclear, i add example of problem:
#\a.py
def print_foo():
global foo
print foo
#\main.py
from a import *
def initialize_values():
global foo, bar
foo='abc'
bar=123
initialize_values()
print_foo()
This causes error "global variable foo not declared" or something like that.
Answer: Python doesn't have truly global variables, only module-level globals. That
is, in `a.print_foo`, the statement `global foo` refers to the variable
`a.foo`. In `main.initialize_values`, `global foo` refers to `main.foo`. When
you call `print_foo`, it tries to print `a.foo`, but that name was never
defined.
You could write in `main.py`
import a
def initialize_values():
global bar # keep in mind, this is main.bar
a.foo='abc'
bar=123
initialize_values()
a.print_foo()
but that raises a question of design: why are you initializing global
variables in the module `a` from a different module?
|
How to edit the style of a heading in Treeview (Python ttk)
Question: I am trying to use ttk.Treeview to make a sortable table (as per [Does tkinter
have a table widget?](http://stackoverflow.com/questions/9348264/does-tkinter-
have-a-table-widget) and <https://www.daniweb.com/software-
development/python/threads/350266/creating-table-in-python>).
Getting it to work is easy, but I'm having some issues with the styling. The
default style for the Treeview heading is black text on a white background,
which is fine. However, in my code I'm using:
ttk.Style().configure(".", font=('Helvetica', 8), foreground="white")
to format my GUI. This overarching style also affects the heading of the
Treeview widget. Because the default heading background is white, I can not
see the text (unless I mouse-over the heading, which turns it light-blue).
Normally, I'd override the style of a widget using a tag to change either the
background or foreground, but I can't for the life of me figure out how to
adjust the Treeview headers! ttk.Treeview(...) doesn't accept any tags, and
ttk.Style().configure("Treeview", ...) has no effect. Only the Treeview items
appear to accept tags when using widget.insert(...).
This baffles me, because the overarching ttk.Style().configure(".",...) _does_
affect the Treeview headings, so it should be possible to apply a tag to them.
**_Does anybody know how to alter the style of a Treeview heading?_**
Below is a Minimum Working Example. Notice that the tag works for items but
not for headings, that the Treeview style has no effect, and that the "."
style does have an effect. I'm using Python 2.7 on Windows 7 in case that
makes a difference.
from Tkinter import *
import ttk
header = ['car', 'repair']
data = [
('Hyundai', 'brakes') ,
('Honda', 'light') ,
('Lexus', 'battery') ,
('Benz', 'wiper') ,
('Ford', 'tire')]
root = Tk()
frame = ttk.Frame(root)
frame.pack()
table = ttk.Treeview(frame, columns=header, show="headings")
table.pack()
## table.tag_configure('items', foreground='blue')
## ttk.Style().configure("Treeview", background='red', foreground='yellow')
## ttk.Style().configure(".", font=('Helvetica', 8), foreground="white")
for col in header:
table.heading(col, text=col.title(), command=lambda c=col: sortby(table, c, 0))
for item in data:
table.insert('', 'end', values=item, tags=('items',))
def sortby(tree, col, descending):
"""sort tree contents when a column header is clicked on"""
# grab values to sort
data = [(tree.set(child, col), child) \
for child in tree.get_children('')]
# if the data to be sorted is numeric change to float
#data = change_numeric(data)
# now sort the data in place
data.sort(reverse=descending)
for ix, item in enumerate(data):
tree.move(item[1], '', ix)
# switch the heading so it will sort in the opposite direction
tree.heading(col, command=lambda col=col: sortby(tree, col, \
int(not descending)))
root.mainloop()
Answer: this works where I am -
style = ttk.Style()
style.configure(".", font=('Helvetica', 8), foreground="white")
style.configure("Treeview", foreground='red')
style.configure("Treeview.Heading", foreground='green') #<----
<http://www.tkdocs.com/tutorial/styles.html>
|
parsing a dns configuration file with python
Question: Not sure this question has it's place, but i'll give it a shot anyway.
Basically what I need is to parse a conf file.
It would look like this :
1. #local-data: "some.dns.url IN MX 192.168.80.45"
2. local-data: "some.other.dns.url IN A 192.168.60.1"
3. local-data: "router.home.somewhere IN A 192.168.20.1"
4. *a linebreak*
5. local-data-ptr: "192.168.80.45 some.dns.url"
6. local-data-ptr: "192.168.60.1 some.other.dns.url"
7. # some other random comment
8. local-data-ptr: "192.168.20.1 router.home.somewhere"
What i'd need to get off of it is : The address : "some.other.dns.url" on the
**2** nd line what is after the "IN" : that can be MX, A, some others. The IP
: in that case 192.168.60.1, but that could be anything else.
I don't necessarily need the complete script. Hell I don't even really need
one, that's not my goal posting here. I would like to know the best approach
for such a case. Most of the time I tend to get out of situations like that,
but this time this seems a bit tricky as :
* I can't base myself on the size of the line.
* I can't base myself on "dots" `(.)` for the address, as one could have 2 dots, and another one have 3.
* I have part of the line (`"IN"`) that is just disturbing and not of some use.
What i've done so far :
dnsconf = open('theconffile.conf', 'r')
dnsconf = dnsconf.readlines()
x = []
for line in dnsconf:
cont = re.findall('\"(.+?)\"', line)
if len(line) > 1 and line[:1] is not '#':
x.append(cont)
print cont
`cont` basically contains what is inside the double quotes. "some.dns.url IN
MX 192.168.80.45" for exemple.
I feel like this is a good start but I fail to see how to continue from there.
I am not good with regexes and I feel like what I need are actually
regexes...so i'm a little bit stuck here.
Can anyone put me on the right track for this problem?
Answer: This ignores the lines beginning with #, decode lines beginning 'local-data:',
and parses out the hostname, DNS type and IP address to a list:
import re
dnsconf = open('dns.txt', 'rt')
x = []
for line in dnsconf:
cont = re.findall('^local-data:\s+\"(\S+)\s+IN\s+(\S+)\s+(\S+)\"', line)
if cont:
x.append(cont)
print cont
This allows spaces to be repeated within the strings by using \s+.
Output for your data is:
[('some.other.dns.url', 'A', '192.168.60.1')]
[('router.home.somewhere', 'A', '192.168.20.1')]
Note unless you have a reason to need all the text in memory there is no need
to use readlines(). Also for Windows-robustness, using file open mode "rt"
doesn't do any harm on unixy systems.
|
ARIMA seasonal prediction with Python: x12a and x13as not found on path
Question: I am using Statsmodels to implement seasonal ARIMA prediction for time series.
Here is my code :
import statsmodels.api as sm
from statsmodels.tsa.x13 import x13_arima_select_order, _find_x12
import pandas
import scipy
import numpy
import imp
data_source = imp.load_source('data_source', '/mypath/')
def main():
data=data_source.getdata()
res = x13_arima_select_order(data)
print (res.order, res.sorder)
main()
When running the code, I am getting this exception:
X13NotFoundError("x12a and x13as not found on path. Give the "
statsmodels.tools.sm_exceptions.X13NotFoundError: x12a and x13as not found on
path. Give the path, put them on PATH, or set the X12PATH or X13PATH
environmental variable.
Answer: From looking at the [source code for
statsmodels.tsa.x13](http://statsmodels.sourceforge.net/devel/_modules/statsmodels/tsa/x13.html)
you need to have either the `x12a` or `x13as` binary applications installed on
your system. In addition to that, the path to the folders where those binaries
are located must be set in your user's `PATH` environment variable. You don't
mention what operating system you're running, so here's a page with links to
OS specific download pages on the left hand side to help you install the
needed software. <https://www.census.gov/srd/www/x13as/>
This is the link to the source I'm referencing to figure out what you're
missing in your environment:
<http://statsmodels.sourceforge.net/devel/_modules/statsmodels/tsa/x13.html>
def x13_arima_analysis(endog, maxorder=(2, 1), maxdiff=(2, 1), diff=None,
exog=None, log=None, outlier=True, trading=False,
forecast_years=None, retspec=False,
speconly=False, start=None, freq=None,
print_stdout=False, x12path=None, prefer_x13=True):
...
x12path = _check_x12(x12path)
if not isinstance(endog, (pd.DataFrame, pd.Series)):
if start is None or freq is None:
raise ValueError("start and freq cannot be none if endog is not "
"a pandas object")
endog = pd.Series(endog, index=pd.DatetimeIndex(start=start,
periods=len(endog),
freq=freq))
...
def _check_x12(x12path=None):
x12path = _find_x12(x12path)
if not x12path:
raise X13NotFoundError("x12a and x13as not found on path. Give the "
"path, put them on PATH, or set the "
"X12PATH or X13PATH environmental variable.")
return x12path
...
def _find_x12(x12path=None, prefer_x13=True):
"""
If x12path is not given, then either x13as[.exe] or x12a[.exe] must
be found on the PATH. Otherwise, the environmental variable X12PATH or
X13PATH must be defined. If prefer_x13 is True, only X13PATH is searched
for. If it is false, only X12PATH is searched for.
"""
|
HTTPSHandler error while installing pip with python 2.7.9
Question: Hi I am trying to install pip with python 2.7.9 but keep getting following
error. I want to create python virtual env.
python get-pip.py
Traceback (most recent call last):
File "get-pip.py", line 17767, in <module>
main()
File "get-pip.py", line 162, in main
bootstrap(tmpdir=tmpdir)
File "get-pip.py", line 82, in bootstrap
import pip
File "/tmp/tmp_Tfw2V/pip.zip/pip/__init__.py", line 15, in <module>
File "/tmp/tmp_Tfw2V/pip.zip/pip/vcs/subversion.py", line 9, in <module>
File "/tmp/tmp_Tfw2V/pip.zip/pip/index.py", line 30, in <module>
File "/tmp/tmp_Tfw2V/pip.zip/pip/wheel.py", line 35, in <module>
File "/tmp/tmp_Tfw2V/pip.zip/pip/_vendor/distlib/scripts.py", line 14, in <module>
File "/tmp/tmp_Tfw2V/pip.zip/pip/_vendor/distlib/compat.py", line 31, in <module>
ImportError: cannot import name HTTPSHandler
I guess this is something related to openssl libraries. Since i don't have
sudo access I would like to install it in home folder from source. Any idea
how to do it?
Answer: Make sure you have openssl and openssl-devel installed before you build Python
2.7
yum install openssl openssl-devel
or
apt-get install openssl openssl-devel
or (for Debian):
apt-get install libssl-dev
To rebuild Python
cd ~
wget https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz
tar xzf Python-2.7.9.tgz
cd Python-2.7.9
./configure
make install
Then the `python get-pip.py` should work.
|
Pull comments from Facebook API (Python, JSON)
Question: I want to pull all comments from all posts the last 24 hours using the
Facebook API. Currently, I can only pull from a certain data range of posts as
the Facebook API only allows "since" and "until" to be used under posts. I
can't seem to use those parameters for comments. So for example, with my code
currently, I cannot pull today's comments from a post that was posted in
April. **Has anyone been able to pull comments from all posts in the last 24
hours without including the posts?** This is my code so far:
import facebook
import requests
import json
import urllib
import urllib2
import time
now = 1439769600
thyme = int(time.time())
since = int((thyme - 0.7 * 60 * 1000))
user = 'INSERT USER ID/NUMBER'
access_token = 'INSERT ACCESS TOKEN'
url = ' https://graph.facebook.com/v2.4/' + user + '?fields=posts.until' + '(' + str(now) + ')' + '.since' + '(' + str(since) + ')' + '.limit(100)%7Bcreated_time%2Cmessage%2Ccomments.limit(1000)%7Bcreated_time%2Cmessage%7D%7D&access_token='
html = url + access_token
print html
data = json.load(urllib2.urlopen(html))
with open('here.txt', 'w') as textfile:
json.dump(data, textfile)
Answer: No worries I came up with the code that solves everything for me:
import facebook
import requests
import json
import urllib
import urllib2
#def some_action(post):
#print posts['data']
# print(post['created_time'])
access_token = 'ENTER ACCESS TOKEN'
url = 'https://graph.facebook.com/v2.4/ENTER FACEBOOK USERNAME/IDNUMBER FOLLOWED BY ?fields=posts.since(1406851200).limit(50)%7Bcreated_time%2Cmessage%2Ccomments.limit(2000)%7Bcreated_time%2Cmessage%7D%7D&access_token='
html = url + access_token
data = json.load(urllib2.urlopen(html))
with open('penguin.txt', 'w') as textfile:
json.dump(data, textfile)
|
import urllib.parse returns "ImportError:No module named parse" for jython 2.7.0
Question: I am using jython 2.7.0 with Java 1.7.0_45 on Windows 7. I call my module with
the following Java code
try{
python.exec("import sys");
python.exec("sys.path.append('c:/Python')");
python.exec("import myModule");
python.set("var1", new PyString(remote));
python.exec("myModule.score(var1)");
} catch (org.python.core.PyException e) {
System.out.println (e.toString());
System.out.println ("\n");
}
The Python code for myModule.score begins with
import json
import urllib.parse
This causes the error
import urllib.parse
ImportError: No module named parse
I am suspecting this is related to Python's format changing between versions
and functions becoming deprecated. I was wondering if someone knew which
version of Python jython 2.7.0 uses and what the correct syntax would be to
call urllib.parse (which works fine in Python 3.5).
Answer: Jython 2.7 uses the Python 2.7 standard library. The version number is
specifically designed to correlate with the CPython version number.
|
How to get relevant month and date by inputting only the day of year in python
Question: I'm developing a phonebook application from python as a mini project in which
I'm having the requirement to store the NIC number of a person and then
display his/her gender, DOB and age. I have to derive these 3 information and
I'm able to derive the gender, but I don't know how to derive the DOB - only
the birth year because the NIC number's first 2 digits represent the year of
birth.
In a NIC number, the 3rd three digits are the day of year :- from 001 to 366.
I can seperate those 3 digits to another variable as well, but how do I derive
the month and the date of month which it refers to?
For example :
derivedYear = 1996
dayOfYear = 032
finalDOB = "1996.02.01"
print finalDOB
I want to know how to calculate the finalDOB value. I'm using python 2.7.6
Answer: You can use
[`timedelta()`](https://docs.python.org/2/library/datetime.html#datetime.timedelta).
It can take days as an argument, and when added to a date, will shift it by
that amount.
import datetime
year = 1996
days = 32
date = datetime.date(year, 1, 1) #Will give 1996-01-01
delta = datetime.timedelta(days - 1) #str(delta) will be '31 days, 0:00:00'
newdate = date + delta
>>> str(newdate)
>>> 1996-02-01
or
>>> newdate.strftime('%Y.%m.%d')
>>> '1996.02.01'
|
How to have WebDriverWait return element instead of boolean in Python using Selenium
Question: Right now, I have a method that will wait until an element is visible using:
WebDriverWait(self.driver, seconds).until(lambda s: s.find_element_by_xpath(path).is_displayed())
This works properly; however, it returns a boolean, rather than the element
that it found. I would like it to return that element once it is found. I am
doing this with the following:
def waituntil(path, seconds):
WebDriverWait(self.driver, seconds).until(lambda s: s.find_element_by_xpath(path).is_displayed())
ret = self.driver.find_element_by_xpath(path)
return ret
Sure, this works. Unfortunately, it requires Selenium to find the same element
twice, though, which adds waiting time (no matter how small). Is there a way I
can return a web element using a waituntil (or similar functionality) by
finding an element only once? So something that would allow the following:
ret = WebDriverWait(self.driver, seconds).until(lambda s: s.find_element_by_xpath(path).is_displayed())
ret.click()
I'm currently using:
Python 2.7
Windows 7
Selenium 2.4.4
Firefox 35.0.1
Answer: Use
`selenium.webdriver.support.expected_conditions.presence_of_element_located`.
Based on [the unofficial docs](http://selenium-
python.readthedocs.org/waits.html):
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
ret = WebDriverWait(self.driver, seconds).until(
expected_conditions.presence_of_element_located((By.XPATH, path)))
ret.click()
(Left out other imports and initialization for clarity, since you seem to have
that stuff working. See the earlier link if you're running into issues.)
|
Python Flask - making ALL file uploads go to tmp directory
Question: According to the
[docs](http://flask.pocoo.org/docs/0.10/patterns/fileuploads/#improving-
uploads), Flask stores the uploaded file in-memory if the file is 'reasonably
small' (no upper limit mentioned) and otherwise in temporary location as
returned by `tempfile.gettempdir()`.
How can I make it store ALL files to the temporary directory?
Answer: According to a [`Flask`
doc](https://github.com/mitsuhiko/flask/blob/master/docs/patterns/fileuploads.rst#uploading-
files), handling of uploading files is actually handled by its underlying
[werkzeug](http://werkzeug.pocoo.org/) WSGI utility library.
As per [werkzeug's
documentation](http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseRequest._get_file_stream)
the lower-limit for getting file's `temp` location, as you mentioned as
"reasonably small", is `500KB`.
> The default implementation returns a temporary file if the total content
> length is higher than 500KB. Because many browsers do not provide a content
> length for the files only the total content length matters.
Let's look into the upper limit. As per [aforementioned `Flask`
doc](https://github.com/mitsuhiko/flask/blob/master/docs/patterns/fileuploads.rst#uploading-
files),
> By default Flask will happily accept file uploads to **an unlimited amount
> of memory** ,but you can limit that by setting the `MAX_CONTENT_LENGTH`
> config key.
For example, this code fragment
from flask import Flask, Request
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
> will limited the maximum allowed payload to 16 megabytes. If a larger file
> is transmitted, Flask will raise an
> `werkzeug.exceptions.RequestEntityTooLarge` exception.
**Now, answering your core question**
> How can I make it store ALL files to the temporary directory?
You can do that by overriding
[`default_stream_factory()`](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/formparser.py#L38)
function to this:
def default_stream_factory(total_content_length, filename, content_type, content_length=None):
"""The stream factory that is used per default."""
# if total_content_length > 1024 * 500:
# return TemporaryFile('wb+')
# return BytesIO()
return TemporaryFile('wb+')
|
ipython startup config for spyder IDE
Question: Trying to add a few imports to my IPython profile so that when I open a kernel
in the Spyder IDE they're always loaded. Spyder has a Qt interface (I
think??), so I (a) checked to make sure I was in the right directory for the
profile using the `ipython locate` command in the terminal (OSX), and (b)
placing the following code in my `ipython_qtconsole_config.py` file:
c.IPythonQtConsoleApp.exec_lines = ["import pandas as pd",
"pd.set_option('io.hdf.default_format', 'table')",
"pd.set_option('mode.chained_assignment','raise')",
"from __future__ import division, print_function"]
But when I open a new window and type `pd.__version__` I get the `NameError:
name 'pd' is not defined` error.
Edit: I don't have any problems if I run `ipython qtconsole` from the
Terminal.
Suggestions?
Thanks!
Answer: Whether Spyder uses a QT interface or not shouldn't be related to which of the
IPython config files you want to modify. The one you chose to modify,
`ipython_qtconsole_config.py` is the configuration file that is loaded when
you launch _IPython's_ QT console, such as with the command line command
user@system:~$ ipython qtconsole
(I needed to update `pyzmq` for this to work.)
If _Spyder_ maintains a running IPython kernel and merely manages how to
display that for you, then Spyder is probably just maintaining a regular
IPython session, in which case you want your configuration settings to go into
the file `ipython_config.py` at the same directory where you found
`ipython_qtconsole_config.py`.
I manage this slightly differently than you do. Inside of `ipython_config.py`
the top few lines for me look like this:
# Configuration file for ipython.
from os.path import join as pjoin
from IPython.utils.path import get_ipython_dir
c = get_config()
c.InteractiveShellApp.exec_files = [
pjoin(get_ipython_dir(), "profile_default", "launch.py")
]
What this does is to obtain the IPython configuration directory for me, add on
the `profile_default` subdirectory, and then add on the name `launch.py` which
is a file that I created just to hold anything I want to be executed/loaded
upon startup.
For example, here's the first bit from my file `launch.py`:
"""
IPython launch script
Author: Ely M. Spears
"""
import re
import os
import abc
import sys
import mock
import time
import types
import pandas
import inspect
import cPickle
import unittest
import operator
import warnings
import datetime
import dateutil
import calendar
import copy_reg
import itertools
import contextlib
import collections
import numpy as np
import scipy as sp
import scipy.stats as st
import scipy.weave as weave
import multiprocessing as mp
from IPython.core.magic import (
Magics,
register_line_magic,
register_cell_magic,
register_line_cell_magic
)
from dateutil.relativedelta import relativedelta as drr
###########################
# Pickle/Unpickle methods #
###########################
# See explanation at:
# < http://bytes.com/topic/python/answers/
# 552476-why-cant-you-pickle-instancemethods >
def _pickle_method(method):
func_name = method.im_func.__name__
obj = method.im_self
cls = method.im_class
return _unpickle_method, (func_name, obj, cls)
def _unpickle_method(func_name, obj, cls):
for cls in cls.mro():
try:
func = cls.__dict__[func_name]
except KeyError:
pass
else:
break
return func.__get__(obj, cls)
copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)
#############
# Utilities #
#############
def interface_methods(*methods):
"""
Class decorator that can decorate an abstract base class with method names
that must be checked in order for isinstance or issubclass to return True.
"""
def decorator(Base):
def __subclasshook__(Class, Subclass):
if Class is Base:
all_ancestor_attrs = [ancestor_class.__dict__.keys()
for ancestor_class in Subclass.__mro__]
if all(method in all_ancestor_attrs for method in methods):
return True
return NotImplemented
Base.__subclasshook__ = classmethod(__subclasshook__)
return Base
def interface(*attributes):
"""
Class decorator checking for any kind of attributes, not just methods.
Usage:
@interface(('foo', 'bar', 'baz))
class Blah
pass
Now, new classes will be treated as if they are subclasses of Blah, and
instances will be treated instances of Blah, provided they possess the
attributes 'foo', 'bar', and 'baz'.
"""
def decorator(Base):
def checker(Other):
return all(hasattr(Other, a) for a in attributes)
def __subclasshook__(cls, Other):
if checker(Other):
return True
return NotImplemented
def __instancecheck__(cls, Other):
return checker(Other)
Base.__metaclass__.__subclasshook__ = classmethod(__subclasshook__)
Base.__metaclass__.__instancecheck__ = classmethod(__instancecheck__)
return Base
return decorator
There's a lot more, probably dozens of helper functions, snippets of code I've
thought are cool and just want to play with, etc. I also define some randomly
generated toy data sets, like NumPy arrays and Pandas DataFrames, so that when
I want to poke around with some one-off Pandas syntax or something, some toy
data is always right there.
The other upside is that this factors out the custom imports, function
definitions, etc. that I want loaded, so if I want the same things loaded for
the notebook and/or the qt console, I can just add the same bit of code to
exec the file `launch.py` and I can make changes in _only_ `launch.py` without
having to manually migrate them to each of the three configuration files.
I also uncomment a few of the different settings, especially for plain IPython
and for the notebook, so the config files are meaningfully different from each
other, just not based on what modules I want imported on start up.
|
Line numbers and Syntax Highlighting don't work on different tabs
Question: I am trying to resolve the issue in which `line numbers` don't work properly
in `multiple tabs`. The issue is that when I create a new tab, the `line
numbers` for the other tabs don't work, but the `line numbers for the current
tab` does. Same goes for `syntax highlighting`.
I think the issue is in using the same variables when creating a new tab, but
I have no idea how to resolve this issue and I am not sure if this is truly
the problem. I was also thinking about redefining the text box, and the
bindings associated with it everytime a tab is clicked.
Below is my code:
import tkinter as tk
import tkinter.filedialog
import traceback
import tkinter.ttk as ttk
from pygments import lex
from pygments.lexers import PythonLexer
import sys
import os
class TextLineNumbers(tk.Canvas):
def __init__(self, *args, **kwargs):
tk.Canvas.__init__(self, *args, **kwargs)
self.textwidget = None
def attach(self, text_widget):
self.textwidget = text_widget
def redraw(self, *args):
'''redraw line numbers'''
self.delete("all")
i = self.textwidget.index("@0,0")
while True:
dline= self.textwidget.dlineinfo(i)
if dline is None: break
y = dline[1]
linenum = str(i).split(".")[0]
self.create_text(5,y,anchor="nw", text=linenum, font=("Courier", 9))
i = self.textwidget.index("%s+1line" % i)
class CustomText(tk.Text):
def __init__(self, *args, **kwargs):
tk.Text.__init__(self, *args, **kwargs)
self.tk.eval('''
proc widget_proxy {widget widget_command args} {
# call the real tk widget command with the real args
set result [uplevel [linsert $args 0 $widget_command]]
# generate the event for certain types of commands
if {([lindex $args 0] in {insert replace delete}) ||
([lrange $args 0 2] == {mark set insert}) ||
([lrange $args 0 1] == {xview moveto}) ||
([lrange $args 0 1] == {xview scroll}) ||
([lrange $args 0 1] == {yview moveto}) ||
([lrange $args 0 1] == {yview scroll})} {
event generate $widget <<Change>> -when tail
}
# return the result from the real widget command
return $result
}
''')
self.tk.eval('''
rename {widget} _{widget}
interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
'''.format(widget=str(self)))
self.comment = False
class Arshi(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.fileName = "Untitled Document"
self.content = ""
self.previousContent = ""
self.language = "Python"
self.row = "0"
self.column = "0"
self.startCol = 0
self.notebook = ttk.Notebook(self)
self.menubar()
self.bottomLabel()
self.createtext()
def deafultHighlight(self, argument):
self.content = self.text.get("1.0", tk.END)
self.lines = self.content.split("\n")
if (self.previousContent != self.content):
self.text.mark_set("range_start", self.row + ".0")
data = self.text.get(self.row + ".0", self.row + "." + str(len(self.lines[int(self.row) - 1])))
for token, content in lex(data, PythonLexer()):
self.text.mark_set("range_end", "range_start + %dc" % len(content))
self.text.tag_add(str(token), "range_start", "range_end")
self.text.mark_set("range_start", "range_end")
self.previousContent = self.text.get("1.0", tk.END)
def highlight(self, argument):
self.content = self.text.get("1.0", tk.END)
if (self.previousContent != self.content):
self.text.mark_set("range_start", "1.0")
data = self.text.get("1.0", self.text.index(tk.INSERT))
for token, content in lex(data, PythonLexer()):
self.text.mark_set("range_end", "range_start + %dc" % len(content))
self.text.tag_add(str(token), "range_start", "range_end")
self.text.mark_set("range_start", "range_end")
self.previousContent = self.text.get("1.0", tk.END)
def keypress(self, argument):
self.updateBottomLabel()
self.deafultHighlight("argument")
def configureTags(self, text):
text.tag_configure("Token.Keyword", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Constant", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Declaration", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Namespace", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Pseudo", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Reserved", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Type", foreground="#CC7A00")
text.tag_configure("Token.Name.Class", foreground="#003D99")
text.tag_configure("Token.Name.Exception", foreground="#003D99")
text.tag_configure("Token.Name.Function", foreground="#003D99")
text.tag_configure("Token.Operator.Word", foreground="#CC7A00")
text.tag_configure("Token.Comment", foreground="#B80000")
text.tag_configure("Token.Literal.String", foreground="#248F24")
def createtext(self):
self.notebook.pack(fill=tk.BOTH, expand=True)
self.tab1 = ttk.Frame(self.notebook)
self.text = CustomText(self.tab1, bd=0, font=("Courier", 9))
self.configureTags(self.text)
self.vsb = tk.Scrollbar(self.tab1, orient=tk.VERTICAL)
self.text.configure(yscrollcommand=self.vsb.set)
self.vsb.configure(command=self.text.yview)
self.linenumbers = TextLineNumbers(self.tab1, width=55)
self.linenumbers.attach(self.text)
self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
self.linenumbers.pack(side="left", fill="y")
self.text.pack(side="right", fill="both", expand=True)
self.notebook.add(self.tab1, text=self.fileName)
self.text.bind("<<Change>>", self._on_change)
self.text.bind("<Configure>", self._on_change)
self.text.bind("<KeyRelease>", self.keypress)
self.text.bind("<Button-1>", self.keypress)
def addtab(self):
self.newTab = ttk.Frame(self.notebook)
self.text = CustomText(self.newTab, bd=0, font=("Courier", 9))
self.configureTags(self.text)
self.vsb = tk.Scrollbar(self.newTab, orient=tk.VERTICAL)
self.text.configure(yscrollcommand=self.vsb.set)
self.vsb.configure(command=self.text.yview)
self.linenumbers = TextLineNumbers(self.newTab, width=55)
self.linenumbers.attach(self.text)
self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
self.linenumbers.pack(side="left", fill="y")
self.text.pack(side="right", fill="both", expand=True)
self.notebook.add(self.newTab, text="Untitled Document")
self.text.bind("<<Change>>", self._on_change)
self.text.bind("<Configure>", self._on_change)
self.text.bind("<KeyRelease>", self.keypress)
self.text.bind("<Button-1>", self.keypress)
def removetab(self):
numberOfTabs = self.notebook.index("end")
if numberOfTabs > 1:
tabIndex = self.notebook.index(self.notebook.select())
self.notebook.forget(tabIndex)
def run(self):
pass
def menubar(self):
self.menu = tk.Menu(self)
self.master.config(menu=self.menu)
self.fileMenu = tk.Menu(self.menu, font=("Courier", 9))
self.fileMenu.add_command(label="New Ctrl+N", command=self.newFile)
self.fileMenu.add_command(label="Open Ctrl+O", command=self.openFile)
self.fileMenu.add_command(label="Save Ctrl+S", command=self.saveFile)
self.fileMenu.add_command(label="Save As Ctrl+Shift+S", command=self.saveAsFile)
self.fileMenu.add_separator()
self.fileMenu.add_command(label="New Window", command=self.addtab)
self.fileMenu.add_command(label="Close Window", command=self.removetab)
self.fileMenu.add_separator()
self.fileMenu.add_command(label="Exit Alt+F4", command=self.close)
self.menu.add_cascade(label="File", menu=self.fileMenu)
self.runMenu = tk.Menu(self.menu, font=("Courier", 9))
self.runMenu.add_command(label="Run", command=self.run)
self.menu.add_cascade(label="Run", menu=self.runMenu)
def bottomLabel(self):
self.positionAndLanguage = tk.Label(self, text=" Ln: 1, Col: 0, Lang: Plain", anchor=tk.W, bg="#E7E7E7", font=("Courier New", 8))
self.positionAndLanguage.pack(fill=tk.X, side=tk.BOTTOM)
def updateBottomLabel(self):
self.row = self.text.index(tk.INSERT).split(".")[0]
self.column = self.text.index(tk.INSERT).split(".")[1]
self.positionAndLanguage["text"] = " Ln: {0}, Col: {1}, Lang: {2}".format(self.row, self.column, self.language)
def newFile(self):
self.fileName = "Untitled"
self.previousContent = ""
self.text.delete(0.0, tk.END)
def openFile(self):
try:
self.fileName = tk.filedialog.askopenfilename() #Asks user to open file
with open(self.fileName, 'r') as file:
self.content = file.read() #Reads content typed
self.text.delete(0.0, tk.END)
self.text.insert(0.0, self.content)
self.highlight(self)
except IOError as e:
print("Error reading file.")
except:
print("Unexpected error occured.")
def deleteContent(self, file):
file.seek(0)
file.truncate()
def saveFile(self):
self.content = self.text.get(0.0, tk.END)
try:
with open(self.fileName, 'w') as file:
self.deleteContent(file)
file.write(self.content)
except IOError as e:
print("Error reading file.")
except:
print("Unexpected error occured.")
def saveAsFile(self):
self.content = self.text.get(0.0, tk.END)
try:
self.fileName = tk.filedialog.asksaveasfilename()
if self.fileName != None:
with open(self.fileName, 'w') as file:
file.write(self.content)
except IOError as e:
print("Error reading file.")
except:
print("Unexcepted error occured.")
def close(self):
try:
os._exit(0)
except:
print(sys.exc_info()[0])
def _on_change(self, event):
self.linenumbers.redraw()
if __name__ == "__main__":
root = tk.Tk()
root.title("Arshi")
root.geometry("1024x600")
window = Arshi(root).pack(side="top", fill="both", expand=True)
root.mainloop()
Answer: Yes, as you observed, the issue is because you are always changing the
`linenumbers` to the linenumber of the latest tab, so for old tabs , even if
the `_on_change()` is called, it would call redraw only on the new line
number, not on the old ones.
I believe the correct way to go forward for your application would be to have
another level of abstraction, where `Tab` is a complete object by itself, and
each tab should be a different object and should keep store the
linenumber/text in itself.
Example -
import tkinter as tk
import tkinter.ttk as ttk
class TextLineNumbers(tk.Canvas):
def __init__(self, *args, **kwargs):
tk.Canvas.__init__(self, *args, **kwargs)
self.textwidget = None
def attach(self, text_widget):
self.textwidget = text_widget
def redraw(self, *args):
'''redraw line numbers'''
self.delete("all")
i = self.textwidget.index("@0,0")
while True:
dline= self.textwidget.dlineinfo(i)
if dline is None: break
y = dline[1]
linenum = str(i).split(".")[0]
self.create_text(5,y,anchor="nw", text=linenum, font=("Courier", 9))
i = self.textwidget.index("%s+1line" % i)
class CustomText(tk.Text):
def __init__(self, *args, **kwargs):
tk.Text.__init__(self, *args, **kwargs)
self.tk.eval('''
proc widget_proxy {widget widget_command args} {
# call the real tk widget command with the real args
set result [uplevel [linsert $args 0 $widget_command]]
# generate the event for certain types of commands
if {([lindex $args 0] in {insert replace delete}) ||
([lrange $args 0 2] == {mark set insert}) ||
([lrange $args 0 1] == {xview moveto}) ||
([lrange $args 0 1] == {xview scroll}) ||
([lrange $args 0 1] == {yview moveto}) ||
([lrange $args 0 1] == {yview scroll})} {
event generate $widget <<Change>> -when tail
}
# return the result from the real widget command
return $result
}
''')
self.tk.eval('''
rename {widget} _{widget}
interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
'''.format(widget=str(self)))
self.comment = False
class Tab:
def __init__(self, parent, filename):
self.parent = parent
self.filename = filename
self.tab1 = ttk.Frame(parent)
self.text = CustomText(self.tab1, bd=0, font=("Courier", 9))
self.vsb = tk.Scrollbar(self.tab1, orient=tk.VERTICAL)
self.text.configure(yscrollcommand=self.vsb.set)
self.vsb.configure(command=self.text.yview)
self.linenumbers = TextLineNumbers(self.tab1, width=55)
self.linenumbers.attach(self.text)
self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
self.linenumbers.pack(side="left", fill="y")
self.text.pack(side="right", fill="both", expand=True)
parent.add(self.tab1, text=filename)
self.text.bind("<<Change>>", self._on_change)
self.text.bind("<Configure>", self._on_change)
def _on_change(self, event):
self.linenumbers.redraw()
class Window(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.fileName = "Untitled Document"
self.content = ""
self.previousContent = ""
self.language = "Python"
self.row = "0"
self.column = "0"
self.startCol = 0
self.notebook = ttk.Notebook(self)
self.tabs = []
self.menubar()
self.createtext()
def createtext(self):
self.notebook.pack(fill=tk.BOTH, expand=True)
t = Tab(self.notebook, self.fileName)
self.tabs.append(t)
def addtab(self):
t = Tab(self.notebook, self.fileName)
self.tabs.append(t)
def removetab(self):
numberOfTabs = self.notebook.index("end")
if numberOfTabs > 1:
tabIndex = self.notebook.index(self.notebook.select())
self.notebook.forget(tabIndex)
del self.tabs[tabIndex]
def menubar(self):
self.menu = tk.Menu(self)
self.master.config(menu=self.menu)
self.fileMenu = tk.Menu(self.menu, font=("Courier", 9))
self.fileMenu.add_command(label="New Window", command=self.addtab)
self.fileMenu.add_command(label="Close Window", command=self.removetab)
self.menu.add_cascade(label="File", menu=self.fileMenu)
if __name__ == "__main__":
root = tk.Tk()
root.title("Window")
root.geometry("1024x600")
window = Window(root).pack(side="top", fill="both", expand=True)
root.mainloop()
I created a new class `Tab` and copied code from previous methods like
`createtext` into it, and now when creating a new tab, we just need to
instantiate object of `Tab` class.
* * *
Partially working code , for your case -
import tkinter as tk
import tkinter.filedialog
import traceback
import tkinter.ttk as ttk
from pygments import lex
from pygments.lexers import PythonLexer
import sys
import os
class TextLineNumbers(tk.Canvas):
def __init__(self, *args, **kwargs):
tk.Canvas.__init__(self, *args, **kwargs)
self.textwidget = None
def attach(self, text_widget):
self.textwidget = text_widget
def redraw(self, *args):
'''redraw line numbers'''
self.delete("all")
i = self.textwidget.index("@0,0")
while True:
dline= self.textwidget.dlineinfo(i)
if dline is None: break
y = dline[1]
linenum = str(i).split(".")[0]
self.create_text(5,y,anchor="nw", text=linenum, font=("Courier", 9))
i = self.textwidget.index("%s+1line" % i)
class CustomText(tk.Text):
def __init__(self, *args, **kwargs):
tk.Text.__init__(self, *args, **kwargs)
self.tk.eval('''
proc widget_proxy {widget widget_command args} {
# call the real tk widget command with the real args
set result [uplevel [linsert $args 0 $widget_command]]
# generate the event for certain types of commands
if {([lindex $args 0] in {insert replace delete}) ||
([lrange $args 0 2] == {mark set insert}) ||
([lrange $args 0 1] == {xview moveto}) ||
([lrange $args 0 1] == {xview scroll}) ||
([lrange $args 0 1] == {yview moveto}) ||
([lrange $args 0 1] == {yview scroll})} {
event generate $widget <<Change>> -when tail
}
# return the result from the real widget command
return $result
}
''')
self.tk.eval('''
rename {widget} _{widget}
interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
'''.format(widget=str(self)))
self.comment = False
class Tab:
def __init__(self, parent, filename, parentwindow):
self.fileName = "Untitled Document"
self.content = ""
self.previousContent = ""
self.parentwindow = parentwindow
self.language = "Python"
self.parent = parent
self.filename = filename
self.tab1 = ttk.Frame(parent)
self.text = CustomText(self.tab1, bd=0, font=("Courier", 9))
self.vsb = tk.Scrollbar(self.tab1, orient=tk.VERTICAL)
self.text.configure(yscrollcommand=self.vsb.set)
self.vsb.configure(command=self.text.yview)
self.linenumbers = TextLineNumbers(self.tab1, width=55)
self.linenumbers.attach(self.text)
self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
self.linenumbers.pack(side="left", fill="y")
self.text.pack(side="right", fill="both", expand=True)
parent.add(self.tab1, text=filename)
self.bottomLabel()
self.text.bind("<<Change>>", self._on_change)
self.text.bind("<Configure>", self._on_change)
self.text.bind("<KeyRelease>", self.keypress)
self.text.bind("<Button-1>", self.keypress)
def deafultHighlight(self, argument):
self.content = self.text.get("1.0", tk.END)
self.lines = self.content.split("\n")
if (self.previousContent != self.content):
self.text.mark_set("range_start", self.row + ".0")
data = self.text.get(self.row + ".0", self.row + "." + str(len(self.lines[int(self.row) - 1])))
for token, content in lex(data, PythonLexer()):
self.text.mark_set("range_end", "range_start + %dc" % len(content))
self.text.tag_add(str(token), "range_start", "range_end")
self.text.mark_set("range_start", "range_end")
self.previousContent = self.text.get("1.0", tk.END)
def highlight(self, argument):
self.content = self.text.get("1.0", tk.END)
if (self.previousContent != self.content):
self.text.mark_set("range_start", "1.0")
data = self.text.get("1.0", self.text.index(tk.INSERT))
for token, content in lex(data, PythonLexer()):
self.text.mark_set("range_end", "range_start + %dc" % len(content))
self.text.tag_add(str(token), "range_start", "range_end")
self.text.mark_set("range_start", "range_end")
self.previousContent = self.text.get("1.0", tk.END)
def keypress(self, argument):
self.updateBottomLabel()
self.deafultHighlight("argument")
def _on_change(self, event):
self.linenumbers.redraw()
def bottomLabel(self):
self.positionAndLanguage = tk.Label(self.parentwindow, text=" Ln: 1, Col: 0, Lang: Plain", anchor=tk.W, bg="#E7E7E7", font=("Courier New", 8))
self.positionAndLanguage.pack(fill=tk.X, side=tk.BOTTOM)
def updateBottomLabel(self):
self.row = self.text.index(tk.INSERT).split(".")[0]
self.column = self.text.index(tk.INSERT).split(".")[1]
self.positionAndLanguage["text"] = " Ln: {0}, Col: {1}, Lang: {2}".format(self.row, self.column, self.language)
class Arshi(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.fileName = "Untitled Document"
self.content = ""
self.previousContent = ""
self.language = "Python"
self.row = "0"
self.column = "0"
self.startCol = 0
self.tabs = []
self.notebook = ttk.Notebook(self)
self.menubar()
#self.bottomLabel()
self.createtext()
def deafultHighlight(self, argument):
self.content = self.text.get("1.0", tk.END)
self.lines = self.content.split("\n")
if (self.previousContent != self.content):
self.text.mark_set("range_start", self.row + ".0")
data = self.text.get(self.row + ".0", self.row + "." + str(len(self.lines[int(self.row) - 1])))
for token, content in lex(data, PythonLexer()):
self.text.mark_set("range_end", "range_start + %dc" % len(content))
self.text.tag_add(str(token), "range_start", "range_end")
self.text.mark_set("range_start", "range_end")
self.previousContent = self.text.get("1.0", tk.END)
def highlight(self, argument):
self.content = self.text.get("1.0", tk.END)
if (self.previousContent != self.content):
self.text.mark_set("range_start", "1.0")
data = self.text.get("1.0", self.text.index(tk.INSERT))
for token, content in lex(data, PythonLexer()):
self.text.mark_set("range_end", "range_start + %dc" % len(content))
self.text.tag_add(str(token), "range_start", "range_end")
self.text.mark_set("range_start", "range_end")
self.previousContent = self.text.get("1.0", tk.END)
def keypress(self, argument):
self.updateBottomLabel()
self.deafultHighlight("argument")
def configureTags(self, text):
text.tag_configure("Token.Keyword", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Constant", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Declaration", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Namespace", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Pseudo", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Reserved", foreground="#CC7A00")
text.tag_configure("Token.Keyword.Type", foreground="#CC7A00")
text.tag_configure("Token.Name.Class", foreground="#003D99")
text.tag_configure("Token.Name.Exception", foreground="#003D99")
text.tag_configure("Token.Name.Function", foreground="#003D99")
text.tag_configure("Token.Operator.Word", foreground="#CC7A00")
text.tag_configure("Token.Comment", foreground="#B80000")
text.tag_configure("Token.Literal.String", foreground="#248F24")
def createtext(self):
self.notebook.pack(fill=tk.BOTH, expand=True)
t = Tab(self.notebook, self.fileName, self)
self.tabs.append(t)
def addtab(self):
t = Tab(self.notebook, self.fileName, self)
self.tabs.append(t)
def removetab(self):
numberOfTabs = self.notebook.index("end")
if numberOfTabs > 1:
tabIndex = self.notebook.index(self.notebook.select())
self.notebook.forget(tabIndex)
def run(self):
pass
def menubar(self):
self.menu = tk.Menu(self)
self.master.config(menu=self.menu)
self.fileMenu = tk.Menu(self.menu, font=("Courier", 9))
self.fileMenu.add_command(label="New Ctrl+N", command=self.newFile)
self.fileMenu.add_command(label="Open Ctrl+O", command=self.openFile)
self.fileMenu.add_command(label="Save Ctrl+S", command=self.saveFile)
self.fileMenu.add_command(label="Save As Ctrl+Shift+S", command=self.saveAsFile)
self.fileMenu.add_separator()
self.fileMenu.add_command(label="New Window", command=self.addtab)
self.fileMenu.add_command(label="Close Window", command=self.removetab)
self.fileMenu.add_separator()
self.fileMenu.add_command(label="Exit Alt+F4", command=self.close)
self.menu.add_cascade(label="File", menu=self.fileMenu)
self.runMenu = tk.Menu(self.menu, font=("Courier", 9))
self.runMenu.add_command(label="Run", command=self.run)
self.menu.add_cascade(label="Run", menu=self.runMenu)
def bottomLabel(self):
self.positionAndLanguage = tk.Label(self, text=" Ln: 1, Col: 0, Lang: Plain", anchor=tk.W, bg="#E7E7E7", font=("Courier New", 8))
self.positionAndLanguage.pack(fill=tk.X, side=tk.BOTTOM)
def updateBottomLabel(self):
self.row = self.text.index(tk.INSERT).split(".")[0]
self.column = self.text.index(tk.INSERT).split(".")[1]
self.positionAndLanguage["text"] = " Ln: {0}, Col: {1}, Lang: {2}".format(self.row, self.column, self.language)
def newFile(self):
self.addtab()
def openFile(self):
try:
self.fileName = tk.filedialog.askopenfilename() #Asks user to open file
with open(self.fileName, 'r') as file:
self.content = file.read() #Reads content typed
self.text.delete(0.0, tk.END)
self.text.insert(0.0, self.content)
self.highlight(self)
except IOError as e:
print("Error reading file.")
except:
print("Unexpected error occured.")
def deleteContent(self, file):
file.seek(0)
file.truncate()
def saveFile(self):
self.content = self.text.get(0.0, tk.END)
try:
with open(self.fileName, 'w') as file:
self.deleteContent(file)
file.write(self.content)
except IOError as e:
print("Error reading file.")
except:
print("Unexpected error occured.")
def saveAsFile(self):
self.content = self.text.get(0.0, tk.END)
try:
self.fileName = tk.filedialog.asksaveasfilename()
if self.fileName != None:
with open(self.fileName, 'w') as file:
file.write(self.content)
except IOError as e:
print("Error reading file.")
except:
print("Unexcepted error occured.")
def close(self):
try:
os._exit(0)
except:
print(sys.exc_info()[0])
def _on_change(self, event):
self.linenumbers.redraw()
if __name__ == "__main__":
root = tk.Tk()
root.title("Arshi")
root.geometry("1024x600")
window = Arshi(root).pack(side="top", fill="both", expand=True)
root.mainloop()
Currently, `open()` would not work , and the bottom labels come up duplicated
for each tab, you should think about how to work those out. The bottom label
one can move out of `Tab` class back to `Arshi` , and then have some
communication between `Tab` class and `Arshi` when tabs are changed to change
the bottom label accordingly.
Also, open should open a new tab, so you can easily work on that. I would also
advice you to understand the complete code and then use it in your code ,
rather than just copy-paste.
|
cross-platform method for determining file owner in Python
Question: I need to find the owner of files in a script running on Windows, Linux and
Mac. `os.stat` returns the owner id, but on windows I can't use `getpwuid` to
find the actual name of the owner. I need the name as a string.
Answer: It seems like you won't find a silver bullet (cross platform). For windows you
can use the win32 module like shown
[here](http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-
file.html)
import win32api
import win32con
import win32security
FILENAME = "temp.txt"
open (FILENAME, "w").close ()
print "I am", win32api.GetUserNameEx (win32con.NameSamCompatible)
sd = win32security.GetFileSecurity (FILENAME, win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner ()
name, domain, type = win32security.LookupAccountSid (None, owner_sid)
print "File owned by %s\\%s" % (domain, name)
|
Python 3.4: href with XPATH
Question: Using `lxml` and `requests` I am passing a `XPATH` to retrieve `href`
attributes of `a` tags. Every time I use the simple code below I get an
`AttributeError` as exemplified below.
import requests
from lxml import html
import csv
url = 'https://biz.yahoo.com/p/sum_conameu.html'
resp = requests.get(url)
tree = html.fromstring(resp.text)
update_tick = [td.text_content()
for td in tree.xpath('''//tr[starts-with(normalize-space(.), "Industry")]
/following-sibling::tr[position()>0]
/td/a/@href''')]
print(update_tick)
AttributeError: 'str' object has no attribute 'text_content'
Answer: Passing XPath attribute selector (`.../@href`) to `xpath()` method make it
return string values of the matched attributes. No need to call
`text_content()` in this case :
update_tick = [td
for td in tree.xpath('''//tr[starts-with(normalize-space(.), "Industry")]
/following-sibling::tr[position()>0]
/td/a/@href''')]
|
How to trace back the cause of an exception raised within a function?
Question: (This is a follow-up question to the post [Python try/except: Showing the
cause of the error after displaying my
variables](http://stackoverflow.com/questions/4560288/python-try-except-
showing-the-cause-of-the-error-after-displaying-my-variables).)
I have the following `script.py`:
import traceback
def process_string(s):
"""
INPUT
-----
s: string
Must be convertable to a float
OUTPUT
------
x: float
"""
# validate that s is convertable to a float
try:
x = float(s)
return x
except ValueError:
print
traceback.print_exc()
if __name__ == '__main__':
a = process_string('0.25')
b = process_string('t01')
c = process_string('201')
Upon execution of `script.py`, the following message is printed in the
terminal window:
Traceback (most recent call last):
File "/home/user/Desktop/script.py", line 20, in process_string
x = float(s)
ValueError: could not convert string to float: t01
May I ask if there is a way for `traceback.print_exc()` to also print in the
terminal window which instruction inside the if-main threw the exception which
was caught by the try-except clause?
Answer: What about this?
import traceback
def process_string(s):
"""
INPUT
-----
s: string
Must be convertible to a float
OUTPUT
------
x: float
"""
return float(s)
if __name__ == '__main__':
try:
a = process_string('0.25')
b = process_string('t01')
c = process_string('201')
except ValueError:
print
traceback.print_exc()
|
imdbpy rating data missing
Question:
i have a question about the [imdbpy](http://imdbpy.sourceforge.net/index.html)
module for python, for some reason i can't retrieve some data about tv shows
even though they exist on the imdb.com website.
for example if i use this code:
from imdb import IMDb
i = IMDb()
s = i.search_movie('killjoys')
m = i.get_movie(s[0].movieID)
print m.get('rating')
the result is **None** even though on the [imdb.com](http://imdb.com) it's
available so what should i so here? and thanks for the help :)
Answer: Consider two things:
1. the Movie objects in the result list from a query contains only limited data (the ones you can see from a search on the web).
2. for a series, the "combined" page doesn't show the rating.
So, in your example, the first result would refer to imdbID 3952222. You can
update the (main) information using:
i.update(m)
but again this would only add main information, by default (the ones from the
<http://www.imdb.com/title/tt3952222/combined> page)
So, you need to also parse the "vote details" page with:
i.update(m, ['main', 'vote details'])
(or just 'vote details' if you don't need to fetch and parse the main
details).
|
Regex python wont work as I want it
Question: I'm trying to filter street names and get the parts that I want. The names
come in several formats. Here are some examples and what I want from them.
Car Cycle 5 B Ap 1233 < what I have
Car Cycle 5 B < what I want
Potato street 13 1 AB < what I have
Potato street 13 < what I want
Chrome Safari 41 Ap 765 < what I have
Chrome Safari 41 < what I want
Highstreet 53 Ap 2632/BH < what I have
Highstreet 53 < what I want
Something street 91/Daniel < what I have
Something street 91 < what I want
Usually what I want is the street name (1-4 names) followed by the street
number if there is one and then the street letter (1 letter) if there is one.
I just can't get it to work right.
Here is my code (I know, it sucks):
import re
def address_regex(address):
regex1 = re.compile("(\w+ ){1,4}(\d{1,4} ){1}(\w{1} )")
regex2 = re.compile("(\w+ ){1,4}(\d{1,4} ){1}")
regex3 = re.compile("(\w+ ){1,4}(\d){1,4}")
regex4 = re.compile("(\w+ ){1,4}(\w+)")
s1 = regex1.search(text)
s2 = regex2.search(text)
s3 = regex3.search(text)
s4 = regex4.search(text)
regex_address = ""
if s1 != None:
regex_address = s1.group()
elif s2 != None:
regex_address = s2.group()
elif s3 != None:
regex_address = s3.group()
elif s4 != None:
regex_address = s4.group()
else:
regex_address = address
return regex_address
I'm using Python 3.4
Answer: I'm going to go out on a limb here and assume in your last example you
actually want to catch the number 91, because it makes no sense not to.
Here's a solution which catches all your examples (and your last, but
including the 91):
^([\p{L} ]+ \d{1,4}(?: ?[A-Za-z])?\b)
* `^` Start match at beginning of string
* `[\p{L} ]+` Character class of space or unicode character belonging to the "letter" category, 1-infinity times
* `\d{1,4}` Number, 1-4 times
* `(?: ?[A-Za-z])?` Non-capture group of optional space and a single letter, 0-1 times
Capture group 1 is the entire address. I didn't quite understand the logic
behind your grouping, but feel free to group it however you prefer.
# [See demo](http://rubular.com/r/fENTAwsBKl)
|
Why can't I crawl this link in Python?
Question: I am trying to crawl the contents of a webpage but I don't understand why I am
getting this error : `http.client.IncompleteRead: IncompleteRead(2268 bytes
read, 612 more expected)`
**here is th link I am trying to crawl :**
[www.rc2.vd.ch](http://www.rc2.vd.ch/registres/hrcintapp-
pub/companySearch.action?lang=FR&init=false&advancedMode=false&printMode=false&ofpCriteria=N&actualDate=18.08.2015&rowMin=0&rowMax=0&listSize=0&go=none&showHeader=false&companyName=&companyNameSearchType=CONTAIN&companyOfsUid=&companyOfrcId13Part1=&companyOfrcId13Part2=&companyOfrcId13Part3=&limitResultCompanyActive=ACTIVE&searchRows=51&resultFormat=STD_COMP_NAME&display=Rechercher#result)
**Here is the Python code I am using to crawl :**
import requests
from bs4 import BeautifulSoup
def spider_list():
url = 'http://www.rc2.vd.ch/registres/hrcintapp-pub/companySearch.action?lang=FR&init=false&advancedMode=false&printMode=false&ofpCriteria=N&actualDate=18.08.2015&rowMin=0&rowMax=0&listSize=0&go=none&showHeader=false&companyName=&companyNameSearchType=CONTAIN&companyOfsUid=&companyOfrcId13Part1=&companyOfrcId13Part2=&companyOfrcId13Part3=&limitResultCompanyActive=ACTIVE&searchRows=51&resultFormat=STD_COMP_NAME&display=Rechercher#result'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')
for link in soup.findAll('a', {'class': 'hoverable'}):
print(link)
spider_list()
I tried with an other website link and it works fine, but why can't I crawl
this one?
If it's not possible to do it with this code then how can I do it ?
\------------ EDIT ------------
**here is the full error message :**
Traceback (most recent call last):
File "C:/Users/Nuriddin/PycharmProjects/project/a.py", line 19, in <module>
spider_list()
File "C:/Users/Nuriddin/PycharmProjects/project/a.py", line 12, in spider_list
source_code = requests.get(url)
File "C:\Python34\lib\site-packages\requests\api.py", line 69, in get
return request('get', url, params=params, **kwargs)
File "C:\Python34\lib\site-packages\requests\api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 465, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 605, in send
r.content
File "C:\Python34\lib\site-packages\requests\models.py", line 750, in content
self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
File "C:\Python34\lib\site-packages\requests\models.py", line 673, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "C:\Python34\lib\site-packages\requests\packages\urllib3\response.py", line 303, in stream
for line in self.read_chunked(amt, decode_content=decode_content):
File "C:\Python34\lib\site-packages\requests\packages\urllib3\response.py", line 450, in read_chunked
chunk = self._handle_chunk(amt)
File "C:\Python34\lib\site-packages\requests\packages\urllib3\response.py", line 420, in _handle_chunk
returned_chunk = self._fp._safe_read(self.chunk_left)
File "C:\Python34\lib\http\client.py", line 664, in _safe_read
raise IncompleteRead(b''.join(s), amt)
http.client.IncompleteRead: IncompleteRead(4485 bytes read, 628 more expected)
Answer: There _might_ be a problem with your editor.
I am getting **correct results** in python 3 with your code in `IDLE`.
Image is attached below for reference-
[](http://i.stack.imgur.com/Xzqvw.png)
The only thing that I can think of is to somehow bypass the error:
import requests
from bs4 import BeautifulSoup
def spider_list():
url = 'http://www.rc2.vd.ch/registres/hrcintapp-pub/companySearch.action?lang=FR&init=false&advancedMode=false&printMode=false&ofpCriteria=N&actualDate=18.08.2015&rowMin=0&rowMax=0&listSize=0&go=none&showHeader=false&companyName=&companyNameSearchType=CONTAIN&companyOfsUid=&companyOfrcId13Part1=&companyOfrcId13Part2=&companyOfrcId13Part3=&limitResultCompanyActive=ACTIVE&searchRows=51&resultFormat=STD_COMP_NAME&display=Rechercher#result'
try:
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')
for link in soup.findAll('a', {'class': 'hoverable'}):
print(link)
except:
pass
#I am passing but you do whatever you want to do in case of error
spider_list()
Let me know if it helps.
|
Python: how to create a class name on the fly
Question: I am looking for a way to "identify" the class name on the fly based on an
incoming parameter and create its object. The code which I attempted gives
error "TypeError: 'str' object is not callable". Any suggestions on how to
achieve this?
class interfaceMsg:
def __init__(self):
#Do some initializations
def updateDB(self, cell_index, xml_msg):
#Do something general
class interfaceMsg_myMsg(interfaceMsg):
def __init__(self):
interfaceMsg.__init__(self)
#Do some specific initializations
class interfaceMsg_yourMsg(interfaceMsg):
def __init__(self):
interfaceMsg.__init__(self)
#Do some special initializations
def updateDB(self, cell_index, xml_msg):
#Do something special
##and so on several derived classes
def doUpdateDB(cell_index, xml_msg):
# I basically want to create an object on the fly and call its updateDB function
#Create the class name correspoding to this message
class_name = "interfaceMsg_" + xml_msg.attrib["showname"]
#class_name becomes interfaceMsg_myMsg or interfaceMsg_yourMsg or interfaceMsg_xyzMsg
#This gives TypeError: 'str' object is not callable
obj = class_name()
obj.updateDB(cell_index, xml_msg)
Thanks
Answer: what i do (for example in an engine of mine
[Contemplate](https://github.com/foo123/Contemplate)), is this:
1. have a set of classes available in subfolder
2. dynamicaly import the appropriate class file
3. get an instance of the class
All these assuming that the class is dynamic but from a specific set of
available classes, sample code follows:
sample available class:
def __getClass__():
class AClass:
# constructor
def __init__(self):
pass
return AClass
# allow to 'import *' from this file as a module
__all__ = ['__getClass__']
sample dynamic class loading:
def include( filename, classname, doReload=False ):
# http://www.php2python.com/wiki/function.include/
# http://docs.python.org/dev/3.0/whatsnew/3.0.html
# http://stackoverflow.com/questions/4821104/python-dynamic-instantiation-from-string-name-of-a-class-in-dynamically-imported
#_locals_ = {'Contemplate': Contemplate}
#_globals_ = {'Contemplate': Contemplate}
#if 'execfile' in globals():
# # Python 2.x
# execfile(filename, _globals_, _locals_)
# return _locals_[classname]
#else:
# # Python 3.x
# exec(Contemplate.read(filename), _globals_, _locals_)
# return _locals_[classname]
# http://docs.python.org/2/library/imp.html
# http://docs.python.org/2/library/functions.html#__import__
# http://docs.python.org/3/library/functions.html#__import__
# http://stackoverflow.com/questions/301134/dynamic-module-import-in-python
# http://stackoverflow.com/questions/11108628/python-dynamic-from-import
# also: http://code.activestate.com/recipes/473888-lazy-module-imports/
# using import instead of execfile, usually takes advantage of Python cached compiled code
global _G
getClass = None
directory = _G.cacheDir
# add the dynamic import path to sys
os.sys.path.append(directory)
currentcwd = os.getcwd()
os.chdir(directory) # change working directory so we know import will work
if os.path.exists(filename):
modname = filename[:-3] # remove .py extension
mod = __import__(modname)
if doReload: reload(mod) # Might be out of date
# a trick in-order to pass the Contemplate super-class in a cross-module way
getClass = getattr( mod, '__getClass__' )
# restore current dir
os.chdir(currentcwd)
# remove the dynamic import path from sys
del os.sys.path[-1]
# return the Class if found
if getClass: return getClass()
return None
This scheme enables these things:
1. dynamic file and module/class loading, where classname/file is dynamic but class name might not correspond to filename (have a generic `__getClass__` function for this in each module/class)
2. the dynamic class file can be generated (as source code) on the fly or be pre-cached and so on... No need to (re-)generate if already available.
3. Set of dynamic classes is specific and not ad-hoc, although it can be dynamicaly changed and/or enlarged at run-time if needed
|
Combine multidimensional array by group python
Question:
[['test', '172.18.74.146', '13:05:43.834', '2015_08_07'],
['test', '172.18.74.148', '12:27:39.016', '2015_08_07'],
['blah', '172.18.74.149', '11:18:33.846', '2015_08_12'],
['blah', '172.18.74.146', '12:27:38.985', '2015_08_12']]
I would like the final result to be grouped by date and the project name
[["test", "172.18.74.146, 172.18.74.148", "13:05:43.834, 12:27:39.016" ,
"2015_08_07"], etc..]
The names will not be the same for the given date.
How can I do this? I tried using groupby.
for g, data in groupby(sorted(my_list, key=itemgetter(0)), itemgetter(0)):
print(g)
for elt in data:
print(' ', elt)
but it didnt give me what I wanted.
Answer: You need to pass two keys to sorted, the name and date, then use `str.join` to
concat the ip's and times
from itertools import groupby
from operator import itemgetter
out = []
for _, v in groupby(sorted(data, key=itemgetter(0, 3)),key=itemgetter(0,3)):
v = list(v)
ips = ", ".join([sub[1] for sub in v])
tmes = ", ".join([sub[2] for sub in v])
out.append([v[0][0], ips, tmes, v[0][-1]])
print(out)
['blah', '172.18.74.149, 172.18.74.146', '11:18:33.846, 12:27:38.985', '2015_08_12'],
['test', '172.18.74.146, 172.18.74.148', '13:05:43.834, 12:27:39.016', '2015_08_07']]
Or without sorting using dict to group:
d = {}
for nm, ip, tm, dte in data:
key = nm, dte
if key in d:
v = d[key]
v[1] += ", {}".format(ip)
v[2] += ", {}".format(dte)
else:
d[key] = [nm, ip, tm, dte]
print(list(d.values()))
Output:
[['test', '172.18.74.146, 172.18.74.148', '13:05:43.834, 2015_08_07', '2015_08_07'],
['blah', '172.18.74.149, 172.18.74.146', '11:18:33.846, 2015_08_12', '2015_08_12']]
|
Using the file descriptor returned from C extension to read the files in python
Question: Bare with me, am new to python.
When I try reading a file in python, it blocks other processes from editing
that file. Even though the file is opened in read mode.
I couldn't find and option which would enable me to achieve this. So, what am
trying to do is, send the file name to a C extension and open the file there
with required option and return the file descriptor from there. And, use this
descriptor to get the file object and read the file.
The code I have tried is:
The C code fileread.h
#include <python.h>
static PyObject* fileread(PyObject *self, PyObject *args)
{
char* filename = NULL;
int fd = 0;
if (!PyArg_ParseTuple(args, "s", &filename)) {
return NULL;
}
fd = _sopen(filename, 0x0000, 0x40, 0x0100);
// _sopen(filename,_O_RDONLY, _SH_DENYNO, _S_IREAD);
return Py_BuildValue("i", fd);
}
static PyMethodDef fileread_funcs[] = {
{ "fileread", (PyCFunction)fileread,
METH_VARARGS, "read file in blocks" },
{ NULL, NULL, 0, NULL }
};
void initfileread(void)
{
Py_InitModule3("fileread", fileread_funcs,
"Extension for file read!");
}
And, the fileread.py is:
import os
import fileread
def ReadDataBlockByBlock(dirPath, fileName):
path = os.path.join(dirPath, fileName)
if os.access(path, os.R_OK):
fd = PyObjectAsFileDescriptor(fileread.fileread(path))
fp = os.fdopen(fd,'r') #Is Error: Expects integer
for block in read_in_chunks(fp):
print block
print '*' * 80
os.close(fd)
def read_in_chunks(file_object, chunk_size=1096):
"""Function (generator) to read a file piece by piece.
Default chunk size: 1k."""
while True:
data = os.read(file_object, chunk_size)
if not data:
break
yield data
When I try to do fdopen() here, it throws an error. What am I doing wrong?
This may not be the right approach, am new to python. Any better way of
achieving this is also very much appreciated
Thanks, Harsh
Answer: By default, Python does not lock files, but see the `fcntl` module if you need
to do so.
But other processes which do lock files may not be able to acquire the lock if
a Python process has a file open. (This is heavily OS-dependent behavior.)
To prove that it is not Python that is keeping the other process from
accessing the file, open two different terminal programs or cmd windows, fire
up Python in both of them, and open the file for reading in each one. This
should work, and will show that it's the other process complaining that it
cannot open (and lock) a file that your Python process has open, and not
Python itself acquiring a lock on the file.
In general, the best way to deal with this is to open the file, do your file
operations, and close it again right away. Unfortunately, though, if your
editor does not let other processes open files, that is a problem that you are
going to have to deal with. You should check your editor configuration
settings, to see if it has one for exclusive access that you can turn off, and
if not, you should consider a different editor.
|
Making a list based off of list of months in Python
Question: I am using Python to make lists. Should be easy! I don't know why I'm
struggling so much with this.
I have some data that I am counting up by date. There is a date column like
this:
Created on
5/1/2015
5/1/2015
6/1/2015
6/1/2015
7/1/2015
8/1/2015
8/1/2015
8/1/2015
In this case, there would be 2 Units created in May, 2 Units in June, 1 Unit
in July, and 3 Units in August.
I want to reflect that in a list that starts in April ([April counts, May
counts, June counts, etc...]):
NumberofUnits = [0, 2, 3, 1, 3, 0, 0, 0, 0, 0, 0, 0]
I have a nice list of months
monthnumbers
Out[69]: [8, 5, 6, 7]
I also have a list with the `unitcounts = [2, 3, 1, 3]` I got this using
value_counts.
So it's a matter of making a list of zeroes and replacing parts with the
unitcount list, right?
For some reason all of my tries are either not making a list or making a list
with one zero in it.
NumberofUnits = [0]*12
for i in range(0,len(monthnumbers)):
if **monthnumbers[i] == (i+4):** **This part is wrong**
NumberofUnits.append(unitcounts[i])
s = slice(0,i+1)
I also tried
NumberofUnits = []
for i in range(0, 12):
if len(NumberofUnits) > i:
unitcounts[i:]+unitcounts[:i]
NumberofUnits.append(unitcounts[i])
s = slice(0,i+1)
else:
unitcounts.append(0)
But this doesn't account for the fact that in this round my data starts with
May, so I need a zero in the first slot.
Answer: You can count entries using `collections.counter`
from collections import Counter
lines = ['5/1/2015', '5/1/2015', ..., '8/1/2015']
month_numbers = [int(line.split("/")[0]) for line in lines]
cnt = Counter(month_numbers)
If you already have counts you can replace above with
from collections import defaultdict
cnt = defaultdict(int, zip(monthnumbers, unitcounts))
and simply map to entries with (month_number - offset) mod 12:
[x[1] for x in sorted([((i - offset) % 12, cnt[i]) for i in range(1, 13)])]
|
Python set environment variables for docker-machine on Mac OS X
Question: As I'm continuing to work in docker-machine and Django, I'm trying to make a
setup script for my project that auto-detects platform and decides how to set
up Docker and the required containers. Auto-detection works fine. One thing I
can't figure out is how to automatically set the environment variables needed
for `docker-machine` to work on Mac OS X. Currently, the script will just tell
the user to manually set the environment variable using the command
eval $(docker-machine env dev)
where `dev` is the name of the VM. This prompt happens after initial setup is
successfully completed. The user is told to do this because the following
subprocess call does not actually set the environment variables:
subprocess.call('eval $(docker-machine env dev)', shell=True)
If an error occurs during creating the VM because the VM already exists, then
I use subprocess to see if Docker is already installed:
check_docker = subprocess.check_call('docker run hello-world', shell=True)
If this call is successful, then the script tells the user that Docker was
already installed and then prompts the user to manually set the environment
variables to be able to start the containers needed for the Django server to
run. I had originally thought that the script behaved correctly in this
scenario, but it turns out that it only appeared that way because I had
already set the environment variables manually. Of course, I see now that the
`docker run` command needs the environment variables to be set in order to
work, and since the environment variables never get set in the script, the
`docker run` test doesn't work. So, how am I supposed to correctly set the
environment variables from Python? It seems like using subprocess is resulting
in the wrong environment getting these variables set. If I do something like
subprocess.call('setdockerenv.sh', shell=True)
where `setdockerenv.sh` has the correct `eval` command, then I run into the
same problem, which I'm guessing is rooted in using subprocess. Would `os`
have something to do this properly where `subprocess` can't? It's important
that I do this in the Python script, or else having the user manually set the
environment variables and then manually test to see if docker is installed
defeats the purpose of having the script.
Answer: You cannot use `subprocess` to change the environment, since any changes it
makes are local to that process. Instead, (as you found) you can change your
_current_ environment via `os.environ`, and that is inherited by any other
processes you subsequently create.
|
Time Zones in python for program
Question: This program is used to find the current time of location of a countries
time and then get the time of a location of your choosing.I need to know how
to get the time from other countries such as China or the ones in the code.
#Eric's Amazing Trip around the world in 80 days time converter#
import time
print("Welcome to Eric's Amazing Trip around the world in 80 days time converter")
print("This program helps the user change the time on the watch as they travel")
cur=input("First enter the current country")
#Displays the country of your choosing time#
print("The current time in " + cur)
#Displays the current time in the country#
print("Current time is " + time.asctime())
print()
nex=input("Next the country your travelng to")
#This display the time of whichever country you choose#
if cur=="Italy" or "italy":
print("The current time in " + nex + "is")
elif cur=="Egypt" or "Egypt":
print("The current time in " + nex + "is")
elif cur=="Paris" or "Paris ":
print("The current time in " + nex + "is")
elif cur=="China" or "china":
print("The current time in " + nex + "is")
elif cur=="India" or "india":
print("The current time in" + nex + "is")
elif cur=="Singapore" or "Singaspore":
print("The current time in " + nex + "is")
Answer: In general, there could be more than one timezone in a country e.g., there are
21 timezones in Russia:
>>> import pytz
>>> pprint(pytz.country_timezones['ru'])
['Europe/Kaliningrad',
'Europe/Moscow',
'Europe/Simferopol',
'Europe/Volgograd',
'Europe/Samara',
'Asia/Yekaterinburg',
'Asia/Omsk',
'Asia/Novosibirsk',
'Asia/Novokuznetsk',
'Asia/Krasnoyarsk',
'Asia/Irkutsk',
'Asia/Chita',
'Asia/Yakutsk',
'Asia/Khandyga',
'Asia/Vladivostok',
'Asia/Sakhalin',
'Asia/Ust-Nera',
'Asia/Magadan',
'Asia/Srednekolymsk',
'Asia/Kamchatka',
'Asia/Anadyr']
Different timezones may have different utc offsets.
Though all countries except China have a single timezone in your example:
>>> country_codes = {country: code for code, country in pytz.country_names.items()}
>>> {c: pytz.country_timezones[country_codes[c]]
... for c in "Italy Egypt China India Singapore".split()}
{'China': ['Asia/Shanghai', 'Asia/Urumqi'],
'Egypt': ['Africa/Cairo'],
'India': ['Asia/Kolkata'],
'Italy': ['Europe/Rome'],
'Singapore': ['Asia/Singapore']}
Once you've chosen a specific timezone such as `Asia/Shanghai`, it is easy to
find the current time in it:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
current_time = datetime.now(pytz.timezone('Asia/Shanghai'))
print(current_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
# -> 2015-08-19 19:03:22 CST+0800
|
What's the fastest method of outputting text to console in python3
Question: I'm creating a game that is supposed to run on the command line. The game uses
text as a the canvas ( the software prints text in a shape of a rectangle, and
when the text changes, the image changes). I've created a little scrip to test
how this would work
import os
# function for printing out the game display grid
def printgrid(input):
for i in range(len(input)):
for j in range(len(input[0]):
print(input[i][j], end='')
print('') # newline after each row
grid = [['#' for x in range(10)] for x in range(10)]
while (True):
# refresh the screen and reprint
os.system('clear')
printgrid(grid)
Unfortunately the code seems to be printing the grid too slowly resulting in a
noticable scrolling effect during the printing, which would make the game
unplayable.
1. Is there a faster way to print text in python?
2. Could the cause of this scrolling effect just be the fact that I have not made any framerate cap on this code, and it just happens to show the current output when the computer monitor refreshes?
3. If my approach is completely wrong, what would be the best way to do this?
Answer: Printing to the console is usually slow, since most languages tend to wait
until the message is displayed before moving on. There are ways around thid
with your current approach.
If you use the file API, via `sys.stdout`, you can `write()` as many times as
you want and call `flush()` when the screen is ready to be printed. You may
also try calling `write()` as little as possible, perhaps building strings in
memory and outputting them whole.
The frame-rate cap is definitely needed, though. The console is not a fast
interface, it can't do high frame-rates. Implement a cap, and play with the
number.
In short:
* Call `write()` as little as possible
* Call `flush()` only when you're ready to render
* Cap the frame-rate at 10, then 20, then 30. Experiment
The other approach, which will **definitely** bring your game up to speed, is
to use `ncurses`. With it, you can update only the portions of the screen that
need re-rendering, instead of reprinting the screen whole.
|
Scraping and parsing data table using beautiful soup and python
Question: Hi everyone so I am trying to scrape table from CIA website that shows data on
roads of different countries based on unpaved and paved roads. I wrote this
script to extract. Secondly I am trying to parse out information from the
second column into separate fields but I don't know how to do that. After that
I want to save into a CSV file with the headers for each column and data.
Here is my code:
import csv
import requests
from bs4 import BeautifulSoup
course_list = []
url = "https://www.cia.gov/library/publications/the-world-factbook/fields/print_2085.html"
r = requests.get(url)
soup=BeautifulSoup(r.content)
for tr in soup.find_all('tr')[1:]:
tds=tr.find_all('td')
print (tds[1].text)
Second Column has three parts of information that I want to parse out how do I
do that?
Thanks!
Answer: Depending on how you want to achieve the extraction you could do the
following:
roadways = tds[1].text.strip().split('\n')
This removes some space from the beginning and end from the content of the
second column and splits it by the newline character. The result would be a
list like this:
['total: 97,267 km', 'paved: 18,481 km', 'unpaved: 78,786 km (2002)']
From here you could remove the labels like `total` or `paved` from the
contents:
roadways = [x[x.index(':')+1:].strip() for x in tds[1].text.strip().split('\n')]
Which would result in the following list:
['97,267 km', '18,481 km', '78,786 km (2002)']
And this you can store in your CSV file:
export_file = open(..., 'w')
wr = csv.writer(export_file, quoting=csv.QUOTE_ALL)
wr.writerow(['total','paved','unpaved'])
This goes for each row you extract:
wr.writerow(roadways)
|
I want to embellish a class from a python module. How do I do this?
Question: I am using a class from a module that I import. I want to extend this class:
add some more attributes/methods. However, I want to retain all the
functionality, including all possible constructors, of the original class.
Here is one way I can do it:
class Extension(module.ModuleClass):
def __init__(self, *args, **kwargs):
newargument = kwargs.pop("myarg")
super(Extension, self).__init__(*args, **kwargs)
self.newargument = newargument
This seems to work, but has a minor syntactic sugar issue and the following
much bigger isssue. ModuleClass overloads the "`+`" etc. operators. Of course,
Extension now benefits from this overloading, but as a result of how these are
implemented in ModuleClass, the result is of type ModuleClass, not Extension.
That is, for `Extension` objects `a` and `b`, the result `a + b` is well
defined, but has type `ModuleClass`, not `Extension`. This is crucially
important..
Is there a better way to achieve extension such as what I am looking for?
Better in the senses of type-preservation as a result of operations, easier to
debug down the line, easier to maintain, and more efficient?
Specifically, is there a way to use composition rather than inheritance? I.e.,
to write a wrapper class that **has as attribute** a `ModuleClass`, is able to
redirect all attributes (including methods) to the contained `ModuleClass`,
but handles functionality related to new arguments etc. itself?
The following is my failed attempt at using composition to solve the problem:
class Extension(object):
def __init__(self, *args, **kwargs):
self.myarg = kwargs.pop('timestamp')
self.mclass = module.ModuleClass(*args, **kwargs)
def __getattribute__(self, name):
if (name == 'mclass'):
return self.mclass
elif (name == 'myarg'):
return self.myarg
else:
return getattr(self.mclass, name)
But this fails to achieve what I want to (make `Extension` look like `Module`
with extensions). What care is to be taken?
**Minor** syntactic sugar issue: the constructor arguments now have to include
"myarg = something", which is not the most desirable. (I would have preferred
if i could have the constructor take the first argument, OR an argument
specified with "myarg = something" to initialize self.newargument. However,
this is a minor issue. Ideally, I would like to support constructor calls of
the form
Extension(validValueForMyarg, validStuffToInitModuleClass)
Extension(validStuffToInitModuleClass, myarg = validValueForMyarg)
and, where it makes sense,
Extension(myarg = validValueForMyarg, validStuffToInitModuleClass)
Answer: You can add a required argument to `Extension.__init__` like so:
class Extension(module.ModuleClass):
def __init__(self, myarg, *args, **kwargs):
super(Extension, self).__init__(*args, **kwargs)
self.newargument = myarg
|
How do I check a 3rd party Python utility library for malware?
Question: I'm very new to programming and I'm trying to find a program or method to pull
out all file names, sheet names, and count the rows of data per sheet from all
the Excel files in a single folder. Thus far, I've entertained mostly Excel
approaches, but I also considered VBA solutions, yet no luck.
I thought I had finally found my solution at
<http://www.basarat.com/2009/07/getting-row-counts-in-all-excel-file-by.html>
It looks like its a utility library with a tool that _exactly_ solves my
problem, but the author indicates that it has to be downloaded at
<https://code.google.com/p/dexutils/>
I don't have any real experience with Python and only a brief introduction to
Java, but Python keeps coming up as an acceptable tool for tackling
statistical/data analysis (which I need to master due to a recent career
change). So it's on my list of things to learn. I thought this would be a good
way to dip my toes in the Python water.
But then I saw that the blog entry and download page for the utility have no
comments and no ratings. How do I know that downloading that file won't expose
my computer to malware? This is a company computer, and I'd like to keep this
job for the foreseeable future. Downloading malware will not accomplish that.
I know that sounds a little paranoid of me, but I figure that when it comes to
security, better safe than sorry. Is there any way to check a file like this
for malware or to confirm that it is only doing what it claims to (i.e., not
running something evil in the background or messing with the registry, etc.)?
I have tried to find an answer for this on Google and this website for longer
than I care to admit, but I just don't know enough about computer security or
Python programming to know that I'm being safe.
Please speak slowly and use small words. :-P Or just give me links to sources.
Answer: Use openpyxl
from openpyxl import load_workbook
wb2 = load_workbook('test.xlsx')
print wb2.get_sheet_names()
Use you can os.listdir(path) to find all the files in folder. Pass that back
into load_workbook()
|
_winreg.EnumKey(key, i) does not workng?
Question: Hy, I trying to reconstruate a script. And in python 3 I used _winreg and the
script was working, but I need it in python 2 and now I get this erorr:
File "discoverNetworks.py", line 14, in printNets
guid = _winreg.EnumKey(key, i)
WindowsError: [Error 259] No more data is available
But of course in that folder is a lot of files.
This is the code:
import _winreg
def val2addr(val):
addr = ''
for ch in val:
addr += '%02x '% ord(ch)
addr = addr.strip(' ').replace(' ', ':')[0:17]
return addr
def printNets():
net = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Signatures\\Unmanaged"
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,net)
print '\n[*] Networks You have Joined.'
for i in range(100):
try:
guid = _winreg.EnumKey(key, i)
netKey = _winreg.OpenKey(key, str(guid))
(n, addr, t) = _winreg.EnumValue(netKey, 5)
(n, name, t) = EnumValue(netKey, 4)
macAddr = val2addr(addr)
netName = str(name)
print '[+] ' + netName + ' ' + macAddr
_winreg.CloseKey(guid)
except WindowsError:
break
def main():
printNets()
if __name__ == "__main__":
main()
* * *
Thanks!
Answer: `EnumKey()` is designed to be called repeatedly until a `WindowsError` is
thrown. From [the
documentation](https://docs.python.org/2/library/_winreg.html#_winreg.EnumKey):
> winreg.**EnumKey**(_key, index_)
>
> . . .
>
> The function retrieves the name of one subkey each time it is called. It is
> typically called repeatedly until a `WindowsError` exception is raised,
> indicating, no more values are available.
However, the reason you did not receive a `WindowsError` when you ran it in
Python 3 is because [the library changed in Python 3.3 to throw an `OSError`
instead.](https://docs.python.org/3.4/library/winreg.html?highlight=_winreg#exception-
changed)
In fact, `EnvironmentError`, `IOError`, `WindowsError`, `VMSError`,
`socket.error`, `select.error` and `mmap.error` have been merged into
`OSError` in 3.3
([source](https://docs.python.org/3.4/library/exceptions.html#OSError)).
You can handle the error via exception handling (`except WindowsError`) or
avoid it altogether by determining the number of values ahead of time with
[`QueryInfoKey`](http://docs.python.org/2/library/_winreg.html#_winreg.QueryInfoKey)
as demonstrated in [this answer](http://stackoverflow.com/a/17563506/).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.