text
stringlengths 226
34.5k
|
---|
calculate multiple sine sweeps one after another
Question: I'm writing a Python program to generate multiple sine sweeps one after
another with varying starting and ending frequencies and varying time
intervals.
One example would be:
1. sweep from 0Hz to 170Hz in 1 millisecond
2. sweep from 170Hz to 170Hz in 1 millisecond
3. sweep from 170Hz down to 10Hz in 1 millisecond
_So it is supposed to be a ramp up, ramp down waveform_.
The equation that I´ve used was inspired by [this
thread](http://stackoverflow.com/questions/11199509/sine-wave-that-slowly-
ramps-up-frequency-from-f1-to-f2-for-a-given-time)
def LinearSineSweep(self, fStart, fEnd, samplingTime, samplesPerSecond):
nValues = int(samplesPerSecond * samplingTime)
for i in range(0, nValues):
delta = float(i) / nValues
t = samplingTime * delta
phase = 2 * math.pi * t * (fStart + (fEnd - fStart) * delta / 2)
return self._amplitude * math.sin(phase) + self._dcOffset
LinearSineSweep(0, 170, 0.001, 44100)
LinearSineSweep(170, 170, 0.001, 44100)
LinearSineSweep(170, 10, 0.001, 44100)
But what I´m getting as an output is not correct:
[](http://i.stack.imgur.com/aYM3s.png)
Even with 10 times the frequency is still doesn`t come together as one
waveform
[](http://i.stack.imgur.com/OLppW.png)
_Is this a mathematical problem or a programming problem?_
Answer: As @jaket pointed out in a comment, you must make the phase vary continuously
from segment to segment (I'm paraphrasing a bit). Here's a variation of your
code that shows one way you could do this. I don't have all your other code,
so instead of `self`, the first argument of `LinearSineSweep` is a file to
which the samples are written as text. (I've also tweaked the code to
compensate for the fact that the requested interval will not, in general, be
an exact multiple of the sampling period.) `numpy` are `matplotlib` are used
to create the plot.
from __future__ import print_function, division
import math
def LinearSineSweep(f, fStart, fEnd, samplingTime, samplesPerSecond,
t0=0, phi0=0):
nValues = int(samplesPerSecond * samplingTime)
actualSamplingTime = nValues / samplesPerSecond
for i in range(0, nValues):
delta = float(i) / nValues
t = actualSamplingTime * delta
phase = 2 * math.pi * t * (fStart + (fEnd - fStart) * delta / 2)
value = math.sin(phase + phi0)
# Write the time and sample value to the output...
print(t0 + t, value, file=f)
phase = 2 * math.pi * actualSamplingTime * (fStart + (fEnd - fStart) / 2)
return t0 + actualSamplingTime, phi0 + phase
if __name__ == "__main__":
with open('out.csv', 'w') as f:
t, phi = LinearSineSweep(f, 0, 1700, 0.001, 44100)
t, phi = LinearSineSweep(f, 1700, 1700, 0.001, 44100, t, phi)
t, phi = LinearSineSweep(f, 1700, 100, 0.001, 44100, t, phi)
import numpy as np
import matplotlib.pyplot as plt
tvals, v = np.loadtxt('out.csv', unpack=True)
plt.figure(figsize=(10, 4))
plt.plot(tvals, v)
plt.grid()
plt.show()
Here's the plot:
[](http://i.stack.imgur.com/VbPtR.png)
|
How can read two field of a csv file separately in python?
Question: I want to read two column of a csv file separately, but when I wrote code like
below python just show first column and nothing for second, but in the csv
file the second column also has lots of rows.
import csv
import pprint
f = open("arachnid.csv", 'r')
read = csv.DictReader(f)
for i in range(3):
read.next()
for i in read:
pprint.pprint(i["binomialAuthority_label"])
for i in read:
pprint.pprint(i["rdf-schema#label"])
Answer: The reason for this is that when you use DictReader the way you are using it
it will create what is called an iterator/generator. So, when you have
iterated over it once, you _cannot_ iterate over it again the way you are
doing it.
If you want to keep your logic as is, you can actually call seek(0) on your
file reader object to reset its position as such:
f.seek(0)
The next time you iterate over your dictreader object, it will give you what
you are looking for. So the part of your code of interest would be this:
for i in read:
pprint.pprint(i["binomialAuthority_label"])
# This is where you set your seek(0) before the second loop
f.seek(0)
for i in read:
pprint.pprint(i['rdf-schema#label'])
|
How to merge two CSV files by Python based on the common information in both files?
Question: Evans, Great thanks. It is almost the expected result. Please kindly take a
hand to modify as follows. We need a little change. Please take a look at the
image. In the present result, each record in fileOne search the similar adv_id
and user_id in the fileTwo and when find a record take it and stop. But
possibility is that there may be several similar records in fileTwo. So, we
need all the similar records from fileTwo. And all records of fileOne must be
available at least once or several times in fileTwo. So, we should include all
record of fileOne and all of their similar records from fileTwo. I think a row
by row search might be helpful. That is take adv_id and user_id of first of
fileOne and search all records in fileTwo to find the similar record. Next use
2nd record of fileOne and search all record in fileTwo. And so on.
[Revised Image For Expected Result](http://i.stack.imgur.com/Zv79G.png)
Answer: The following script will create `result.csv` based on your original sample
data (see past edits to question):
import csv
from collections import defaultdict
d_entries = defaultdict(list)
with open('fileTwo.csv', 'r') as f_fileTwo:
csv_fileTwo = csv.reader(f_fileTwo)
header_fileTwo = next(csv_fileTwo)
for cols in csv_fileTwo:
d_entries[(cols[0], cols[1])].append([cols[0], ''] + cols[1:])
with open('fileOne.csv', 'r') as f_fileOne, open('result.csv', 'w', newline='') as f_result:
csv_fileOne = csv.reader(f_fileOne)
csv_result = csv.writer(f_result)
header_fileOne = next(csv_fileOne)
csv_result.writerow(header_fileOne)
for cols in csv_fileOne:
if (cols[0], cols[2]) in d_entries:
csv_result.writerow(cols)
csv_result.writerows(d_entries.pop((cols[0], cols[2])))
`result.csv` will then contain the following data when opened in Excel:
[](http://i.stack.imgur.com/BtRKU.png)
Tested in Python 3.4.3
To only match on the `adv_id` columns and to have all entries:
import csv
from collections import defaultdict
d_entries = defaultdict(list)
with open('fileTwo.csv', 'r') as f_fileTwo:
csv_fileTwo = csv.reader(f_fileTwo)
header_fileTwo = next(csv_fileTwo)
for cols in csv_fileTwo:
d_entries[cols[0]].append([cols[0], ''] + cols[1:])
with open('fileOne.csv', 'r') as f_fileOne, open('result.csv', 'w', newline='') as f_result:
csv_fileOne = csv.reader(f_fileOne)
csv_result = csv.writer(f_result)
header_fileOne = next(csv_fileOne)
csv_result.writerow(header_fileOne)
for cols in csv_fileOne:
if cols[0] in d_entries:
csv_result.writerows(d_entries.pop(cols[0]))
csv_result.writerow(cols)
|
xlwings wipes out my EXCEL addin
Question: I own a professional Addin for EXCEL called Valuesoft. It performs several
calculations related to equity (stockmarket) data. It is a 160K dll file and
works fine from EXCEL including from VBA scripts. However, as soon as an EXCEL
file (Workbook) is opened using xlwings from Python the dll disappears (along
with the Addins tag on the EXCEL menu).
Answer: [This question](http://stackoverflow.com/questions/32076150/excel-custom-add-
in-not-loading-when-instance-of-excel-is-opened-by-another-appl) or this [msdn
article](https://support.microsoft.com/en-us/kb/213489) seem to explain what's
happening and give you a workaround.
Since you are using an xll add-in, adopting msdn's code sample to xlwings
should look something like that:
import xlwings as xw
wb = xw.Workbook('YourWorkbook.xls')
app = xw.Application(wb)
app.xl_app.RegisterXLL("YourAddIn.xll")
|
Can the [a-zA-Z] Python regex pattern be made to match and replace non-ASCII Unicode characters?
Question: In the following regular expression, I would like each character in the string
replaced with an 'X', but it isn't working.
In Python 2.7:
>>> import re
>>> re.sub(u"[a-zA-Z]","X","dfäg")
'XX\xc3\xa4X'
or
>>> re.sub("[a-zA-Z]","X","dfäg",re.UNICODE)
u'XX\xe4X'
In Python 3.4:
>>> re.sub("[a-zA-Z]","X","dfäg")
'XXäX'
Is it possible to somehow 'configure' the [a-zA-Z] pattern to match 'ä', 'ü',
etc.? If this can't be done, how can I create a similar character range
pattern between square brackets that would include Unicode characters in the
usual 'full alphabet' range? I mean, in a language like German, for instance,
'ä' would be placed somewhere close to 'a' in the alphabet, so one would
expect it to be included in the 'a-z' range.
Answer: You may use
(?![\d_])\w
With the Unicode modifier. The `(?![\d_])` look-ahead is restricting the `\w`
shorthand class so as it could not match any digits (`\d`) or underscores.
See [regex demo](https://regex101.com/r/rR2hZ1/3)
A [Python 3 demo](http://ideone.com/7iQbyY):
import re
print (re.sub(r"(?![\d_])\w","X","dfäg"))
# => XXXX
As for [Python 2](http://ideone.com/kYgfmf):
# -*- coding: utf-8 -*-
import re
s = "dfäg"
w = re.sub(ur'(?![\d_])\w', u'X', s.decode('utf8'), 0, re.UNICODE).encode("utf8")
print(w)
|
Python - Position of last character in sequence using similar method to one here
Question:
def PositionLast(x,s):
position = -1
for i in s:
position +=1
if i == x:
return position
Is what I have so far - just returns the first. Is there a way using similar
means to return the last ? Thanks in advance
Answer: Seems that you want to return the last position of a character in your
string.For that aim you can traverse your string from end to start :
def PositionLast(x,s):
length=len(s)
position = -1
for i in s[::-1]:
position +=1
if i == x:
return length-position
But as a more pythonic way you can use `enumerate` and a generator expression
within `next` function :
def PositionLast(x,s):
return next(i for i,j in enumerate(s)[::-1] if j==x)
If you don't want to reverse the string you can use a `deque` object with max
length one to preserve the positions, thus at the end it will preserver the
last index :
from dollections import deque
def PositionLast(x,s,d=deque(maxlen=1)):
position = -1
for i in s:
position +=1
if i == x:
d.append(position)
return d.pop()
|
upload file with post params
Question: I want send file to url with some post params like "chat_id", "caption" and
file must be sended as 'photo' field-name.
but I found only methods to send only POST params without file or sending only
file without POST params and custom file name param..
This code send only `params` field, but I need also `files` field.
from urllib import parse, request
...
files={'photo': open('file.jpg','rb')}
params = parse.urlencode({'chat_id': chat_id, 'caption': 'test'})
#headers = {"Content-type": "multipart/form-data"}
req = request.Request(url, params.encode('ascii'))
response = request.urlopen(req)
print(response.read())
Python 3.4.2
Answer: ok. I found solution.
I install external lib [Requests: HTTP for
Humans](https://github.com/kennethreitz/requests).
and now i'm using `requests`
import requests
...
url = 'https://api.telegram.org/bot'+self.token+'/sendPhoto' #'/sendmessage'
print('request to '+url+' with params '+chat_id+' ' + text)
headers = {'Content-Type': 'multipart/form-data'}
files = {'photo': open('file.jpg', 'rb')}
params = {'chat_id': chat_id, 'caption': text}
r = requests.post(url, files=files, params=params)
print(r.text)
|
Python py pyfirmata code is showing the incorrect value
Question: I write the following code to check the value of input pin but it never shows
the digital value as input. I don't know what is wrong. Can any one explain it
?
from pyfirmata import ArduinoMega, util
board = ArduinoMega('COM3')
digital_0 = board.get_pin('d:30:i')
board.digital[9].write(1)
value= digital_0.read()
print value
The result is always :
>>>
None
>>>
Answer: Actually I wan not using pull-down resistor that is why it was giving the
wrong value. This problem is solved long ago :)
|
Trouble adding data to Solr with python?
Question: I am using python 3.4.3 and sunburnt to add some document to Solr(5.2.1). The
following code is directly from the Sunburnt documentation:
import sunburnt
si=sunburnt.SolrInterface("http://localhost:8983/solr/")
document = {"id":"0553573403",
"cat":"book",
"name":"A Game of Thrones",
"price":7.99,
"inStock": True,
"author_t":
"George R.R. Martin",
"series_t":"A Song of Ice and Fire",
"sequence_i":1,
"genre_s":"fantasy"}
si.add(document)
and when I run the above command I get the following:
NameError Traceback (most recent call last)
<ipython-input-1-1008a9ce394f> in <module>()----> 1 import sunburnt
2
3 si= sunburnt.SolrInterface("http://localhost:8983/solr/")
4
5 document = {"id":"0553573403",
/Users/rmohan/venv_py3/lib/python3.4/site-packages/sunburnt/__init__.py in <module>()
1 from __future__ import absolute_import
2
----> 3 from .strings import RawString
4 from .sunburnt import SolrError, SolrInterface
5
/Users/rmohan/venv_py3/lib/python3.4/site-packages/sunburnt/strings.py in <module>()
2
3
----> 4 class SolrString(unicode):
5 # The behaviour below is only really relevant for String fields rather
6 # than Text fields - most queryparsers will strip these characters out
NameError: name 'unicode' is not defined
So I tried the same document with pysolr as follows:
import pysolr
solr = pysolr.Solr('http://localhost:8983/solr/', timeout=10)
document = [{"id":"0553573403",
"cat":"book",
"name":"A Game of Thrones",
"price":7.99,
"inStock": True,
"author_t":
"George R.R. Martin",
"series_t":"A Song of Ice and Fire",
"sequence_i":1,
"genre_s":"fantasy"}]
solr.add(document)
which give the following:
/Users/rmohan/venv_py3/lib/python3.4/site-packages/pysolr.py in _scrape_response(self, headers, response)
443 dom_tree = None
444
--> 445 if response.startswith('<?xml'):
446 # Try a strict XML parse
447 try:
TypeError: startswith first arg must be bytes or a tuple of bytes, not str
I did some googling but couldn't find a definitive answer on how to resolve
the unicode or the bytes issue with the inputs. I tried converting strings to
both bytes and unicode but nothing seem to work.
If someone knows a better way to insert docs in SOLR please do share. Any help
will be greatly appreciated.
Answer: I figured it out, the file pysolr.py has
if response.startswith('<?xml'):
which needed to be changed to
if response.startswith(b'<?xml'):
More information at : <https://github.com/toastdriven/pysolr/issues/159>
|
Error: object() takes no parameters , cant resolve it
Question: this is python file im trying to make A*algorithm , but cant get it to work, I
need some help , its an awesome code , its been run in latest python version
for windows
from queue import PriorityQueue
class State(object):
def _init_(self,value,parent,start = 0,goal = 0):
self.children = []
self.value = value
self.parent = parent
self.dist = 0
if parent:
self.path = parent.path[:]
self.path.append(value)
self.start = parent.start
self.goal = parent.goal
else:
self.path = [value]
self.start = start
self.goal = goal
def GetDist(self):
pass
def CreateChildren(self):
pass
class State_String(State):
def _init_(self,value,parent,start = 0,goal = 0):
super(State_String,self).__init__(value,parent,start,goal)
self.dist = self.GetDist()
def GetDist(self):
if self.value == self.goal:
return 0
dist = 0
for i in range(len(self.goal)):
letter = self.goal[i]
dist += abs(i - self.value.index(letter))
return dist
def CreateChildren(self):
if not self.children:
for i in xrange(len(self.goal)-1):
val = self.value
val = val[:i] + val[i+1] + val[i] + val[i+2:]
child = State_String(val,self)
self.children.append(child)
class AStar_Solver:
def _init_(self,start,goal):
self.path = []
self.visitedQueue = []
self.priorityQueue = PriorityQueue()
self.start = start
self.goal = goal
def Solve(self):
startState = State_String(self.start,0,self.start,self.goal)
count = 0
self.priorityQueue.put((0,count,startState))
while(not self.path and self.priorityQueue.qsize()):
closestChild = self.priorityQueue.get()[2]
closestChild.CreateChildren()
self.visitedQueue.append(closestChild.value)
for child in closestChild.children:
if child.value not in self.visitedQueue:
count +=1
if not child.dist:
self.path = child.path
break
self.priorityQueue.put((child.dist,count,child))
if not self.path:
print "Goal of " + self.goal + " is not possible!"
return self.path
if _name_ == '__main__':
start1 = "hma"
goal1 = "ham"
a = AStar_Solver(start1,goal1)
a.Solve()
for i in xrange(len(a.path)):
print " %d)" %i + a.path[i]
getting these errors:
Traceback (most recent call last):
File "C:/Users/Herby/Desktop/untitled/Astar.py", line 82, in <module>
a.Solve()
File "C:/Users/Herby/Desktop/untitled/Astar.py", line 59, in Solve
startState = State_String(self.start,0,self.start,self.goal)
TypeError: object() takes no parameters
I need to know how it can be fixed
Answer: All of your `init` in your classes are written with single underscore instead
of double underscore:
Change all init written as: `_init_` to `__init__`
Also, this line is incorrect as well:
if _name_ == '__main__':
It needs to be double underscore for name as well
if __name__ == '__main__':
If you're interested, here is more information on why this is needed:
<https://www.python.org/dev/peps/pep-0008/>
In particular look at the description for:
"**double_leading_and_trailing_underscore** "
|
Can Golang multiply strings like Python can?
Question: Python can multiply strings like so:
Python 3.4.3 (default, Mar 26 2015, 22:03:40)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 'my new text is this long'
>>> y = '#' * len(x)
>>> y
'########################'
>>>
Can Golang do the equivalent somehow?
Answer: It has a function instead of an operator,
[Repeat](https://golang.org/pkg/strings/#Repeat). Here's a port of your Python
example:
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
x := "my new text is this long"
y := strings.Repeat("#", utf8.RuneCountInString(x))
fmt.Println(y)
}
Note that I've used `utf8.RuneCountInString(x)` instead of `len(x)`; the
former counts "runes" (Unicode code points), while the latter counts bytes. In
the case of `"my new text is this long"`, the difference doesn't matter since
all the characters are only one byte, but it's good to get into the habit of
specifying what you mean.
(In Python, `len` does both jobs depending on whether or not the string is a
Unicode string; in Go, you have to pick the function to match the semantics
you want.)
|
Python how to save dictionary with cyrillic symbols into json file
Question:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
d = {'a':'текст',
'b':{
'a':'текст2',
'b':'текст3'
}}
print(d)
w = open('log', 'w')
json.dump(d,w, ensure_ascii=False)
w.close()
It gives me: UnicodeEncodeError: 'ascii' codec can't encode characters in
position 1-5: ordinal not in range(128)
Answer: Post the full traceback, the error could be coming from the print statement
when it fails to decode the dictionary object. For some reason print statement
cannot decode all contents if you have Cyrillic text in it.
Here is how I save to json my dictionary that contains Cyrillics:
mydictionary = {'a':'текст'}
filename = "myoutfile"
with open(filename, 'w') as jsonfile:
json.dump(mydictionary, jsonfile, ensure_ascii=False)
The trick will be reading in json back into dictionary and doing things with
it.
To read in json back into dictionary:
with open(filename, 'r') as jsonfile:
newdictonary = json.load(jsonfile)
Now when you look at the dictionary, the word 'текст' looks (encoded) like
'\u0442\u0435\u043a\u0441\u0442'. You simply need to decode it using
encode('utf-8'):
for key, value in newdictionary.iteritems():
print value.encode('utf-8')
Same goes for lists if your Cyrillic text is stored there:
for f in value:
print f.encode('utf-8')
# or if you plan to use the val somewhere else:
f = f.encode('utf-8')
|
Create a list property in Python
Question: I am starting OOP with Python 3 and I find the concept of `property` really
interesting.
I need to encapsulate a private list, but how could I use this paradigm for
lists?
Here's my naive try:
class Foo:
""" Naive try to create a list property.. and obvious fail """
def __init__(self, list):
self._list = list
def _get_list(self, i):
print("Accessed element {}".format(i))
return self._list[i]
def _set_list(self, i, new):
print("Set element {} to {}".format(i, new))
self._list[i] = new
list = property(_get_list, _set_list)
This doesn't behave as expected and even makes python crash when I try the
following code. This is the fictive behavior I would like `Foo` to exhibit:
>>> f = Foo([1, 2, 3])
>>> f.list
[1, 2, 3]
>>> f.list[1]
Accessed element 1
2
>>> f.list[1] = 12
Set element 1 to 12
>>> f.list
[1, 12, 3]
Answer:
import collections
class PrivateList(collections.MutableSequence):
def __init__(self, initial=None):
self._list = initial or []
def __repr__(self):
return repr(self._list)
def __getitem__(self, item):
print("Accessed element {}".format(item))
return self._list[item]
def __setitem__(self, key, value):
print("Set element {} to {}".format(key, value))
self._list[key] = value
def __delitem__(self, key):
print("Deleting element {}".format(key))
del self._list[key]
def __len__(self):
print("Getting length")
return len(self._list)
def insert(self, index, item):
print("Inserting item {} at {}".format(item, index))
self._list.insert(index, item)
class Foo(object):
def __init__(self, a_list):
self.list = PrivateList(a_list)
Then runnning this:
foo = Foo([1,2,3])
print(foo.list)
print(foo.list[1])
foo.list[1] = 12
print(foo.list)
Outputs:
[1, 2, 3]
Accessed element 1
2
Set element 1 to 12
[1, 12, 3]
|
TypeError: Can't convert 'bytes' object to str implicitly for tweepy
Question:
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
ckey=''
csecret=''
atoken=''
asecret=''
class listener(StreamListener):
def on_data(self,data):
print(data)
return True
def on_error(self,status):
print(status)
auth = OAuthHandler(ckey,csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track="cricket")
This code filter the twitter stream based on the filter. But I am getting
following traceback after running the code. Can somebody please help
Traceback (most recent call last):
File "lab.py", line 23, in <module>
twitterStream.filter(track="car".strip())
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 430, in filter
self._start(async)
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 346, in _start
self._run()
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 286, in _run
raise exception
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 255, in _run
self._read_loop(resp)
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 298, in _read_loop
line = buf.read_line().strip()
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 171, in read_line
self._buffer += self._stream.read(self._chunk_size)
TypeError: Can't convert 'bytes' object to str implicitly
Answer: Im assuming you're using tweepy 3.4.0. The issue you've raised is 'open' on
github (<https://github.com/tweepy/tweepy/issues/615>).
Two work-arounds :
**1)** In streaming.py:
I changed line 161 to
**self._buffer += self._stream.read(read_len).decode('UTF-8', 'ignore')**
and line 171 to
**self._buffer += self._stream.read(self._chunk_size).decode('UTF-8',
'ignore')**
and then reinstalled via python3 setup.py install on my local copy of tweepy.
**2)** remove the tweepy 3.4.0 module, and install 3.3.0 using command: **pip
install -I tweepy==3.3.0**
Hope that helps,
-A
|
How to plot a CVS file with python? My plot comes up blank
Question: I have the code below that seems to run without issues until I try to plot it.
A blank plot will show when asked to plot.
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('/home/oem/Documents/620157.csv', delimiter=',', skip_header=01, skip_footer=01, names=['x', 'y'])
plt.plot(data,'o-')
plt.show()
Answer: I'm not sure what your data looks like, but I believe you need to do something
like this:
data = np.genfromtxt('/home/oem/Documents/620157.csv',
delimiter=',',
skip_header=1,
skip_footer=1)
name, x, y, a, b = zip(*data)
plt.plot(x, y, 'o-')
As per your comment, the data is currently an array containing tuples of the
station name and the x and y data. Using `zip` with the `*` symbol assigns
them back to individual variables which can then be used for plotting.
|
Python: plot timestamp data frame matplotlib
Question: I am plotting values over the time (i.e. hourly) I have a dataframe `dfout` as
following
val x y ID time
0 6.0 48.730304 11.594837 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:02:02
1 6.5 48.731639 11.602004 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:02:26
2 7.0 48.740104 11.641433 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:04:45
3 6.5 48.744026 11.648048 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:05:11
4 6.0 48.747356 11.654539 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:05:32
5 5.5 48.749050 11.660844 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:05:50
6 5.0 48.749935 11.666812 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:06:10
7 4.5 48.751007 11.677590 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:06:54
8 4.0 48.742317 11.675558 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:08:31
9 4.5 48.736461 11.675782 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:08:55
10 5.0 48.729659 11.675481 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:09:20
11 5.5 48.725871 11.673145 0efd2316-feb9-461c-b102-045aef8e22fe 2014-03-10 08:09:35
and I want to plot the column `val` as following
import matplotlib.dates as md
fig=figure(figsize=(20,10))
ax=plt.gca()
xfmt = md.DateFormatter('%H:%M:%S')
plt.xticks( rotation=25 )
ax.xaxis.set_major_formatter(xfmt)
plt.title("Temperature")
plt.ylabel(r'Temperature, $^{o}C$')
ax.plot(datenumes,dfout.val, marker='.',lw=0)
[](http://i.stack.imgur.com/PjUlB.png)
However I would like the xlabel between `08:00:00` to `16:00:00` hour by hour,
so: `08:00:00`, `09:00:00`, `10:00:00`,....,`16:00:00`.
Answer: Simply choose the position of your ticks using `ax.set_xticks()` and feed it a
custom list of `datetime` objects created for that purpose. The issue is that
the label representations of those object are floats. You can remedy this by
creating another list that contains the time-strings as you want them to look
like, which I called `ticklabels` in this solution.
import matplotlib.dates as md
import matplotlib.pyplot as plt
from datetime import *
val = [6, 6.5, 7, 6.5, 6, 5.5, 5, 4.5, 4, 4.5, 5, 5.5]
datenumes = [datetime(2014, 3, 10, 8, 2, 2),
datetime(2014, 3, 10, 8, 2, 26),
datetime(2014, 3, 10, 10, 4, 45),
datetime(2014, 3, 10, 10, 5, 11),
datetime(2014, 3, 10, 12, 5, 32),
datetime(2014, 3, 10, 12, 5, 50),
datetime(2014, 3, 10, 15, 6, 10),
datetime(2014, 3, 10, 16, 6, 54),
datetime(2014, 3, 10, 17, 8, 31),
datetime(2014, 3, 10, 18, 8, 55),
datetime(2014, 3, 10, 19, 9, 20),
datetime(2014, 3, 10, 22, 9, 35)]
# creates list of datetimes where ticks should be set
ticks = [datetime(2014, 3, 10, 8, 0, 0),
datetime(2014, 3, 10, 10, 0, 0),
datetime(2014, 3, 10, 12, 0, 0),
datetime(2014, 3, 10, 14, 0, 0),
datetime(2014, 3, 10, 16, 0, 0),
datetime(2014, 3, 10, 18, 0, 0),
datetime(2014, 3, 10, 20, 0, 0),
datetime(2014, 3, 10, 22, 0, 0) ]
# generate labels for the datetimes used as ticks
ticklabels = [str(tick)[11:] for tick in ticks]
# PLOT
fig=plt.figure(figsize=(20,10))
ax=plt.gca()
plt.xticks( rotation=25 )
# set the ticks according to the list tick
ax.set_xticks(ticks)
## set labels to human readable format
ax.set_xticklabels(ticklabels)
plt.title("Temperature")
plt.ylabel(r'Temperature, $^{o}C$')
ax.plot(datenumes, val, marker='.', lw=0)
plt.show()
[](http://i.stack.imgur.com/qlstS.png)
|
Improve performance of a for loop in Python (possibly with numpy or numba)
Question: I want to improve the performance of the `for` loop in this function.
import numpy as np
import random
def play_game(row, n=1000000):
"""Play the game! This game is a kind of random walk.
Arguments:
row (int[]): row index to use in the p matrix for each step in the
walk. Then length of this array is the same as n.
n (int): number of steps in the random walk
"""
p = np.array([[ 0.499, 0.499, 0.499],
[ 0.099, 0.749, 0.749]])
X0 = 100
Y0 = X0 % 3
X = np.zeros(n)
tempX = X0
Y = Y0
for j in range(n):
tempX = X[j] = tempX + 2 * (random.random() < p.item(row.item(j), Y)) - 1
Y = tempX % 3
return np.r_[X0, X]
The difficulty lies in the fact that the value of `Y` is computed at each step
based on the value of `X` **and** that `Y` is then used in the next step to
update the value for `X`.
I wonder if there is some numpy trick that could make a big difference. Using
Numba is fair game (I tried it but without much success). However, I do not
want to use Cython.
Answer: A quick oberservation tells us that there is data dependency between
iterations in the function code. Now, there are different kinds of data
dependencies. The kind of data dependency you are looking at is indexing
dependency that is data selection at any iteration depends on the previous
iteration calculations. This dependency seemed difficult to trace between
iterations, so this post isn't really a vectorized solution. Rather, we would
try to pre-compute values that would be used within the loop, as much as
possible. The basic idea is to do minimum work inside the loop.
Here's a brief explanation on how we can proceed with pre-calculations and
thus have a more efficient solution :
* Given, the relatively small shape of `p` from which row elements are to be extracted based on the input `row`, you can pre-select all those rows from `p` with `p[row]`.
* For each iteration, you are calculating a random number. You can replace this with a random array that you can setup before the loop and thus, you would have precalculated those random values as well.
* Based on the precalculated values thus far, you would have the column indices for all rows in `p`. Note that these column indices would be a large ndarray containing all possible column indices and inside our code, only one would be chosen based on per-iteration calculations. Using the per-iteration column indices, you would increment or decrement `X0` to get per-iteration output.
The implementation would look like this -
randarr = np.random.rand(n)
p = np.array([[ 0.499, 0.419, 0.639],
[ 0.099, 0.749, 0.319]])
def play_game_partvect(row,n,randarr,p):
X0 = 100
Y0 = X0 % 3
signvals = 2*(randarr[:,None] < p[row]) - 1
col_idx = (signvals + np.arange(3)) % 3
Y = Y0
currval = X0
out = np.empty(n+1)
out[0] = X0
for j in range(n):
currval = currval + signvals[j,Y]
out[j+1] = currval
Y = col_idx[j,Y]
return out
For verification against the original code, you would have the original code
modified like so -
def play_game(row,n,randarr,p):
X0 = 100
Y0 = X0 % 3
X = np.zeros(n)
tempX = X0
Y = Y0
for j in range(n):
tempX = X[j] = tempX + 2 * (randarr[j] < p.item(row.item(j), Y)) - 1
Y = tempX % 3
return np.r_[X0, X]
Please note that since this code precomputes those random values, so this
already would give you a good speedup over the code in the question.
Runtime tests and output verification -
In [2]: # Inputs
...: n = 1000
...: row = np.random.randint(0,2,(n))
...: randarr = np.random.rand(n)
...: p = np.array([[ 0.499, 0.419, 0.639],
...: [ 0.099, 0.749, 0.319]])
...:
In [3]: np.allclose(play_game_partvect(row,n,randarr,p),play_game(row,n,randarr,p))
Out[3]: True
In [4]: %timeit play_game(row,n,randarr,p)
100 loops, best of 3: 11.6 ms per loop
In [5]: %timeit play_game_partvect(row,n,randarr,p)
1000 loops, best of 3: 1.51 ms per loop
In [6]: # Inputs
...: n = 10000
...: row = np.random.randint(0,2,(n))
...: randarr = np.random.rand(n)
...: p = np.array([[ 0.499, 0.419, 0.639],
...: [ 0.099, 0.749, 0.319]])
...:
In [7]: np.allclose(play_game_partvect(row,n,randarr,p),play_game(row,n,randarr,p))
Out[7]: True
In [8]: %timeit play_game(row,n,randarr,p)
10 loops, best of 3: 116 ms per loop
In [9]: %timeit play_game_partvect(row,n,randarr,p)
100 loops, best of 3: 14.8 ms per loop
Thus, we are seeing a speedup of about **`7.5x+`** , not bad!
|
Jython "Attribute not found"
Question: I'm attempting to use some of the tkinter functionality in JES, on v3.4. But
I'm getting an error after import.
Code begin with this:
import Turtle
import math
myPen = Turtle.turtle()
window = Turtle.screen()
Returns the error
> The error was:class 'Turtle' has no attribute 'turtle'
> Attribute not found.
(Note I'm on the right version (3.4.3) of python for "Turtle" instead of
"turtle")
`import turtle` gives `The error was: turtle (wrong name: Turtle)`
I tried some troubleshooting in the Python console as recommended by a similar
thread, the results are below. I believe the output should have been
`"turtle.py"` or similar but as you can see, not working.
>>> import sys
>>> sys.path
['', 'C:\\Windows\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\
\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
>>> import turtle
>>> turtle.__file.__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file'
>>>
Following the path `C:\Python34\Lib` I found there is a folder
`C:\Python34\Lib\turtledemo` containing file `turtle.cfg` but no `turtle.py`
Also `C:\Python34\DLLs` contains `_tkinter.pyd` (and many others) but no
`_turtle.pyd`
I'm just a student trying to use `turtle` in JES for a project, so I hope this
question makes sense.
Answer: Your problem is that you're looking for a screen in the module. You have to
create a turtle object. That will have a screen attribute. I'm using CPython
3.5 and `import turtle` works.
>>> import turtle
>>> t = turtle.Turtle()
>>> t.screen
<turtle._Screen object at 0x10cd25a20>
You may have to modify this on your platform.
|
IP scan then do certain job and play MP3 only once
Question: I have the following code here. What I want to do is I want to script to scan
my ip address then do certain job.
My problem is the MP3 is always repeating every 30 seconds even if I did not
turn off my phone WIFI which is carrying the IP of the hostname.
I'd like the MP3 to only play once after the script found the IP but the scan
will continue scanning.
Is that possible? Any help will be very much appreciated
#!/usr/bin/env python
import os, sys
import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
import os
hostname = "192.168.254.102" #example
response = os.system("ping -c 1 " + hostname)
if response == 0:
print(hostname, 'is up!')
os.system("sudo python ../aquarium/nightlight_on.py 1")
os.system("omxplayer -o local ../music/jarvis_on.mp3 1")
else:
print(hostname, 'is down!')
os.system("sudo python ../aquarium/nightlight_off.py 1")
sc.enter(160, 1, do_something, (sc,))
s.enter(30, 1, do_something, (s,))
s.run()
Answer: If I understand what you're trying to do correctly, you want to run certain
behaviors when the availability of the IP adderss you're scanning for changes.
That is, you want to do one action when it becomes available (after having
been down) and a different action when it goes down (after having been
available). You don't want to do anything if it keeps doing the same thing it
was doing before.
This requires that you make your function access some kind of `state`
variable. A local variable won't work because you call the function repeatedly
from the scheduler (rather than writing your own loop). I think there are
three reasonable alternatives.
The simplest (from the perspective of how much your current code will need to
change) is to use a global variable. Something like this will work:
import os, sys
import sched, time
state = None
def do_something(sc):
global state # global statement is required since we write to the global state
hostname = "192.168.254.102" #example
response = os.system("ping -c 1 " + hostname)
if response == 0 and state != "up":
state = "up"
print(hostname, 'is up!')
os.system("sudo python ../aquarium/nightlight_on.py 1")
os.system("omxplayer -o local ../music/jarvis_on.mp3 1")
elif state != "down":
state = "down"
print(hostname, 'is down!')
os.system("sudo python ../aquarium/nightlight_off.py 1")
sc.enter(160, 1, do_something, (sc,))
s = sched.scheduler(time.time, time.sleep)
s.enter(30, 1, do_something, (s,))
s.run()
Global variables are often considered bad programming practice, since they
clutter up the global namespace, especially in a situation like this when you
won't be accessing that `state` variable from any other code. It's not really
a big deal for a small script like this, but it's a bad idea to do this in any
more complicated code.
The next alternative uses a closure to hold the state variable. A closure is
the namespace of an outer function that an inner function can access. To write
to a variable in a closure, you'll need to use a `nonlocal` statement, just
like the `global` statement in the previous version of the code (this is only
available in Python 3, which it looks like you're using):
import os, sys
import sched, time
def do_something_factory():
state = None # state is a local variable in the factory function's namespace
def do_something(sc):
nonlocal state # nonlocal statement lets us write to the outer scope
hostname = "192.168.254.102" #example
response = os.system("ping -c 1 " + hostname)
if response == 0 and state != "up":
state = "up"
print(hostname, 'is up!')
os.system("sudo python ../aquarium/nightlight_on.py 1")
os.system("omxplayer -o local ../music/jarvis_on.mp3 1")
elif state != "down":
state = "down"
print(hostname, 'is down!')
os.system("sudo python ../aquarium/nightlight_off.py 1")
sc.enter(160, 1, do_something, (sc,))
return do_something # return inner function to caller
s = sched.scheduler(time.time, time.sleep)
s.enter(30, 1, do_something_factory(), (s,)) # call factory function here!
s.run()
The final approach is to use a `class` to contain the function (as a method).
The state will be stored in an instance variable, accessed via `self`. The
main script code will create the object and then pass the bound method to the
scheduler. You could probably move some or all of that code into the class if
you wanted to, but I'll leave the design more or less the same for now.
import os, sys
import sched, time
class Doer(object):
def __init__(self):
self.state = None
def do_something(self, sc):
hostname = "192.168.254.102" #example
response = os.system("ping -c 1 " + hostname)
if response == 0 and self.state != "up":
self.state = "up"
print(hostname, 'is up!')
os.system("sudo python ../aquarium/nightlight_on.py 1")
os.system("omxplayer -o local ../music/jarvis_on.mp3 1")
elif self.state != "down":
self.state = "down"
print(hostname, 'is down!')
os.system("sudo python ../aquarium/nightlight_off.py 1")
sc.enter(160, 1, self.do_something, (sc,))
s = sched.scheduler(time.time, time.sleep)
d = Doer()
s.enter(30, 1, d.do_something, (s,))
s.run()
|
SQLAlchemy instantiate object from ORM fails with AttributeError: mapper
Question: I've been trying to get a decent-sized project going with SQLAlchemy on the
backend. I have table models across multiple files, a declarative base in its
own file, and a helper file to wrap common SQLAlchemy functions, and driver
file.
I was uploading data, then decided to add a column. Since this is just test
data I thought it'd be simplest to just drop all of the tables and start
fresh... then when I tried to recreate the schema and tables, the common
declarative base class suddenly had empty metadata. I worked around this by
importing the class declaration files -- strange, since I didn't need those
imports before -- and it was able to recreate the schema successfully.
But now when I try to create objects again, I get an error:
AttributeError: mapper
Now I'm totally confused! Can someone explain what's happening here? It was
working fine before I dropped the schema and now I can't get it working.
Here's the skeleton of my setup:
**base.py**
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
**models1.py**
from base import Base
class Business(Base):
__tablename__ = 'business'
id = Column(Integer, primary_key=True)
**models2.py:**
from base import Base
class Category(Base):
__tablename__ = 'category'
id = Column(Integer, primary_key=True)
**helper.py:**
from base import Base
# I didn't need these two imports the first time I made the schema
# I added them after I was just getting an empty schema from base.Base
# but have no idea why they're needed now?
import models1
import models2
def setupDB():
engine = getDBEngine(echo=True) # also a wrapped func (omitted for space)
#instantiate the schema
try:
Base.metadata.create_all(engine, checkfirst=True)
logger.info("Successfully instantiated Database with model schema")
except:
logger.error("Failed to instantieate Database with model schema")
traceback.print_exc()
def dropAllTables():
engine = getDBEngine(echo=True)
# drop the schema
try:
Base.metadata.reflect(engine, extend_existing=True)
Base.metadata.drop_all(engine)
logger.info("Successfully dropped all the database tables in the schema")
except:
logger.error("Failed to drop all tables")
traceback.print_exc()
**driver.py:**
import models1
import models2
# ^ some code to get to this point
categories []
categories.append(
models2.Category(alias=category['alias'],
title=category['title']) # error occurs here
)
**stack trace: (for completeness)**
File "./main.py", line 16, in <module>
yelp.updateDBFromYelpFeed(fname)
File "/Users/thomaseffland/Development/projects/health/pyhealth/pyhealth/data/sources/yelp.py", line 188, in updateDBFromYelpFeed
title=category['title'])
File "<string>", line 2, in __init__
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 347, in _new_state_if_none
state = self._state_constructor(instance, self)
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 747, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 177, in _state_constructor
self.dispatch.first_init(self, self.class_)
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/event/attr.py", line 256, in __call__
fn(*args, **kw)
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2825, in _event_on_first_init
configure_mappers()
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2721, in configure_mappers
mapper._post_configure_properties()
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 1710, in _post_configure_properties
prop.init()
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/interfaces.py", line 183, in init
self.do_init()
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1616, in do_init
self._process_dependent_arguments()
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1673, in _process_dependent_arguments
self.target = self.mapper.mapped_table
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 833, in __getattr__
return self._fallback_getattr(key)
File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 811, in _fallback_getattr
raise AttributeError(key)
AttributeError: mapper
I know this post is long, but I wanted to give the complete picture. First I
am confused why the `base.Base` schema was empty in the first place. Now I am
confused why the Categories object is missing a mapper!
Any help/insight/advice is greatly appreciated, thanks!
**Edit:**
So the model files and `helper.py` are in a supackage and the `driver.py` is
actually a file in a sibling subpackage and its code is wrapped in a function.
This driver function is called by a package-level main file. So I don't think
it can be because SQLAlchemy hasn't had time to initialize? (If I understand
the answer correctly) here is what the (relevant part of) main file looks
like:
**main.py:**
import models.helper as helper
helper.setupDB(echo=true) # SQLAlchemy echos the correct statements
import driverpackage.driver as driver
driver.updateDBFromFile(fname) # error occurs in here
and **driver.py** actually looks like:
import ..models.models1
import ..models.models2
def updateDBFromFile(fname):
# ^ some code to get to this point
categories []
categories.append(
models2.Category(alias=category['alias'],
title=category['title']) # error occurs here
)
# a bunch more code
**Edit 2:** I'm beginning to suspect the underlying issue is the same reason I
suddenly need to import all of the models to set up the schema in `helper.py`.
If I print the tables of the imported model objects, they have no bound
MetaData or schema:
print YelpCategory.__dict__['__table__'].__dict__
####
{'schema': None, '_columns': <sqlalchemy.sql.base.ColumnCollection object at 0x102312ef0>,
'name': 'yelp_category', 'description': 'yelp_category',
'dispatch': <sqlalchemy.event.base.DDLEventsDispatch object at 0x10230caf0>,
'indexes': set([]), 'foreign_keys': set([]),
'columns': <sqlalchemy.sql.base.ImmutableColumnCollection object at 0x10230fc58>,
'_prefixes': [],
'_extra_dependencies': set([]),
'fullname': 'yelp_category', 'metadata': MetaData(bind=None),
'implicit_returning': True,
'constraints': set([PrimaryKeyConstraint(Column('id', Integer(), table=<yelp_category>, primary_key=True, nullable=False))]), 'primary_key': PrimaryKeyConstraint(Column('id', Integer(), table=<yelp_category>, primary_key=True, nullable=False))}
I wonder why the metadata from the base that created the database is not
gettng bound?
Answer: I guess the error happens because you are executing your code on Python
module-level. This code is executed when Python imports the module.
* Move your code to a function.
* Call the function after SQLAlchemy has been properly initialized.
* `create_all()` needs to call only once when the application is installed, because created tables persistent in the database
* You need `DBSession.configure(bind=engine)` or related which will tell models to which database connection they are related. This is missing from the question.
|
BeautifulSoup - How to remove nested tags with no text and blank space from the end of HTML
Question: I'm trying to use BeautifulSoup to remove tags that have no text inside of
them. For example I have the following tags:
<p>
<p>
<br/>
</p>
</p>
or
<p>
<br/>
</p>
I have the following function:
@staticmethod
def stripTagWithNoText(soup,tagname,**kwargs):
"""Strip tags with no text"""
#Make sure that soup and tags were defined
assert isinstance(tagname,str)
#Remove tags with no text
for tag in soup.find_all(tagname):
if tag.string:
continue
for subtag in tag.findChildren():
if subtag.string:
break
else:
continue
tag.extract()
However this is also removing tags such as the following:
<p>This is some random text</p>
Can anyone spot what is wrong with this?
Additionally, suppose I have the following appended to the end of my html:
<p><br />
</p><p><br />
</p><p><br />
</p><p><br />
</p><p><br />
</p><p><br />
</p>
Is there someway to remove all blank spaces from the end of the html similar
to string_text.strip()?
**Note** I am using Python3, bs4
Answer: Does this work for you?
from bs4 import BeautifulSoup
from bs4.element import Tag
def main():
test = """
<p>
this should not be here
<p>this should not be here
<br/>this should not be here
</p>
this should not be here
</p>
"""
soup = BeautifulSoup(test, 'html.parser')
def stripTagWithNoText(soup, tagname):
def remove(node):
for index, item in enumerate(node.contents):
if isinstance(item, Tag):
remove(node.contents[index])
else:
node.contents[index] = ''
#Remove tags with no text
for tag in soup.find_all(tagname):
remove(tag)
print(soup)
stripTagWithNoText(soup, 'p')
return 0
if __name__ == '__main__':
main()
|
Multiprocess Python 3
Question: I have a script that loops over an array of numbers, those numbers are passed
to a function which calls and API. It returns JSON data which is then written
to a CSV.
for label_number in label_array:
call_api(domain, api_call_1, api_call_2, label_number, api_key)
The list can be up to 7000 elements big, as the API takes a few seconds to
respond this can take hours to run the entire script. Multiprocessing seems
the way to go with this. I can't quite working out how to do this with the
above loop. The documentation I am looking at is
<https://docs.python.org/3.5/library/multiprocessing.html>
I found a similar article at
[Python Multiprocessing a for
loop](http://stackoverflow.com/questions/20190668/python-multiprocessing-a-
for-loop)
But manipulating it doesn't seem to work, I think I am buggering it up when it
comes to passing all the variables into the function.
Any help would be appreciated.
Answer: Multiprocessing could help but this sounds more like a threading problem. Any
IO implementation should be made asynchronous, which is what threading does.
Better, in `python3.4` onwards, you could do `asyncio`.
<https://docs.python.org/3.4/library/asyncio.html>
If you have `python3.5`, this will be useful:
<https://docs.python.org/3.5/library/asyncio-task.html#example-hello-world-
coroutine>
You can mix `asyncio` with `multiprocessing` to get the optimized result. I
use in addition `joblib`.
import multiprocessing
from joblib import Parallel, delayed
def parallelProcess(i):
for index, label_number in enumerate(label_array):
if index % i == 0:
call_api_async(domain, api_call_1, api_call_2, label_number, api_key)
if __name__=="__main__":
num_cores_to_use = multiprocessing.cpu_count()
inputs = range(num_cores_to_use)
Parallel(n_jobs=num_cores_to_use)(delayed(parallelProcess)(i) for i in inputs)
|
why can't i center my menubar/navigation
Question: I'm new with **html** and **css** but I'm making a responsive dropdown menu
and I cant find why my menu/navigation bar won't center in the desktop
version.
I found the menu from [here](http://www.cssscript.com/pure-css-mobile-
compatible-responsive-dropdown-menu/) and downloaded it.
Here is my code:
<style>
@import url(http://fonts.googleapis.com/css?family=roboto);
body {
background: #212121;
font-size: 22px;
line-height: 32px;
color: #ffffff;
margin: 0;
padding: 0;
word-wrap: break-word !important;
font-family: 'roboto', sans-serif;
}
h1 {
font-size: 60px;
text-align: center;
color: #FFF;
}
h3 {
font-size: 30px;
line-height: 34px;
text-align: center;
color: #FFF;
}
h3 a { color: #FFF; }
a { color: #FFF; }
h1 {
margin-top: 100px;
text-align: center;
font-size: 60px;
line-height: 70px;
font-family: 'roboto', sans-serif;
}
#container {
margin: 0 auto;
max-width: 890px;
}
p { text-align: center; }
.toggle, [id^=drop] {
display: none;
}
nav {
margin: 0;
padding: 0;
background-color: #254441;
}
#logo {
display: block;
padding: 0 30px;
float: left;
font-size: 20px;
line-height: 60px;
}
nav:after {
content: "";
display: table;
clear: both;
}
nav ul {
float: right;
padding: 0;
margin: 0;
list-style: none;
position: relative;
}
nav ul li {
margin: 0px;
display: inline-block;
float: left;
background-color: #254441;
}
nav a {
display: block;
padding: 0 20px;
color: #FFF;
font-size: 20px;
line-height: 60px;
text-decoration: none;
}
nav ul li ul li:hover { background: #000000; }
nav a:hover { background-color: #000000; }
nav ul ul {
display: none;
position: absolute;
top: 60px;
}
nav ul li:hover > ul { display: inherit; }
nav ul ul li {
width: 170px;
float: none;
display: list-item;
position: relative;
}
nav ul ul ul li {
position: relative;
top: -60px;
left: 170px;
}
li > a:after { content: ' +'; }
li > a:only-child:after { content: ''; }
/* Media Queries
--------------------------------------------- */
@media all and (max-width : 768px) {
#logo {
display: block;
padding: 0;
width: 100%;
text-align: center;
float: none;
}
nav { margin: 0; }
.toggle + a,
.menu { display: none; }
.toggle {
display: block;
background-color: #254441;
padding: 0 20px;
color: #FFF;
font-size: 20px;
line-height: 60px;
text-decoration: none;
border: none;
}
.toggle:hover { background-color: #000000; }
[id^=drop]:checked + ul { display: block; }
nav ul li {
display: block;
width: 100%;
}
nav ul ul .toggle,
nav ul ul a { padding: 0 40px; }
nav ul ul ul a { padding: 0 80px; }
nav a:hover,
nav ul ul ul a { background-color: #000000; }
nav ul li ul li .toggle,
nav ul ul a { background-color: #212121; }
nav ul ul {
float: none;
position: static;
color: #ffffff;
}
nav ul ul li:hover > ul,
nav ul li:hover > ul { display: none; }
nav ul ul li {
display: block;
width: 100%;
}
nav ul ul ul li { position: static;
}
}
@media all and (max-width : 330px) {
nav ul li {
display: block;
width: 94%;
}
}
</style>
<body>
<nav>
<div id="logo">Demo Page</div>
<label for="drop" class="toggle">Menu</label>
<input type="checkbox" id="drop" />
<ul class="menu">
<li><a href="#">Home</a></li>
<li>
<!-- First Tier Drop Down -->
<label for="drop-1" class="toggle">Service +</label>
<a href="#">Service</a>
<input type="checkbox" id="drop-1"/>
<ul>
<li><a href="#">Service 1</a></li>
<li><a href="#">Service 2</a></li>
<li><a href="#">Service 3</a></li>
</ul>
</li>
<li>
<!-- First Tier Drop Down -->
<label for="drop-2" class="toggle">Portfolio +</label>
<a href="#">Portfolio</a>
<input type="checkbox" id="drop-2"/>
<ul>
<li><a href="#">Portfolio 1</a></li>
<li><a href="#">Portfolio 2</a></li>
<li>
<!-- Second Tier Drop Down -->
<label for="drop-3" class="toggle">Works +</label>
<a href="#">Works</a>
<input type="checkbox" id="drop-3"/>
<ul>
<li><a href="#">HTML/CSS</a></li>
<li><a href="#">jQuery</a></li>
<li><a href="#">Python</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Blog</a></li>
<li><a href="#">Submit</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>
</ul>
</nav>
<h1> Mobile-compatible Responsive Dropdown Menu Demo </h1>
</body>
Answer: Try this.
`#nav { width:750px; margin:0 auto; list-style:none;` `}`
`#nav li { float:left; }`
`#nav a { display:block; text-align:center; width:150px; /* fixed width */
text-decoration:none; }`
> Method #1 is primarily using `margin:auto;` to `center` the `nav`. If your
> menu items (li/a) are a fixed width, then this method is probably the
> easiest way to `center` your `nav`. The essentail pieces of code used to
> `center` the `nav` are in bold.
Check out this [site](http://www.websitecodetutorials.com/code/css/css-center-
nav.php) for more. Hope it helps!
|
How can I create a new page to confluence with Python
Question: I am trying to create a new page into confluence using Python's `xmlrpclib`. I
already know how to update content of an existing page, but how can I create a
totally new page?
I have used following script to update content:
import xmlrpclib
CONFLUENCE_URL='https://wiki.*ownURL*/rpc/xmlrpc'
def update_confluence(user, pwd, pageid, newcontent):
client = xmlrpclib.Server(CONFLUENCE_URL,verbose=0)
authToken=client.confluence2.login(user,pwd)
page = client.confluence2.getPage(authToken, pageid)
page['content'] = newcontent
cient.confluence2.storePage(authToken, page)
client.confluence2.logout(authToken)
and that works well when updating content. But problem is that somehow I need
to resolve `pageID` when creating a new page and I have no idea how to do
that.
Are there any other ways to create new page?
Answer: I dont know Python, but can do this with a REST call:
echo '{"type":"page","ancestors":[{"type":"page","id":'$CONFLUENCE_PARENT_PAGE'}],"title":"'$PAGE_NAME'","space":{"key":"'$CONFLUENCE_SPACE'"},"body":{"storage":{"value":"'$CONTENT'","representation":"storage"}}}' > body.json
curl --globoff --insecure --silent -u ${CONFLUENCE_USER}:${CONFLUENCE_PASSWORD} -X POST -H 'Content-Type: application/json' --data @body.json $CONFLUENCE_REST_API_URL
The confluence rest api url looks something like this:
<https://confluence.yourdomain.com/rest/api/content/>
Basically the answer to your question is you need to send the parent page as
an ancestor when creating a brand new page.
|
Look for text with BeautifulSoup in a web page with multiple html tags?
Question: Thanks for your help.
I am trying to extract text from a web page using BeautifulSoup and Python. I
have done it lots of times with different web pages and always got the
information I needed, but this time the html source code from the web page has
a lot of scripts and other stuff. This is one of the pages I want to extract
information from:
<http://www.cofemersimir.gob.mx/mirs/38656>
The problem with this web page is that it has a lot of iframe tags, each of
which has an opening tag (html) and a closing one (/html) and I can extract
information from the main page but not the information hidden on the second
tab and under the hidden display text area.
For example, when I look for:
soup.find('div',{'name':"Pregunta_452Respuesta_826"})
I can get the information I need, but if I look for:
soup.find('div',{'name':"Pregunta_459Respuesta_841"})
I get a None answer even tough I can see the information in the html source
code.
Please help me...
Thanks!
Answer: Using the following code:
import urllib2
from bs4 import BeautifulSoup
data = urllib2.urlopen('http://www.cofemersimir.gob.mx/mirs/38656')
data = data.read()
soup = BeautifulSoup(data, 'html.parser')
print soup.find('div',{'name':"Pregunta_459Respuesta_841"})
I am getting back:
<div class="RespMir" name="Pregunta_459Respuesta_841"> <p style="text-align: justify">
La regulación de mérito tiene como propósito dar a conocer el cambio de domicilio y horarios de atención de la Delegación de la Secretaría de Relaciones Exteriores en Ciudad Juárez, Chihuahua.
</p> </div>
|
Unable to see image on Google app engine web
Question: I Just want to show image on Google app Engine Website. I am new to Google app
engine. I made changes in App.yaml and Main.py app.yaml looks like :
application: simplegraph-007
version: 1
runtime: python27
api_version: 1
threadsafe: yes
handlers:
- url: /favicon\.ico
static_files: favicon.ico
upload: favicon\.ico
- url: /images
static_dir: static/images
mime_type: image/png
- url: .*
script: main.app
libraries:
- name: webapp2
version: "2.5.2"
Main.py looks like.
import webapp2
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write("""<img src = 'D:\download\rel.png/>""")
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
What else I need to change. I hope to get help.
Thanks,
Answer: Copy the image to static/images directory in your project. From a browser,
this path is "/images".
If you just want to show the image, in your browser, go to:
<http://localhost:8080/images/rel.png>
To see the image from the cloud, deploy your app and see the image at:
<http://PROJECT_ID.appspot.com/images/rel.png>
To use that image within an html page, use:
<img src="/images/rel.png" />
|
"Inconsistent number of matrix lines compared to the number of labels" runtime exception error when importing large CSV file into Gephi
Question: The full error is "java.lang.RuntimeException: java.lang.Exception:
Inconsistent number of matrix lines compared to the number of labels."
I am trying to pull an adjacency matrix stored in a CSV file into Gephi so
that I can use its modularity optimization tool and make a really slick chart
of my data. I compiled the data in Excel (yes, it took forever) and saved it
as CSV, and then I opened the file in Notepad and used Ctrl + H to replace all
commas with semicolons (and saved it as a CSV file again). My dataset is 5,654
x 5,654 cells, not counting the labels. It is an r-neighborhood graph with r =
.6299 (80th percentile and above).
I searched Google and StackOverflow and I only found one solution for my error
message: to remove all the spaces in the file. I used Ctrl + H again to remove
all spaces, but I received the same error message when I tried to upload the
"spaceless" CSV file. Just to double-check that saving it as CSV didn't cause
an issue, I checked the CSV by opening it up in Excel. The file opened
correctly, but I do not have much experience with CSV files so I do not know
if anything was off. It seemed as though all the records were separated by
semicolons instead of commas and I did not see any spaces.
Is it the size of my file? I am currently struggling through learning some
Python and R, and I would be open to creating this adjacency matrix CSV file
in either of those environments and then feeding it to Gephi. I just need a
dependable solution that works without bogging my computer down in Excel all
afternoon and allows me to be the "slick graph superhero" of my office.
Answer: Not a direct answer to your problem but there is also the [Excel/CSV import
spigot](https://marketplace.gephi.org/plugin/excel-csv-converter-to-network/)
to whatever it might be useful. Otherwise you could perhaps try to import the
network with NodeXL and then save it in GraphML format which can then be
opened by Gephi
|
Python Hangman not working
Question: So, I've finished my Hangman project for a coding class and it's stuck in a
loop where it just keeps asking if you want to play, after that it defines the
word to play but it also TELLS you which word to play you're going to play. I
think the chained whiles and ifs have some wrong variables.
So, I beg for your help.
__author__ = 'Rodrigo Cano'
#Modulos
import random
import re
#Variables Globales
intentos = 0
incorrectos = 0
palabras = [(1,"disclosure"),(1,"thenational"),(1,"foals"),(1,"skepta"),(1,"shamir"),(1,"kanye"),
(1,"fidlar"),(1,"lcdsoundsystem"),(1,"lorde"),(1,"fkatwigs"),(1,"miguel"),(1,"rtj"),
(1,"boniver"),(1,"strokes"),(2,"vaporwave"),(2,"witchouse"),(2,"shoegaze"),(2,"memerap"),
(2,"paulblartisoursaviour"),(3,"glockenspiel"),(3,"aesthetic"),(3,"schadenfreude"),
(3,"bonvivant"),(3,"swag"),(3,"jue")]
Ascii_Art =[""]
Dibujo = ' '
palabra_a_jugar = ''
Array_Palabra = []
Nuevas_Letras = ''
letras = []
Vidas = 0
i = len(Array_Palabra)
#Funciones
def Definir_Palabra():
eleccion = int(input("Bienvenido, que categoria quiere usar:"
'\n'"1 - Musica que Escuche Mientras Lo Hacia"
'\n'"2 - Generos Musicales"
'\n'"3 - Palabras Pretenciosas"))
palabras_escogidas = [i for i in palabras if eleccion in i ]
palabra_a_jugar = str(palabras_escogidas[random.randint(0,len(palabras_escogidas))].__getitem__(1))
Array_Palabra = len(palabra_a_jugar) * ['*']
return palabra_a_jugar, Array_Palabra
def Letras_En_Palabra(letra):
letras = [i for i, x in enumerate(palabra_a_jugar) if x == letra]
for i in range (0, len(letras)):
Array_Palabra[letras] = letra
return letras,Array_Palabra
def Letras_Jugadas(letra):
for i in range(0,len(Nuevas_Letras)):
Nuevas_Letras = re.findall(letra,Nuevas_Letras[i])
if Nuevas_Letras != []:
return 1
return Nuevas_Letras
def Eleccion():
Choice = input("Quiere Jugar?")
if Choice == 'si':
Choice = 1
elif Choice == 'no':
Choice = 0
return Choice
# Juego
Choice = Eleccion()
def Juego(Choice):
i = len(Array_Palabra)
while Choice == 1:
print(Definir_Palabra())
while i != 0 :
tiro = str.lower(input("adivine una letra"))
if Letras_Jugadas(tiro) != 1:
Nuevas_Letras = Nuevas_Letras + tiro
letras = Letras_En_Palabra(tiro)
if Letras_Jugadas(tiro) != []:
i = len(letras) - 1
print("Letras Utilizadas",Nuevas_Letras)
print(Letras_En_Palabra(tiro))
else:
Vidas = Vidas + 1
Dibujo += Ascii_Art[Vidas]
print("WROOOONG")
print(Dibujo)
print("Letras Utilizadas",Nuevas_Letras)
if Vidas ==9:
i = 0
else:
print("Letra ya Juagada",Nuevas_Letras)
Eleccion()
Juego(Choice)
Answer: The last line in your `Juego` should be `Choice = Eleccion()`, otherwise,
you're not actually changing the value of `Choice`, so the loop continues
indefinitely.
def Juego(Choice):
i = len(Array_Palabra)
while Choice == 1:
print(Definir_Palabra())
while i != 0 :
tiro = str.lower(input("adivine una letra"))
if Letras_Jugadas(tiro) != 1:
Nuevas_Letras = Nuevas_Letras + tiro
letras = Letras_En_Palabra(tiro)
if Letras_Jugadas(tiro) != []:
i = len(letras) - 1
print("Letras Utilizadas",Nuevas_Letras)
print(Letras_En_Palabra(tiro))
else:
Vidas = Vidas + 1
Dibujo += Ascii_Art[Vidas]
print("WROOOONG")
print(Dibujo)
print("Letras Utilizadas",Nuevas_Letras)
if Vidas ==9:
i = 0
else:
print("Letra ya Juagada",Nuevas_Letras)
"""
>>>> CHANGED <<<<
"""
Choice = Eleccion()
Otherwise, the way you had it simply calls the function `Eleccion` but
_doesn't_ return the value to the `Choice` variable in scope of `Juego`
function.
|
Scraping a web page, using xpath, returning text for the result
Question: I'm scraping a web page with lxml in Python, and trying to get the text under
the Table named (Table3). Under this table as you can see in the code below
number of tr's and then 4 td's under each tr.
**What I want is to print the text of td1 under all tr's in a list.**
Here's the HTML code :
<table width="100%" cellspacing="1" cellpadding="0" border="0" class="Table3">
<TBODY>
<TR>
<Th class="calibri-12" align="center">Symbol</Th>
<Th class="calibri-12" align="center">CompanyName</Th>
<Th class="calibri-12" align="center">Short Name</Th>
<Th class="calibri-12" align="center">ISIN Code</Th>
</TR>
<TR>
<TD >1330</TD>
<TD >ALKHODARI</TD>
<TD >SA12L0O0KP12</TD>
</TR>
<TR>
<TD >4001</TD>
<TD >A.Othaim Market</TD>
<TD >SA1230K1UGH7</TD>
</TR>
<TR>
<TD >1820</TD>
<TD >Al Hokair Group</TD>
<TD >SA13IG50SE12</TD>
</TR>
and the code I used here :
from lxml import html
import requests
page = requests.get('http://www.example.com')
tree = html.fromstring(page.content)
code_test = tree.xpath('//table[@class = "Table3"]//td[1]')
print code_test
and the result is like this :
<Element td at 0x7f4e7bbf5b50>, <Element td at 0x7f4e7bbf5ba8>, <Element td at 0x7f4e7bbf5c00>, <Element td at 0x7f4e7bbf5c58>, <Element td at 0x7f4e7bbf5cb0>, <Element td at 0x7f4e7bbf5d08>, <Element td at 0x7f4e7bbf5d60>, <Element td at 0x7f4e7bbf5db8>, <Element td at 0x7f4e7bbf5e10>, <Element td at 0x7f4e7bbf5e68>, <Element td at 0x7f4e7bbf5ec0>, <Element td at 0x7f4e7bbf5f18>, <Element td at 0x7f4e7bbf5f70>, <Element td at 0x7f4e7bbf5fc8>, <Element td at 0x7f4e7bbf6050>, <Element td at 0x7f4e7bbf60a8>, <Element td at 0x7f4e7bbf6100>, <Element td at 0x7f4e7bbf6158>, <Element td at 0x7f4e7bbf61b0>, <Element td at 0x7f4e7bbf6208>]
Answer: Modify your xpath to call `text()`.
tree.xpath('//table[@class = "Table3"]//td[1]/text()')
|
How to fit a double Gaussian distribution in Python?
Question: I am trying to obtain a double Gaussian distribution for data
([link](https://drive.google.com/file/d/0BwwhEMUIYGyTbkVwVGpoUDA2OGs/view?usp=sharing))
using Python. The raw data is of the form:
[](http://i.stack.imgur.com/Q1Wy0.png)
For the given data, I would like to obtain two Gaussian profiles for the peaks
seen in figure. I tried it with the following code
([source](http://stackoverflow.com/a/19182915/4576447)):
from sklearn import mixture
import matplotlib.pyplot
import matplotlib.mlab
import numpy as np
from pylab import *
data = np.genfromtxt('gaussian_fit.dat', skiprows = 1)
x = data[:, 0]
y = data[:, 1]
clf = mixture.GMM(n_components=2, covariance_type='full')
clf.fit((y, x))
m1, m2 = clf.means_
w1, w2 = clf.weights_
c1, c2 = clf.covars_
fig = plt.figure(figsize = (5, 5))
plt.subplot(111)
plotgauss1 = lambda x: plot(x,w1*matplotlib.mlab.normpdf(x,m1,np.sqrt(c1))[0], linewidth=3)
plotgauss2 = lambda x: plot(x,w2*matplotlib.mlab.normpdf(x,m2,np.sqrt(c2))[0], linewidth=3)
fig.savefig('gaussian_fit.pdf')
But I am not able to get the desired output. So, how can a double Gaussian
distribution be obtained in Python?
**Update**
I was able to fit a single Gaussian distribution with the following code:
import pylab as plb
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
import numpy as np
data = np.genfromtxt('gaussian_fit.dat', skiprows = 1)
x = data[:, 0]
y = data[:, 1]
n = len(x)
mean = sum(x*y)/n
sigma = sum(y*(x-mean)**2)/n
def gaus(x,a,x0,sigma):
return a*exp(-(x-x0)**2/(2*sigma**2))
popt,pcov = curve_fit(gaus, x, y ,p0 = [1, mean, sigma])
fig = plt.figure(figsize = (5, 5))
plt.subplot(111)
plt.plot(x, y, label='Raw')
plt.plot(x, gaus(x, *popt), 'o', markersize = 4, label='Gaussian fit')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
fig.savefig('gaussian_fit.pdf')
[](http://i.stack.imgur.com/lsX7X.png)
Answer: You can't use scikit-learn for this, because the you are not dealing with a
set of samples whose distribution you want to estimate. You could of course
transform your curve to a PDF, sample it and then try to fit it using a
Gaussian mixture model, but that seems to be a bit of an overkill to me.
Here's a solution using simple least square curve fitting. To get it to work I
had to remove the background, i.e. ignore all data points with `y < 5`, and
also provide a good starting vector for `leastsq`, which can be estimated form
a plot of the data.
### Finding the Starting Vector
The parameter vector that that is found by the least squares method is the
vector
params = [c1, mu1, sigma1, c2, mu2, sigma2]
Here, `c1` and `c2` are scaling factors for the two Gaussians, i.e. their
height, `mu1`and `mu2` are the means, i.e. the horizontal positions of the
peaks and `sigma1` and `sigma2` the standard deviations that determine the
width of the Gaussians. To find a starting vector I just looked at a plot of
the data and estimated the height of the two peaks ( = `c1`, `c2`,
respectively) and their horizontal position (= `mu1`, `mu1`, respectively).
`sigma1` and `sigma2` were simply set to `1.0`.
### Code
from sklearn import mixture
import matplotlib.pyplot
import matplotlib.mlab
import numpy as np
from pylab import *
from scipy.optimize import leastsq
data = np.genfromtxt('gaussian_fit.dat', skiprows = 1)
x = data[:, 0]
y = data[:, 1]
def double_gaussian( x, params ):
(c1, mu1, sigma1, c2, mu2, sigma2) = params
res = c1 * np.exp( - (x - mu1)**2.0 / (2.0 * sigma1**2.0) ) \
+ c2 * np.exp( - (x - mu2)**2.0 / (2.0 * sigma2**2.0) )
return res
def double_gaussian_fit( params ):
fit = double_gaussian( x, params )
return (fit - y_proc)
# Remove background.
y_proc = np.copy(y)
y_proc[y_proc < 5] = 0.0
# Least squares fit. Starting values found by inspection.
fit = leastsq( double_gaussian_fit, [13.0,-13.0,1.0,60.0,3.0,1.0] )
plot( x, y, c='b' )
plot( x, double_gaussian( x, fit[0] ), c='r' )
|
drawing a barcode with turtle graphics on python
Question: I know that there are crazy short cuts to doing a lot of things with Python,
which is where I'm running into trouble with this project for my intro CIS
class. I've searched for variations of my question, but without luck.. SO:
the project is to make our "turtle" draw a barcode using a ZIP that would be
entered into the command line. I have a lot of the structural work done, ie:
encodings for specific digits and telling the turtle how long to draw the bars
for specific digits.. however, now I'm stuck at writing the for loops to
actually put those two pieces together and get the program drawing the
barcode.
here's what I have:
import argparse # Used in main program to obtain 5-digit ZIP code from command
# line
import time # Used in main program to pause program before exit
import turtle # Used in your function to print the bar code
## Constants used by this program
SLEEP_TIME = 30 # number of seconds to sleep after drawing the barcode
ENCODINGS = [[1, 1, 0, 0, 0], # encoding for '0'
[0, 0, 0, 1, 1], # encoding for '1'
[0, 0, 1, 0, 1], # encoding for '2'
[0, 0, 1, 1, 0], # encoding for '3'
[0, 1, 0, 0, 1], # encoding for '4'
[0, 1, 0, 1, 0], # encoding for '5'
[0, 1, 1, 0, 0], # encoding for '6'
[1, 0, 0, 0, 1], # encoding for '7'
[1, 0, 0, 1, 0], # encoding for '8'
[1, 0, 1, 0, 0] # encoding for '9'
]
SINGLE_LENGTH = 25 # length of a short bar, long bar is twice as long
def compute_check_digit(digits):
sum = 0
for i in range(len(digits)):
sum = sum + digits[i]
check_digit = 10 - (sum % 10)
if (check_digit == 10):
check_digit = 0
return check_digit
def draw_bar(my_turtle, digit):
my_turtle.left(90)
if digit == 0:
length = SINGLE_LENGTH
else:
length = 2 * SINGLE_LENGTH
my_turtle.forward(length)
my_turtle.up()
my_turtle.backward(length)
my_turtle.right(90)
my_turtle.forward(10)
my_turtle.down()
def draw_zip(my_turtle, zip):
# WHAT DO I DO
print("My code to draw the barcode needs to replace this print statement")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("ZIP", type=int)
args = parser.parse_args()
zip = args.ZIP
if zip <= 0 or zip > 99999:
print("zip must be > 0 and < 100000; you provided", zip)
else:
my_turtle = turtle.Turtle()
draw_zip(my_turtle, zip)
time.sleep(SLEEP_TIME)
if __name__ == "__main__":
main()
The argparse/parser stuff at the beginning and end is given to us when we
start each project.
I know this next line would be helpful somewhere, i looked up the map feature
and i know that i need to convert the encodings to integers from strings.
map(list, str(zip))
Thanks!
Answer: You need to iterate through the digits of the zip. For each digit, you iterate
through the 5 bars.
for str_digit in str(zip):
digit = int(str_digit)
for bar_bit in ENCODINGS[digit]:
draw_bar(my_turtle, bar_bit)
<move turtle to next bar's starting point>
I hope this is understandable to you. You can shorten the code with various
Python techniques, but this is easy to understand.
|
django.contrib.auth utf-8 ascii python 'Unicode-objects must be encoded before hashing'
Question: I have a Django web project that was originally authored on a Linux machine
(UTF-8) and I cloned the git repository code to my windows machine. When
accessing Django's admin interface running from the built-in development web
server, I am unable to authenticate. After running a few of the authentication
calls from the Django shell it appears there is an encoding issue. Yes, I know
the best solution would be not to use Microsoft Windows, but this is the
development environment my company has provided / decided for me.
Unfortunately, adding this to my settings file does not work on windows:
import locale
locale.setlocale(locale.LC_ALL, 'UTF-8')
From VS 2013 PTVS version 2.2 Immediate Window C:\Python27\Lib\site-
packages\django\contrib\auth\backends.py:
user.set_password('mark')
None
user.save()
None
user.check_password('mark')
True
user.check_password('mark')
error: Unicode-objects must be encoded before hashing
user.password
u'bc$$2b$12$FaJjXbx.DupiSJvLJbGg7.YLDd6Ci8wS9BdASm0z94SRttMb.MFwO'
You can work around Unicode issue by converting password hash and the password
variable string to ASCII:
password = password.encode('ascii')
None
user.check_password(password)
True
Clearly this is the wrong approach and I would rather set the default encoding
to 'UTF-8' for Python running this Django project globally.
How might I best solve this?
Note: Creating new django projects locally on windows machine work just fine
because they are in default ASCII encoding. Also, sys.setdefaultencoding is no
longer an option... it would likely cause more problems anyway. I don't have
time to upgrade all our apps to Python 3.x.
Answer: It turns out the implementation of bcrypt in Django package django-
bcrypt==0.9.2, was not coded properly. I worked around issue by:
1. I removed django_bcrypt Django app from settings.py file:
INSTALLED_APPS = ( ...
# django_bcrypt,
...)
2. I then added this to the settings.py:
FILE_CHARSET='UTF-8'
3. I then simply reset my admin user's password in order to re-hash password using Django's default hash algorithm.
python manage.py changepassword *username*
Now I am able to authenticate on to the local development server again using
my windows workstation. I am sure there is another work around to get bcrypt
working with Django, but I only needed this to work on my workstation for
development and testing.
|
breaking a loop in the middle python
Question: i am trying to have a loop that keeps functioning until something is inputted
which will break the loop. However if i put in 'stop = input()' in the loop
then it has to go through that first before doing anything else. my code is
like this: (it uses some minecraft commands. basically im trying to make a
block move down a 20X20 square and have it be able to stop in the middle on
command)
from mcpi import minecraft
mc=minecraft.Minecraft.create()
from time import sleep
pos=mc.player.getTilePos
x=pos.x
y=pos.y
z=pos.z
mc.setBlocks(x-10,y,z+30,x+10,y+20,z+30,49)
BB=0
while BB<20:
BB=BB+1
sleep(.7)
mc.setBlock(x,y+(20-BB),z+30,35)
mc.setBlock(x,y+(21-BB),z+30,49)
stop=input()
if stop=='stp':
break
how do i keep the loop going until someone inputs 'stp'? because currently it
will move one block then stop and wait until i input something. The loop works
if i take out the last three lines.
Answer: Whenever you run into `input()` in your code, Python will stop until it
receives an input. If you're running the script in your console, then pressing
Ctrl+C will stop execution of the program. (I'll assume you are, because how
else would you be able to input 'stp'?)
|
How to output python graphs from terminal?
Question: I am very new to Python. Just installed it yesterday on Ubuntu 15.04. Now I am
trying to output a parabola from the terminal. As far I understand I can not
output any drawing on terminal so how can I see the graph?
I did : `sudo apt-get install python-numpy python-scipy python-matplotlib`
my code is
import matplotlib.pyplot as plt
import numpy as np
# create 1000 equally spaced points between -10 and 10
x = np.linspace(-10, 10, 1000)
# calculate the y value for each element of the x vector
y = x**2 + 2*x + 2
fig, ax = plt.subplots()
ax.plot(x, y)
it does not show error when i do `python parabola.py` but no output :(
Answer: You need to add plt.show() at the end of the code, to display the parabola.
<http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show>
|
Sum of lists for each element of list1 with all in list2
Question: I want make script that reads lines from file, than takes slices from each
line, combines all slices from 1 line with all slices from 2 line, then
combines all slices from previous step with 3rd line.
For example, we have
Stackoverflow (4)
python (3)
question (3)
I get first list with slices of (number) letters.
lst = ['Stac', 'tack', 'acko', 'ckov', 'kove', 'over', 'verf', 'erfl', 'rflo', 'flow']
Then i need to combine it with second list:
lst = ['pyt', 'yth', 'tho', 'hon']
Desired output:
finallist = ['Stacpyt', 'tackpyt', 'ackopyt', 'ckovpyt', 'kovepyt', 'overpyt', 'verfpyt', 'erflpyt', 'rflopyt', 'flowpyt' 'Stacyth', 'tackyth', 'ackoyth', 'ckovyth', 'koveyth', 'overyth', 'verfyth', 'erflyth', 'rfloyth', 'flowyth', ..... , 'erflhon', 'rflohon', 'flowhon']
then with 3rd list:
lst = ['que', 'ues', 'est', 'sti', 'tio', 'ion']
finallist = ['Stacpytque', 'tackpytque', 'ackopytque', 'ckovpytque', 'kovepytque', 'overpytque', 'verfpytque', 'erflpytque', 'rflopytque', .... 'erflhonion', 'rflohonion', 'flowhonion']
I stuck at point where I need to make finallist with combined results.
I am trying pieces of code like this, but its wrong:
for i in lst:
for y in finallist:
finallist.append(i + y)
So if finallist is empty - it should copy lst in first loop iteration, and if
finallist is not empty it should combine each element with lst and so on.
Answer: Use [**ittertools**](https://docs.python.org/2/library/itertools.html
"itertools — Functions creating iterators for efficient looping")
import itertools
list1 = ['Stac', 'tack', 'acko', 'ckov', 'kove', 'over', 'verf', 'erfl', 'rflo', 'flow']
list2 = ['pyt', 'yth', 'tho', 'hon']
list3 = ['que', 'ues', 'est', 'sti', 'tio', 'ion']
final_list = list(itertools.product(list(itertools.product(list1,list2)),list3))
This will give you all combinations, then you can just join all of them to get
your string.
|
python won't accept the value of a variable
Question: This runs and scrapes links exactly how I want it except python doesn't
recognize the value of "scraped_pages" when I run it in the terminal scraped
pages will increment by 1 every loop but it just carries on when the integer
is higher than "page_nums". when I set "page_nums" to an integer below 5 it
will run and stop at 5 but any more and it will crash. I apologize if I've not
worded the question the best I've been up all night on this. All code above
this is working this is the problem code. All modules are imported correctly
also. It uses selenium, I'm not sure the explicit wait is working since it
crashes before it will reach the "page_nums" value.
page_nums = raw_input("how many pages to scrape?: ")
urls_list = []
scraped_pages = 0
scraped_links = 0
while scraped_pages <= page_nums:
for li in list_items:
for a in li.find_all('a', href=True):
url = a['href']
if slicer(url,'http'):
url1 = slicer(url,'http')
urls_list.append(url1)
scraped_links += 1
elif slicer(url,'www'):
url1 = slicer(url,'www')
urls_list.append(url1)
scraped_links += 1
else:
pass
scraped_pages += 1
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "/html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[5]/div/span[1]/div/table/tbody/tr/td[12]")))
driver.find_element_by_xpath("/html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[5]/div/span[1]/div/table/tbody/tr/td[12]").click()
print scraped_links
print urls_list
Here is part of the error returned.
1
2
Traceback (most recent call last):
File "google page click 2.py", line 51, in <module>
driver.find_element_by_xpath("/html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[5]/div/span[1]/div/table/tbody/tr/td[12]").click()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 75, in click
self._execute(Command.CLICK_ELEMENT)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 454, in _execute
return self._parent.execute(command, params)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with
Stacktrace:
at fxdriver.preconditions.visible (file:///tmp/tmpzSHEeb/extensions/[email protected]/components/command-processor.js:9981)
at DelayedCommand.prototype.checkPreconditions_ (file:///tmp/tmpzSHEeb/extensions/[email protected]/components/command-processor.js:12517)
at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpzSHEeb/extensions/[email protected]/components/command-processor.js:12534)
at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpzSHEeb/extensions/[email protected]/components/command-processor.js:12539)
at DelayedCommand.prototype.execute/< (file:///tmp/tmpzSHEeb/extensions/[email protected]/components/command-processor.js:12481)
Answer: This problem is because Selenium has successfully loaded a webpage, but the
button you are trying to click is 'not in view'. There are two likely
scenarios:
**1.** If, for some reason, the element is hidden (ie hidden via CSS), then
you will not be able to click it.
**2.** The element might not be visible because it is in part of the webpage
that you have to scroll to view. To circumvent this issue you can use:
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[5]/div/span[1]/div/table/tbody/tr/td[12]")))
element_to_click = driver.find_element_by_xpath("/html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[5]/div/span[1]/div/table/tbody/tr/td[12]")
driver.execute_script('return arguments[0].scrollIntoView();', element_to_click)
element_to_click.click()
The third line executes some JavaScript which scrolls the element into view
before you ask Selenium to click it. If you are using this script on
hundreds/thousands of webpages then you may want to put use `time.sleep(1)`
before `element_to_click.click()`, thus giving the browser time to scroll the
element into view before attempting to click it.
As an aside, you should do a little reading on XPaths - it is a lot easier to
try and select elements by `id` or `class` name eg:
//div[@id="some-id"]
Selects the element in the document with `id="some-id"`.
|
Printing the output that is a list of file names to a text file
Question: I have made a Python program that checks the files in a folder and returns a
list of the ones that end with .txt. Now i want to output that to a file. Here
is my code:
import os
import os.path
import sys
f=open("E:\\test.txt",'w')
f.write('')
path=os.path.abspath("E:\\test")
def print_result():
print(name)
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith(".txt"):
print_result()
Version 1:
alist=[print_name]
alist.append(print_result)
f=open("E:\\test.txt", 'a')
f.writelines(alist)
Version 2:
alist=name
alist.append(name)
f = open("E:\\test.txt",'a')
print (name)
Version 3:
frame=print_result
saveout = sys.stdout
fsock = open("E:\\test.txt", 'a')
sys.stdout = fsock
print (frame)
sys.stdout = saveout`enter code here`
As you can see i have tried diferent types. The thing is that i only get the following in the file, instead of the actual output list:
<function print_result at 0x004F6DB0>
Answer: This can be done a little simpler using a
[glob](https://docs.python.org/2/library/glob.html):
import glob
txtfiles = glob.glob('E:\\test\\*.txt')
with open('E:\\test.txt', 'w') as f:
for txtfile in txtfiles:
f.write('{}\n'.format(txtfile))
|
Python can't import urllib2 (gives an error)
Question: I just started with programming, I wanted to import the urllib resource but
when I just use this code:
import urllib2
It worked 2 months ago (took a break). It gives me this error:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import urllib2
File "/usr/lib/python2.7/urllib2.py", line 94, in <module>
import httplib
File "/usr/lib/python2.7/httplib.py", line 1157, in <module>
import ssl
File "/usr/lib/python2.7/ssl.py", line 58, in <module>
import textwrap
File "/usr/lib/python2.7/textwrap.py", line 10, in <module>
import string, re
File "/home/younes/Python/string.py", line 11
for total:
^
I used Python 2 for that, also when using Python 3 it doesn't find the module.
(it also doesn't find the urllib3 module?) I have reinstalled Python but it
didn't work. I am using Ubuntu 14.04.
Answer: The file `/home/younes/Python/string.py` is preventing import of the standard
library module [`string`](https://docs.python.org/2/library/string.html) which
in turn prevent import of modules depending on the `string` module. In
addition to that, the file has an syntax error.
Remove the file or rename the file. If there's
`/home/younes/Python/string.pyc`, also remove/rename it.
|
Check_mk syntax to to make python add new hosts
Question: I´m using Check_mk and i was trying to implement a python script to run via
cfengine to add automatically new installed hosts. I´m having some trouble
with both using pycurl or running and external curl.
An example of the command i want to be able to pycurl is:
curl
"[http://10.20.30.40/mysite/check_mk/webapi.py?action=add_host&_username=autouser&_secret=mysecret](http://10.20.30.40/mysite/check_mk/webapi.py?action=add_host&_username=autouser&_secret=mysecret)"
-d 'request={"attributes":{"alias": "Alias of winxp_1", "tag_agent": "cmk-
agent", "tag_criticality": "prod", "ipaddress": "127.0.0.1"}, "hostname":
"winxp_1", "folder": "os/windows"}'
This works fine from the terminal
but i cannot find the right syntax to make it working from within the python
script.
thanks for any help.
Answer: this works for me.
NOTES: The user must exist. The "folder" must exist; i put "/" in sample.
import urllib2
req = urllib2.Request("http://localhost/mysite/check_mk/webapi.py?action=add_host&_username=autouser&_secret=mysecret",
headers = {"Content-Type": "application/x-www-form-urlencoded"},
data = 'request={"attributes":{"alias": "Alias of winxp_1", "tag_agent": "cmk-agent", "tag_criticality": "prod", "ipaddress": "127.0.0.1"}, "hostname": "winxp_1", "folder": "/"}')
f = urllib2.urlopen(req)
Sorry for my english.
|
Reconstructing a binary tree from infix and prefix expressions [python]
Question: Ive been spending hours on trying to figure out how to do this, I know the
function "buildtree" has to be called recursively to draw but I just cant
figure it out, I just need a spoon-fed answer which I can then study, I have
tried to do this for so long its just not within my capabilities cause I cant
understand the logical flow of things. (Sad thing is I know this will only
take a few lines of code)
from ListBinaryTree import ListBinaryTree
def buildtree(left_inorder, left_preorder, right_inorder, right_preorder, root, tree):
#dont know what to do.
def main():
print("Binary Tree reconstructed by glee598:")
inorder_seq = input("Please enter the inorder sequence: ")
preorder_seq = input("Please enter the preorder sequence: ")
root = preorder_seq[0]
root_inorder_index = inorder_seq.find(root)
left_inorder = inorder_seq[:root_inorder_index]
right_inorder = inorder_seq[root_inorder_index+1:]
left_preorder = preorder_seq[1:preorder_seq.find(left_inorder[0])+1]
right_preorder = preorder_seq[preorder_seq.find(left_inorder[0])+1:]
tree = ListBinaryTree(root)
buildtree(left_inorder, left_preorder, right_inorder, right_preorder, root, tree)
main()
The ListBinaryTree class:
class ListBinaryTree:
"""A binary tree class with nodes as lists."""
DATA = 0 # just some constants for readability
LEFT = 1
RIGHT = 2
def __init__(self, root_value, left=None, right=None):
"""Create a binary tree with a given root value
left, right the left, right subtrees
"""
self.node = [root_value, left, right]
def create_tree(self, a_list):
return ListBinaryTree(a_list[0], a_list[1], a_list[2])
def insert_value_left(self, value):
"""Inserts value to the left of this node.
Pushes any existing left subtree down as the left child of the new node.
"""
self.node[self.LEFT] = ListBinaryTree(value, self.node[self.LEFT], None)
def insert_value_right(self, value):
"""Inserts value to the right of this node.
Pushes any existing left subtree down as the left child of the new node.
"""
self.node[self.RIGHT] = ListBinaryTree(value, None, self.node[self.RIGHT])
def insert_tree_left(self, tree):
"""Inserts new left subtree of current node"""
self.node[self.LEFT] = tree
def insert_tree_right(self, tree):
"""Inserts new left subtree of current node"""
self.node[self.RIGHT] = tree
def set_value(self, new_value):
"""Sets the value of the node."""
self.node[self.DATA] = new_value
def get_value(self):
"""Gets the value of the node."""
return self.node[self.DATA]
def get_left_subtree(self):
"""Gets the left subtree of the node."""
return self.node[self.LEFT]
def get_right_subtree(self):
"""Gets the right subtree of the node."""
return self.node[self.RIGHT]
def __str__(self):
return '['+str(self.node[self.DATA])+', '+str(self.node[self.LEFT])+', '+\
str(self.node[self.RIGHT])+']'
Objective: [](http://i.stack.imgur.com/fpOeJ.png)
Answer: I think you've just about got it, you've just put too much of your logic in
the setup code and not realized that the recursive code is going to be the
same thing.
It will be a lot easier if you change the API of your recursive `buildtree`
function to simply take the whole `inorder` and `preorder` sequences and
return a tree built out of them.
def buildtree(inorder, preorder):
root_val = preorder[0]
left_size = inorder.index(root_val) # size of the left subtree
if left_size > 0:
left = buildtree(inorder[:left_size], preorder[1:left_size+1])
else:
left = None
if (left_size + 1) < len(inorder):
right = buildtree(inorder[left_size+1:], preorder[left_size+1:])
else:
right = None
return ListBinaryTree(root_val, left, right)
|
Python: How to Call a function in another file
Question: I am making a text-based floor game for learning purposes. I want all of the
moving-around functions to be in a separate python file but I am having issues
getting them to work together.
I have the main game called `floors.py` and the map file is `floormap.py`.
I can import and run functions from `floormap.py` inside of `floors.py`
perfectly okay.
But I do not know how to return to the `floors.py`functions after running a
`floormap.py` functions. Here is an example below. When I run this, I get the
following error in terminal:
NameError: global name 'first_hall_1' is not defined
I did get this working using:
from floormap import first_hall_1
But I could find a way to get the functions to once again be called in the
original file.
Floors.py:
import floormap
def first_hall_object():
grab = raw_input("Enter Command > ")
backward = ['back', 'Back', 'Backward', 'backward']
if any (s in grab for s in backward):
first_hall_1()
def walkin_hall():
print "whatever"
floormap.py:
import floors
def first_hall_1():
print "You are in front of the door again. It is locked."
walkin_hall()
Answer: You need to qualify `first_hall_1` with the module name `floormap`.
def first_hall_object():
grab = raw_input("Enter Command > ")
backward = ['back', 'Back', 'Backward', 'backward']
if any (s in grab for s in backward):
floormap.first_hall_1() # <-----
Same for the `walkin_hall()` call:
def first_hall_1():
print "You are in front of the door again. It is locked."
floors.walkin_hall()
|
Testing headless firefox using selenium but it is throwing an error
Question: I am trying to test headless firefox using Selenium and the below code is
giving correct result.
From a fresh Ubuntu 14.04 install I did the following
sudo apt-get install python-pip firefox xvfb
pip install selenium pyvirtualdisplay
useradd testuser
And then in a python shell:
from selenium import webdriver
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
display.start()
driver = webdriver.Firefox()
driver.get("http://askubuntu.com")
print driver.page_source.encode('utf-8')
driver.quit()
display.stop()
But if the implement the same functionality using a `class` in `Django
test.py` it is not working and throwing an error.
class FirefoxHeadlessTestCase(LiveServerTestCase):
def setUp(self):
# start display
self.display = Display(visible=0, size=(1024, 768))
self.display.start()
# start browser
self.driver = webdriver.Firefox()
def tearDown(self):
# stop browser
self.driver.quit()
super(FirefoxHeadlessTestCase, self).tearDown()
# stop display
self.display.stop()
# check if this test should be skipped
def test_example(self):
# run tests
print self.driver.get("http://askubuntu.com").page_source.encode('utf-8')
> Error: `print
> self.driver.get("http://askubuntu.com").page_source.encode('utf-8')
> AttributeError: 'NoneType' object has no attribute 'page_source'`
Anyone has an idea where I am going wrong here?
Answer: The problem is with your chaining. Notice that your django code is slightly
different
print self.driver.get("http://askubuntu.com").page_source.encode('utf-8')
from your other python code
driver.get("http://askubuntu.com")
print driver.page_source.encode('utf-8')
Unfortunately the driver [get](http://selenium-
python.readthedocs.org/api.html#selenium.webdriver.remote.webdriver.WebDriver.get)
method does not return anything so it cannot be changed as done in your django
code. You will need to lines as in your other python code.
|
Python - 2nd 'for' loop in function not working
Question: I may be missing the obvious here, and if so please excuse the noob (which I
am) question. I am trying to iterate through the lines in a text file. The
first `for` works fine; however, the 2nd `for` does not. The
`print(eachLine)`command does not print anything, and the result of the `newY`
list is a blank list (as it has been initialized). All the debugging I have
done (below is just the latest) points out to the 2nd `for` not being accessed
at all. What am I missing here?
Edit: There is a similar question
[here](http://stackoverflow.com/questions/14737980/two-for-loops-second-only-
executes-on-first-iteration-python), but in that one there are _nested_ loops
and the mistake is that the user was referring to the _same_ line in the _same
file_ in _nested_ loops. I am trying to loop through the file all over again,
from scratch.
import os
os.chdir ('d:\Documente\python tests')
def plotRegression(myFile):
lineCounter=0
sumX=0
sumY=0
sumXY=0
sumX2=0
newY=[]
for eachLine in myFile:
coords=eachLine.split()
lineCounter=lineCounter+1
sumX=sumX+float(coords[0])
sumY=sumY+float(coords[1])
sumXY=sumXY+float(coords[0])*float(coords[1])
sumX2=sumX2+float(coords[0])**2
avgX=sumX/lineCounter
avgY=sumY/lineCounter
m =(sumXY-lineCounter*avgX*avgY)/(sumX2-lineCounter*avgX**2)
for eachLine in myFile:
print (eachLine)
coords=eachLine.split()
newY.append(avgY+m*(coords[0]-avgX))
return (avgX, avgY,sumXY, sumX2, m, newY)
def Main():
dataFile = open("labdata.txt","r")
print (plotRegression(dataFile))
dataFile.close()
Main()
Answer: You'll need to _rewind_ your file read position to the start, using
[`file.seek()`](https://docs.python.org/2/library/stdtypes.html#file.seek):
myFile.seek(0)
Files are streams; reading from a file or writing to it advances a file
pointer to a new position. Iterating over a file to read from it line by line
is no exception. Once you've read all the lines in a file, the file position
is left all the way at the end and iterating again won't produce any
additional information.
It'd be a better idea to process all the information from the file and store
it in memory, reading just _once_. File reading is a slow process, compared to
accessing the same information in memory. In this case, you only need to use
the first value from each line; store that when reading in the first loop:
x_coords = []
for eachLine in myFile:
x, y = (float(c) for c in eachLine.split())
lineCounter += 1
x_coords.append(x)
sumX += x
sumY += y
sumXY += x * y
sumX2 += x ** 2
avgX = sumX / lineCounter
avgY = sumY / lineCounter
m = (sumXY - lineCounter * avgX * avgY) / (sumX2 - lineCounter * avgX ** 2)
for x in x_coords:
newY.append(avgY + m * (x - avgX))
|
dictionary update sequence element #0 has length 4; 2 is required
Question: I'm new here and django world.. I tried to find an answer about this error,
but I didn't find one that fix my problem.
**urls.py**
from django.conf.urls import include, url, patterns
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^menu_direcao/', "academico.views.menu_direcao", name='menu_direçao'),
url(r'^menu_direcao/add_prof/', "academico.views.add_prof", name='add_prof'),
]
if settings.DEBUG:
urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),)
**models.py**
from django.db import models
class AddProfessor(models.Model):
nome = models.CharField(max_length=20)
sobrenome = models.CharField(max_length=100)
nascimento = models.DateField()
matricula = models.IntegerField(max_length=20)
senha = models.CharField(max_length=20)
**forms.py**
from django import forms
from academico.models import AddProfessor
class FormAddProfessor(forms.ModelForm):
class Meta:
model = AddProfessor
fields = 'nome', 'sobrenome', 'nascimento', 'matricula'
**views.py**
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from academico.models import AddProfessor
from academico.forms import FormAddProfessor
def menu(request):
return render_to_response("menu_temp.html", context_instance = RequestContext(request))
def menu_direcao(request):
return render_to_response("menu_direcao.html", context_instance = RequestContext(request))
def add_prof(request):
if request.method == "POST":
form = FormAddProfessor(request.POST, request.FILES)
if form.is_valid():
form.save()
return render_to_response("salvo.html", {})
else:
form = FormAddProfessor()
return render_to_response("add_professor.html", {'form', form}, context_instance = RequestContext(request))
**template/add_prof.html**
{% extends 'base.html' %}
{% block corpo %}
<form action="" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Adicionar</button>
</form>
{% endblock %}
**ERROR:**
ValueError at /menu_direcao/add_prof/
dictionary update sequence element #0 has length 4; 2 is required
Request Method: GET
Request URL: http://127.0.0.1:8000/menu_direcao/add_prof/
Django Version: 1.8.5
Exception Type: ValueError
Exception Value:
dictionary update sequence element #0 has length 4; 2 is required
Exception Location: C:\Python34\lib\site-packages\django\template\context.py in __init__, line 20
Python Executable: C:\Python34\python.exe
Python Version: 3.4.2
Python Path:
['c:\\Python34\\Scripts\\escola',
'C:\\WINDOWS\\SYSTEM32\\python34.zip',
'C:\\Python34\\DLLs',
'C:\\Python34\\lib',
'C:\\Python34',
'C:\\Python34\\lib\\site-packages']
Server time: Dom, 18 Out 2015 12:50:21 -0200
**TRACEBACK:**
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/menu_direcao/add_prof/
Django Version: 1.8.5
Python Version: 3.4.2
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'academico')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "c:\Python34\Scripts\escola\academico\views.py" in add_prof
49. context_instance = RequestContext(request))
File "C:\Python34\lib\site-packages\django\shortcuts.py" in render_to_response
45. using=using)
File "C:\Python34\lib\site-packages\django\template\loader.py" in render_to_string
115. template_name, context, context_instance, dirs, dictionary)
File "C:\Python34\lib\site-packages\django\template\engine.py" in render_to_string
220. with context_instance.push(context):
File "C:\Python34\lib\site-packages\django\template\context.py" in push
55. return ContextDict(self, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\template\context.py" in __init__
20. super(ContextDict, self).__init__(*args, **kwargs)
Exception Type: ValueError at /menu_direcao/add_prof/
Exception Value: dictionary update sequence element #0 has length 4; 2 is required
So, if you can help me, I'll be very greateful.
Thanks
Answer: Try this view:
from django.shortcuts import render
def add_prof(request):
if request.method == "POST":
form = FormAddProfessor(request.POST, request.FILES)
if form.is_valid():
form.save()
return render(request, "salvo.html")
else:
form = FormAddProfessor()
return render(request, "add_professor.html", {'form': form})
|
XQuery absolute path in python lxml
Question: I have an XML document from which I want to extract the absolute path to a
specific node (mynode) for later use. I retrieve the node like this:
from StringIO import StringIO
from lxml import etree
xml = """
<a1>
<b1>
<c1>content1</c1>
</b1>
<b1>
<c1>content2</c1>
</b1>
</a1>"""
root = etree.fromstring(xml)
i = 0
mynode = root.xpath('//c1')[i]
In order to get the path I currently use
ancestors = mynode.xpath('./ancestor::*')
p = ''.join( map( lambda x: '/' + x.tag , ancestors ) + [ '/' , mynode.tag ] )
p has now the value
/a1/b1/c1
However to store the path for later use I have to store the index i from the
first code snippet aswell in order to retrieve the right node because an xpath
query for p will contain both nodes c1. I do not want to store that index.
What would be better is a path for xquery which has the index included. For
the first c1 node it could look like this:
/a1/b1[1]/c1
or this for the second c1 node
/a1/b1[2]/c1
Anyone an idea how this can be achieved? Is there another method to specify a
node and access it later on?
Answer:
from lxml import etree
from io import StringIO, BytesIO
# ----------------------------------------------
def node_location(node):
position = len(node.xpath('./preceding-sibling::' + node.tag)) + 1
return '/' + node.tag + '[' + str(position) + ']'
def node_path(node):
nodes = mynode.xpath('./ancestor-or-self::*')
return ''.join( map(node_location, nodes) )
# ----------------------------------------------
xml = """
<a1>
<b1>
<c1>content1</c1>
</b1>
<b1>
<c1>content2</c1>
</b1>
</a1>"""
root = etree.fromstring(xml)
for mynode in root.xpath('//c1'):
print node_path(mynode)
prints
/a1[1]/b1[1]/c1[1]
/a1[1]/b1[2]/c1[1]
* * *
> Is there another method to specify a node and access it later on?
If you mean "persist across separate invocations of the program", then no, not
really.
|
Date formats and its difference in python
Question: I have two dates in below formats:
d1 = "Fri, 16 Oct 2015 18:06:37 +0530"
d2 = "Thu, 1 Oct 2015 17:12:00 +0530"
I need to find the number of days between these two dates.
Answer: I like the dateutil library:
from dateutil import parser
d1 = parser.parse("Fri, 16 Oct 2015 18:06:37 +0530")
d2 = parser.parse("Thu, 1 Oct 2015 17:12:00 +0530")
print d1-d2
print (d1-d2).days
output:
15 days, 0:54:37
15
|
How can ı make a program that can run cmd comands in python3.x
Question: I trying to make a program that can access other computers in the same network
by using the cmd command. I have an administrator password that work in all
computers in our network. But I don't know how to make a program that includes
cmd commands? Which module should I use or are there other ways to do that?
Answer: Use python's os module.
import os
os.system('dir')
os.system('ping 127.0.0.1')
|
Why doesn't sys.stdout.write work in python2?
Question:
#!/usr/bin/python
import sys
def main():
f=open("a",'r')
line1=f.readlines()
f.close()
try:
sys.stdout.write(line1)
except:
print "?"
if __name__ == "__main__":
main()
Answer: `f.readlines()` doesn't return a single string, it returns a _list of lines_.
Even if there's only one line! So `sys.stdout.write()` doesn't know how to
handle that. If you iterate over that list of lines, and try to write each
one, it works just fine:
#!/usr/bin/python
import sys
def main():
f = open("a",'r')
lines = f.readlines() # lines is actually a list
f.close()
print lines # You'll see your issue, here!
try:
for line in lines:
sys.stdout.write(line) # Works now
except:
print "?"
if __name__ == "__main__":
main()
|
How to detect a laser line in an image using Python
Question: What's the quickest most reliable method of detecting a roughly horizontal red
laser line in an image using Python? I'm working on a small project related to
3d laser scanning, and I need to be able to detect the laser in an image in
order to calculate distance from its distortion.
To start, I have two images, a reference image A known to contain no laser
line, and an image B that definitely contains a laser line, possibly
distorted. e.g.
Sample image A:
[](http://i.stack.imgur.com/ZLPrA.jpg)
Sample image B:
[](http://i.stack.imgur.com/t5gkr.jpg)
Since these are RGB, but the laser is red, I remove some noise by stripping
out the blue and green channels using this function:
from PIL import Image
import numpy as np
def only_red(im):
"""
Strips out everything except red.
"""
data = np.array(im)
red, green, blue, alpha = data.T
im2 = Image.fromarray(red.T)
return im2
That gets me these images:
[](http://i.stack.imgur.com/08Lp0.jpg)
[](http://i.stack.imgur.com/YRnYp.jpg)
Next, I try and eliminate more noise by taking the difference of these two
images using `PIL.ImageChops.difference()`. Ideally, the exposure between the
two images would be identical, causing the difference to contain nothing
except the laser line. Unfortunately, because the laser adds light, the
exposure and overall brightness of each image is significantly different,
resulting in a difference that still has considerable noise. e.g.
[](http://i.stack.imgur.com/28BlP.jpg)
My final step is to make a "best guess" as to where the line is. Since I know
the line will be roughly horizontal and the laser line should be the brightest
thing in the image, I scan each column and find the row with the brightest
pixel, which I assume to be the laser line. The code for this is:
import os
from PIL import Image, ImageOps
import numpy as np
x = Image.open('laser-diff.png', 'r')
x = x.convert('L')
out = Image.new("L", x.size, "black")
pix = out.load()
y = np.asarray(x.getdata(), dtype=np.float64).reshape((x.size[1], x.size[0]))
print y.shape
for col_i in xrange(y.shape[1]):
col_max = max([(y[row_i][col_i], row_i) for row_i in xrange(y.shape[0])])
col_max_brightness, col_max_row = col_max
print col_i, col_max
pix[col_i, col_max_row] = 255
out.save('laser-line.png')
All I really need to perform my distance calculation is the array of `col_max`
values, but the `laser-line.png` helps me visualize the success, and looks
like:
[](http://i.stack.imgur.com/LdTNZ.jpg)
As you can see, the estimate is pretty close, but it still has some noise,
mostly on the left-hand side of the image where the laser line is absorbed by
a matte black finish.
What can I do to improve my accuracy and/or speed? I'm trying to run this on
an ARM platform like the Raspberry Pi, so I'm worried my code might to be too
inefficient to run well.
I'm not fully familiar with Numpy's matrix functions, so I had to settle for a
slow for loop to scan each column instead of something more efficient. Is
there a fast way to find the row with the brightest pixel per column in Numpy?
Also, is there a reliable way to equalize the images prior to performing the
difference without dimming the laser line?
Answer: First you can probably rescale the intensity of your negative image before
subtracting it from your positive, to remove more noise. For example maybe
rescaling by the ratios of the average intesity might be a good first try?
You can also try to put a threshold: if your max in below whatever good value,
then it is probably not your laser but a noisy point...
Then yes numpy can find the best row / col with the argmax function.
|
How to select rows where hours and minutes = 0 using da.searchcursor
Question: I am trying to exclude some results from numerous tables in an arc.sde
database and the only field I can use is a date field. I have researche the
Python2 site and tried to understand page 8.1 regarding datetime etc but not
been able to achieve my goal yet. (Using Win 7, ArcGIS 10.2, Python 2.7.5 and
mixed OS environment)
The code below runs fine.....
with arcpy.da.SearchCursor(fc, ['LASTEDIT_ON']) as cursor:
for row in cursor:
if row[0] <> None:
print str(row[0])
But I need it to exclude the rows returned where the hours/minutes/seconds are
all 00:00:00.
2014-05-13 16:16:34
2014-09-26 11:45:15
2015-06-18 14:47:05
2015-02-03 10:38:50
2008-03-10 00:00:00
2007-06-06 00:00:00
I tried adding hour and minutes to my code but Im totally on the wrong track I
think. Error as below.
if row[0] <> None and datetime.hour <> 0:
Error Info:
'module' object has no attribute 'hour'
Answer: If your date field is a real date field, not a text field, the following code
will print the dates with hour, minute and second all null:
import arcpy
with arcpy.da.SearchCursor(fc, 'LASTEDIT_ON') as cursor:
for row in cursor:
if row[0].hour == 0:
if row[0].minute == 0:
if row[0].second == 0:
print row[0]
|
Python : file.seek(10000000000, 2000000000). Python int too large to convert to C long
Question: im developing a program that downloads "big files" from the internet (from
200mb to 5Gb) using threads and file.seek to find a offset and insert the data
to a main file, but when i try to set the offset above the 2147483647 byte
(exceeds the C long max value) it gives the _int too large to convert to C
long_ error. how can i work around this? Bellow is a representation of my
script code.
f = open("bigfile.txt")
#create big file
f.seek(5000000000-1)
f.write("\0")
#try to get the offset, this gives the error (Python int too large to convert to C long)
f.seek(3333333333, 4444444444)
I wouldn't be asking (because it has been asked a lot) if i really found a
solution to this.
I read about casting it to a int64 and use something like UL but i dont really
understand it. I hope you can help or at least try make this clearer in my
head. xD
Answer:
f.seek(3333333333, 4444444444)
That second argument is supposed to be the `from_where` argument, dictating
whether you're seeking from:
* the file start, `os.SEEK_SET` or `0`;
* the current position, `os.SEEK_CUR` or `1`;
* the end of the file, `os.SEEK_END` or `2`.
`4444444444` is _not_ one of the allowed values.
The following program works fine:
import os
f = open("bigfile.txt",'w')
f.seek(5000000000-1)
f.write("\0")
f.seek(3333333333, os.SEEK_SET)
print f.tell() # 'print(f.tell())' for Python3
and outputs `3333333333` as expected.
|
supervisord python import error
Question: I'm trying to daemonize my bash script which starts running python script
inside.
Here is my program section of supervisord.conf
[program:source]
directory=/home/vagrant/
command=/usr/local/bin/python /home/vagrant/start.py
process_name=%(program_name)s
user=vagrant
autostart=true
When I start supervisord it doesn't work. From the log i receive:
No module named monitor.tasks
When I run the program directly it works. Seems it has working directory issue
but I don't know how to solve. Any suggestion?
Answer: Found where my mistake was. I just had to use -m after python command as
follows:
command=/usr/local/bin/python -m vagrant/start.py
|
Parsing a book into chapters – Python
Question: I have a large book stored in a single plain text file and want to parse it in
order to create individual files for each chapter. I some simple regex that
finds each chapter title, but I'm struggling at capturing all of the text in
between.
import re
txt = open('book.txt', 'r')
for line in txt :
if re.match("^[A-Z]+$", line):
print line,
I know this is fairly rudimentary, but I'm new enough to python that it's got
me a bit stumped. At the moment I'm going line by line, so my thought process
is:
1. If the line is a chapter title: Make a new file 'chapter_title.txt'
2. If the next line isn't a chapter title: Write the line to chapter_title.txt
My attempts to actually write that out have been less successful though.
Appreciate the help!
**Edit:** Specifically, I'm confused by the Python syntax for file I/O. I've
tried:
for line in txt :
if re.match("^[A-Z]+$", line):
f = open(line + '.txt', 'w')
else f.write(line + "\n")
as my general approach, but that's not gonna work as written. Hoping for help
structuring the loops. Thanks
Answer: I think this will work:
import re
with open('book.txt', 'r') as file:
txt = file.readlines()
f = False
for line in txt:
if re.match("^[A-Z]+$", line):
if f: f.close()
f = open(line + '.txt', 'w')
else:
f.write(line + "\n")
* * *
Maybe I should add some explanation:
1. `with` will auto close the file. Close an opened file is important.
2. `readlines()` function can read the file by lines and save the output to a list.
3. Here I'm using `f = False`. So first time `if f:` will be `False`.
Now here is important, if the file `f` has been opened, then `if f:` will be
`True` and the file will be closed by `f.close()`(but the first time
`f.close()` will not run).
And then, `f = open(line + '.txt', 'w')` will write text into that file, when
`re.match("^[A-Z]+$", line)` is `True` the file will be closed, and open
another file, and again, again until the `txt` list is empty.
|
Compile Latex file using a python script
Question: I am able to use python script to create a LaTeX file, but I want to take that
file and compile it, so it creates a pdf by using a python script. I have seen
some things using os and subprocess but I really don't understand it.
Answer: Try this out.
import os
os.system("pdflatex mylatex.tex")
|
Class is in sys.modules but cannot be used. Why?
Question: I have a file `MySQL.py` which contains a class `MySQL` defined like so:
class MySQL:
... all stuff that is not important here
In other file (test.py), which is in the same directory I do a conditional
loading of this `MySQL` class. By this conditional loading I mean, that I load
it in case it has not been loaded yet. To check it, I use `sys.modules` like
so:
print("MySQL" not in sys.modules)
if "MySQL" not in sys.modules:
from MySQL import MySQL
print("Loaded it")
print("MySQL" not in sys.modules)
return MySQL()
As you can see, I have some `print's` for debugging purposes. And this is what
I get in the console, when I run this file:
$ python3 test.py
True
Loaded it
False
Traceback ...
...
UnboundLocalError: local variable 'MySQL' referenced before assignment
It is really interesting, because in the console we see, that at first the
module is not loaded (`print("MySQL" not in sys.modules)` => `True`), then we
see that it gets loaded, but finally for some crazy reason `Python` does not
see this class. PS. I should add, that if I import at the very start of my
file (before all other code, then everything is ok).
**EDIT**
I think, I got it, The whole reason of all troubles is that the way I do
`import` puts my class to `sys.modules`, but at the same time it puts it to
the local namespace of the function and not the global namespace of the
module. That's it.
Answer: Your code doesn't work because if the `MySQL` module has previously been
loaded, you're not importing the class, and so the attempt to call `MySQL()`
on the last line cannot work.
A better approach is to simply do the import unconditionally. Python caches
the module once it's been loaded (this is the whole purpose of `sys.modules`),
so if you import it more than once, the heavyweight code you have in it will
still only be run once.
That said, it may be a sign of bad design if your module is doing a lot of
stuff at the top level. Perhaps you should move some or all of the object
creation or whatever inside a function somewhere and call it at an appropriate
time.
|
Extract columns from file to another file
Question: I got a text file with 17 columns and a few 100s lines. How do I extract only
column nr2, 14 and 16 to another file with only those 3 columns with a python
script? I want to make a file with 17 columns to a new file with only 3 of
those
Answer: you can use `nympy`:
import csv
import numpy as np
data = np.array(x for x in csv.reader(open("your_file")))
data[0::, column_number]
^^^
replace column_number with the number you want
|
how to save date and time using localtime in Django?
Question: So I am trying to learn Python and Django... Great language and framework.
That said, please excuse me for my seemingly very dumb question.
I have a Django project which won't be used outside a single timezone, so it
doesn't really make much sense to save stuff in UTC and convert to the "local"
timezone when needed.
The problem is that I can't seem to find a "Python/Django" way to do it
properly as seen below:
> python manage.py shell
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.utils import timezone
>>> timezone.localtime(timezone.now())
datetime.datetime(2015, 10, 19, 10, 17, 58, 153065, tzinfo=<DstTzInfo 'America/Sao_Paulo' BRST-1 day, 22:00:00 DST>)
>>> from thingie.models import Thingie
>>> a=Thingie(field1="teste",field2="12121",field3="112121",field4="904095034",timestamp=timezone.localtime(timezone.now()))
>>> a.save()
As it stands, this creates a record in my MySQL database, but the timestamp
field is recorded as UTC time...
What am I doing wrong? How can I save the timestamp in localtime?
Thanks in advance!
**EDIT**
As per my comments to Daniel's response, using datetime generates a warning in
Django, which led me to disable USE_TZ (`USE_TZ = False`). This seemed to do
the trick, but I wonder if there are any unwanted behaviours, since the
documentation recommends to use timezone support.
Thanks again!
Answer: If you don't care about timezones, don't do anything at all; just save it.
a = Thingie(field1="teste", field2="12121", field3="112121", field4="904095034", timestamp=datetime.datetime.now()))
Note, for timestamps, it's simpler to use the `auto_now` and `auto_now_add`
options in the field definition, which will set the time automatically.
|
Getting same process details as task manager in Windows
Question: I have written a program to get memory details of the current running
processes using `psutil` in Python 3. The problem is that the values I get are
not the same as those from the Windows Task Manager. Specifically, how do I
obtain the private working set size of a process in Python?
Answer: psutil calls [`GetProcessMemoryInfo`](https://msdn.microsoft.com/en-
us/library/ms683219), which doesn't break the working set down by private vs
shared memory. To get this information you can use the Windows [performance
counter API](https://msdn.microsoft.com/en-us/library/aa373083). Another way,
which I demonstrate below, is to directly count the number of shared pages.
[`QueryWorkingSet`](https://msdn.microsoft.com/en-us/library/ms684946) returns
an array of `PSAPI_WORKING_SET_BLOCK` entries (one per page in the working
set), for which you can tally the entries that have the `Shared` field set.
You'll need a process handle, which you can get by calling either
[`GetCurrentProcess`](https://msdn.microsoft.com/en-us/library/ms683179) or
[`OpenProcess`](https://msdn.microsoft.com/en-us/library/ms684320). To convert
from pages to bytes, get the system page size by calling either
[`GetPerformanceInfo`](https://msdn.microsoft.com/en-us/library/ms683210) or
[`GetSystemInfo`](https://msdn.microsoft.com/en-us/library/ms724381).
The downside to this approach is that you'll need `PROCESS_VM_READ` and
`PROCESS_QUERY_INFORMATION` access to the process. If the current user is an
elevated administrator, typically enabling `SeDebugPrivilege` gets around the
access check, except not for 'protected' processes.
from ctypes import *
from ctypes.wintypes import *
from collections import namedtuple
__all__ = ['query_working_set', 'working_set_size']
kernel32 = WinDLL('kernel32', use_last_error=True)
psapi = WinDLL('psapi', use_last_error=True)
PROCESS_VM_READ = 0x0010
PROCESS_QUERY_INFORMATION = 0x0400
ERROR_ACCESS_DENIED = 0x0005
ERROR_BAD_LENGTH = 0x0018
ULONG_PTR = WPARAM
SIZE_T = c_size_t
class PSAPI_WORKING_SET_BLOCK(Union):
class _FLAGS(Structure):
_fields_ = (('Protection', ULONG_PTR, 5),
('ShareCount', ULONG_PTR, 3),
('Shared', ULONG_PTR, 1),
('Reserved', ULONG_PTR, 3),
('VirtualPage', ULONG_PTR, 20))
_anonymous_ = '_flags',
_fields_ = (('Flags', ULONG_PTR),
('_flags', _FLAGS))
class PSAPI_WORKING_SET_INFORMATION(Structure):
_fields_ = (('NumberOfEntries', ULONG_PTR),
('_WorkingSetInfo', PSAPI_WORKING_SET_BLOCK * 1))
@property
def WorkingSetInfo(self):
array_t = PSAPI_WORKING_SET_BLOCK * self.NumberOfEntries
offset = PSAPI_WORKING_SET_INFORMATION._WorkingSetInfo.offset
return array_t.from_buffer(self, offset)
PPSAPI_WORKING_SET_INFORMATION = POINTER(PSAPI_WORKING_SET_INFORMATION)
def errcheck_bool(result, func, args):
if not result:
raise WinError(get_last_error())
return args
psapi.QueryWorkingSet.errcheck = errcheck_bool
psapi.QueryWorkingSet.argtypes = (
HANDLE, # _In_ hProcess
PPSAPI_WORKING_SET_INFORMATION, # _Out_ pv
DWORD) # _In_ cb
kernel32.GetCurrentProcess.restype = HANDLE
kernel32.OpenProcess.errcheck = errcheck_bool
kernel32.OpenProcess.restype = HANDLE
kernel32.OpenProcess.argtypes = (
DWORD, # _In_ dwDesiredAccess
BOOL, # _In_ bInheritHandle
DWORD) # _In_ dwProcessId
def query_working_set(pid=None):
"""Return the PSAPI_WORKING_SET_BLOCK array for the target process."""
if pid is None:
hprocess = kernel32.GetCurrentProcess()
else:
access = PROCESS_VM_READ | PROCESS_QUERY_INFORMATION
hprocess = kernel32.OpenProcess(access, False, pid)
info = PSAPI_WORKING_SET_INFORMATION()
base_size = sizeof(info)
item_size = sizeof(PSAPI_WORKING_SET_BLOCK)
overshoot = 0
while True:
overshoot += 4096
n = info.NumberOfEntries + overshoot
resize(info, base_size + n * item_size)
try:
psapi.QueryWorkingSet(hprocess, byref(info), sizeof(info))
break
except OSError as e:
if e.winerror != ERROR_BAD_LENGTH:
raise
return info.WorkingSetInfo
class PERFORMANCE_INFORMATION(Structure):
_fields_ = (('cb', DWORD),
('CommitTotal', SIZE_T),
('CommitLimit', SIZE_T),
('CommitPeak', SIZE_T),
('PhysicalTotal', SIZE_T),
('PhysicalAvailable', SIZE_T),
('SystemCache', SIZE_T),
('KernelTotal', SIZE_T),
('KernelPaged', SIZE_T),
('KernelNonpaged', SIZE_T),
('PageSize', SIZE_T),
('HandleCount', DWORD),
('ProcessCount', DWORD),
('ThreadCount', DWORD))
def __init__(self, *args, **kwds):
super(PERFORMANCE_INFORMATION, self).__init__(*args, **kwds)
self.cb = sizeof(self)
PPERFORMANCE_INFORMATION = POINTER(PERFORMANCE_INFORMATION)
psapi.GetPerformanceInfo.errcheck = errcheck_bool
psapi.GetPerformanceInfo.argtypes = (
PPERFORMANCE_INFORMATION, # _Out_ pPerformanceInformation
DWORD) # _In_ cb
WorkingSetSize = namedtuple('WorkingSetSize', 'total shared private')
def working_set_size(pid=None):
"""Return the total, shared, and private working set sizes
for the target process.
"""
wset = query_working_set(pid)
pinfo = PERFORMANCE_INFORMATION()
psapi.GetPerformanceInfo(byref(pinfo), sizeof(pinfo))
pagesize = pinfo.PageSize
total = len(wset) * pagesize
shared = sum(b.Shared for b in wset) * pagesize
private = total - shared
return WorkingSetSize(total, shared, private)
if __name__ == '__main__':
import sys
pid = int(sys.argv[1]) if len(sys.argv) > 1 else None
try:
total, shared, private = working_set_size(pid)
except OSError as e:
if e.winerror == ERROR_ACCESS_DENIED:
sys.exit('Access Denied')
raise
width = len(str(total))
print('Working Set: %*d' % (width, total))
print(' Shared: %*d' % (width, shared))
print(' Private: %*d' % (width, private))
For example:
C:\>tasklist /fi "imagename eq explorer.exe"
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
explorer.exe 2688 Console 1 66,048 K
C:\>workingset.py 2688
Working Set: 67465216
Shared: 59142144
Private: 8323072
The following demonstrates getting denied access to a system process, even as
an administrator. Usually enabling `SeDebugPrivilege` gets around this (note
the privilege has to be present in the process token in order to enable it;
you can't just add privileges to a token). Showing how to enable and disable
privileges in an access token is beyond the scope of this answer, but below I
demonstrate that it does work, at least for non-protected processes.
C:\>tasklist /fi "imagename eq winlogon.exe"
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
winlogon.exe 496 Console 1 8,528 K
C:\>workingset.py 496
Access Denied
C:\>python
>>> from workingset import *
>>> from privilege import enable_privilege
>>> enable_privilege('SeDebugPrivilege')
>>> working_set_size(496)
WorkingSetSize(total=8732672, shared=8716288, private=16384)
|
Plotting the graph on the complex plain
Question: I would like to plot the graphic of function: `w(s) = 1/(1+s)`.
`s` is the product of the imaginary unit (`1j`) and the variable called
`omega`; i.e. `s = 1j*omega`.
How I can plot that in the complex axis (Real and Imaginary) using Python (2.7
or 3.4) and `matplotlib`?
Answer: You're not clear in your question about what you want to plot, but assuming
omega = x + iy is the number you wish to plot w(s) as a function of, you have
to decide how to present the complex numbers w(s). You might choose a plot
with Cartesian axes representing the real (x) and imaginary (y) axes and to
plot the absolute value of w(s) as a colour, or you might choose to plot the
real and imaginary parts separately. For example,
import matplotlib as plt
import numpy as np
x = np.linspace(-0.5,0.5,100)
y = np.linspace(-3,0,100)
X, Y = np.meshgrid(x,y)
def f(x, y):
return 1./(1+1j*(x+1j*y))
import pylab
pylab.imshow(np.abs(f(X,Y)))
pylab.show()
[](http://i.stack.imgur.com/qrjuS.png)
|
Python connect to MySQL database on web server
Question: I wanted to know the process of connecting to a MySQL database that is hosted
on a web server.
I have a basic free webserver for testing on 000webhost on which I created a
MySQL database.
I have the credentials for the database which I will pretend are host -
mysql.webhost000.com user - dummy_user password - dummy_password database -
dummy_database
and I have a python script executing from my local computer with internet
access
import MySQLdb
db = MySQLdb.connect(host="mysql.webhost000.com",
port=3306,
user="dummy_user",
passwd="dummy_password",
db="dummy_database")
I was hoping it would connect as long as I have the right credentials but when
I execute the script it just hangs and once I quit it I see the error
Can't connect to MySQL server on 'mysql.webhost000.com' (4)
Am I missing some steps?
Answer: There are two possible problems and im not able to recreate the first one. One
is the
host="mysql.webhost000.com"
is incorrect and throwing an error. The connection could be listed as another
way. The other I noticed is this is usually how I set up my connection script.
import MySQLdb
def connect():
db = MySQLdb.connect(host="mysql.webhost000.com",
port=3306,
user="dummy_user",
passwd="dummy_password",
db="dummy_database")
c = conn.cursor()
return c, db
|
Python (spyder) - name 'debugfile' is not defined
Question: I'm a beginner at programming and I need to do it for a university course. The
programme I'm using is Spyder (downloaded last night) and I have to code in
'python'. I've downloaded the version required, but I can't seem to run a
simple code.
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import math
def circleAreaFromDiameter(d):
"""takes a float d and returns the area of a cirlce with diameter d.
"""
Area = math.pi * d**2/4.0
return Area
print circleAreaFromDiameter(1)
The last line, "print circleAreaFromDiameter(1)" has an exclamation mark at
the side of it saying that it's an invalid syntax. I don't understand why, but
I don't think that's my problem.
When I press the "run file" or "debug file", it says:
Traceback (most recent call last): File "", line 1, in NameError: name
'runfile' is not defined
or
Traceback (most recent call last): File "", line 1, in NameError: name
'debugfile' is not defined
I would really appreciate any help.
Answer: Clean up your line breaks, and I think it should run fine. It owrks for me in
this form:
import math
def circleAreaFromDiameter(d):
"""takes a float d and returns the area of a cirlce with diameter d. """
area = math.pi * d**2/4.0
return area
print circleAreaFromDiameter(1)
The problem was pasting the Area assignment on the same line with the block
quote (triple-quoted string).
|
Quiverkey reference arrow is not being displayed
Question: The reference arrow is missing in my quiverkey and I can't figure out why.
Can someone see what I'm doing wrong? I originally wasn't using gridspec, but
I needed to so that my figures scaled correctly. When I wasn't using gridspec,
the reference arrow was showing, but now it no longer is. Why would gridspec
cause me to lose the reference arrow for the quiverkey?
Matplotlib version : 1.4.3
Python version : 2.7.10
Note: the stick plot function taken from
[here.](https://ocefpaf.github.io/python4oceanographers/blog/2014/09/15/stick_plot/)
import matplotlib.pyplot as plot
import matplotlib as mpl
from mpl_toolkits.basemap import Basemap
import numpy as np
from datetime import datetime, timedelta
import matplotlib.gridspec as gridspec
from matplotlib.dates import date2num
def stick_plot(time, u, v, **kw):
width = kw.pop('width', 0.002)
headwidth = kw.pop('headwidth', 0)
headlength = kw.pop('headlength', 0)
headaxislength = kw.pop('headaxislength', 0)
angles = kw.pop('angles', 'uv')
ax = kw.pop('ax', None)
if angles != 'uv':
raise AssertionError("Stickplot angles must be 'uv' so that"
"if *U*==*V* the angle of the arrow on"
"the plot is 45 degrees CCW from the *x*-axis.")
if not ax:
fig, ax = plot.subplots()
q = ax.quiver(date2num(time), [[0]*len(time)], u, v,
angles='uv', width=width, headwidth=headwidth,
headlength=headlength, headaxislength=headaxislength,
**kw)
ax.axes.get_yaxis().set_visible(False)
ax.xaxis_date()
return q
x = np.arange(100, 110, 0.1)
start = datetime.now()
time = [start + timedelta(days=n) for n in range(len(x))]
u, v = np.sin(x), np.cos(x)
gs = gridspec.GridSpec(1,3, width_ratios = [5,1,3], height_ratios = [2,1])
fig = plot.figure(figsize=(11,8))
ax1 = plot.subplot(gs[:, :-1])
ax2 = plot.subplot(gs[:, -1])
map1 = Basemap(ax = ax1)
map1.drawcoastlines()
q = stick_plot(time, u, v, ax = ax2)
ref = 1
qk = plot.quiverkey(q, 0.3, 0.85, ref,
"%s N m$^{-2}$" % ref,
labelpos='N', coordinates='axes')
_ = plot.xticks(rotation=30)
plot.show()
The picture:
[](http://i.stack.imgur.com/7abmh.png)
Answer: I had similar problem. Explicitly setting `linewidth` keyword in call to
`quiver()` solved the problem for me.
|
Python, Sort List
Question: I'm trying to get it so that it finds the average of the numbers inside the
list, then sorts the averages by highest average. Here's what I have o far:
d = defaultdict(list)
for name, score in ListAvg:
d[name].append(score)
print(d.items())
This currently prrints:
dict_items([('J', ['10', '8', '4']), ('D', ['10', '7', '6']),
('I', ['10', '9', '7']), ('G', ['10', '9', '6']),
('C', ['9', '7', '5']), ('B', ['8', '6', '5']),
('F', ['8', '7', '6']), ('E', ['9', '8', '5']),
('A', ['8', '6', '5']), ('H', ['10', '7', '6'])])
Ideally I want it to print something like:
dict_items([('I', ['8.66']), ('G', ['8.33'],
('D', ['7.66']),), ('H', ['7.66']),
('J', ['7.33']), ('E', ['7.33']),
('C', ['7']), ('F', ['7']),
('A', ['6.66']), ('B', ['6.33'])])
Any way how I can make this happen, or at least have it print the names with
the averages in that order?
Answer: You can use
[statistics.mean](https://docs.python.org/3/library/statistics.html#statistics.mean)
using to get the the average and reverse sort the the tuple pairs by the
second element.
d = dict([('Jordan', ['10', '8', '4']), ('David', ['10', '7', '6']),
('Zak', ['10', '9', '7']), ('Luke', ['10', '9', '6']),
('Chloe', ['9', '7', '5']), ('Charlotte', ['8', '6', '5']),
('Josh', ['8', '7', '6']), ('Dominic', ['9', '8', '5']),
('Matthew', ['8', '6', '5']), ('Harry', ['10', '7', '6'])])
from statistics import mean
from operator import itemgetter
print(sorted(((k,mean(map(int,v))) for k,v in d.items()),key=itemgetter(1),reverse=True))
[('Zak', 8.666666666666666), ('Luke', 8.333333333333334),
('David', 7.666666666666667),('Harry', 7.666666666666667),
('Jordan', 7.333333333333333), ('Dominic', 7.333333333333333),
('Josh', 7.0), ('Chloe', 7.0), ('Charlotte', 6.333333333333333),
('Matthew', 6.333333333333333)]
If you want a dict create an `OrderedDict` for the sorted tuples:
from collections import OrderedDict
new_d = OrderedDict(sorted(((k,mean(map(int,v)))
for k,v in d.items()),key=itemgetter(1),reverse=True))
print(new_d)
OrderedDict([('Zak', 8.666666666666666), ('Luke', 8.333333333333334),
('David', 7.666666666666667), ('Harry', 7.666666666666667),
('Dominic', 7.333333333333333), ('Jordan', 7.333333333333333),
('Chloe', 7.0), ('Josh', 7.0), ('Charlotte', 6.333333333333333),
('Matthew', 6.333333333333333)])
The `OrderedDict` will maintain the insertion order which is users sorted from
highest to lowest average.
|
PyCharm type hinting doesn't work with overloaded operators
Question: This was sort of touched on in [this
thread](http://stackoverflow.com/questions/31231541/pycharm-type-error-
message/31367247#31367247), but never resolved.
I have a vector class:
class Vector2D(object):
# ...
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
# ...
def __truediv__(self, scalar):
return Vector2D(self.x / scalar, self.y / scalar)
Then, I have a function that is type hinted to accept a Vector2D:
def foo(vector):
"""
:type vector: Vector2D
"""
print("<{}, {}>".format(vector.x, vector.y))
If I try to call `foo` like so, I get a strange warning saying `"Expected type
'Vector2D', got 'int' instead"`:
foo((Vector2D(1, 2) + Vector2D(2, 3)) / 2)
However, it works fine when I run it, and there is no warning when I
explicitly use the methods of `Vector2d`:
foo(Vector2D(1, 2).__add__(Vector2D(2, 3)).__truediv__(2))
Please note I am using Python 2.7 but I have `from __future__ import division,
print_function` at the top of all my modules. Any help or advice appreciated.
Answer: Ok, I can't add a comment, because my reputation is too low, but I can create
an answer. Seems legit.
I tried you Code example (using operators) and I didn't get a warning. Even
when I left out `from __future__ import division, print_function`. Also the
right operands (or what are they called?) like `__rmul__` don't produce
warnings. In fact the autocomplete works, too
(2 * Vector2D(0, 0))
I can press `.` and it shows me the attributes of the `Vector2D` class.
I have PyCharm 4.5.4 Professional.
You can however try to manually specify the return type in the operators:
def __add__(self, other):
"""
:rtype: Vector2D
"""
return ...
You can also try to clear the PyCharm-Cache: `File -> Invalidate
Caches/Restart... -> Invalidate and Restart`
|
Alternatives to pyipc lib for IPC with python
Question: I use for an old project pyipc a Python binings to System V interprocess
communication mechanisms: <https://pypi.python.org/pypi/pyipc/>
that work well, I use it like this:
from ipc import Semaphore, MessageQueue
...
But it seems not maintain any more.
What is the more modern way to do this in python ?
Answer: check the multiprocessing module in the standard library
<https://docs.python.org/2/library/multiprocessing.html>
|
(Django) CSRF Verification for AJAX requests working in Chrome but not Firefox
Question: As the title states, my (Django) CSRF verification is working in Chrome but
not Firefox and I'd like to know why so I can fix this.
I have this included in the _head_ tag of my **base.html** file from which all
other files in my application extend:
# base.html, bottom of the head tag
<script>
$(document).ready(function() {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
</script>
And I have this code in a file called **browse.js** which needs to make ajax
requests to my own server.
# browse.js
Template = {
setup : function(){
Template.events.csrf();
// etc. etc.
},
events: {
csrf : function(){
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
},
//etc. etc.
}
//The actual ajax request
Data = {
api : {
ajax_get_listings : function(cb){
var g, i, o, _ref;
_ref = [
$('#ci').val(),
$('#co').val(),
$('#guests').val()],
i = _ref[0],
o = _ref[1],
g = _ref[2];
if (g) {
console.log('getting listings');
return $.ajax({
url:'/api/get_listing_items/',
type: 'POST',
datatype:'json',
data: {
available_start_date: i,
available_end_date: o,
max_guests: g
},
success: function(d) {
if (d.listings !== null){
Data.listings._results = [];
console.log(d);
var l = $.parseJSON(
$("<textarea/>").html(d.listings).text());
console.log(l);
data = l;
console.log(data);
return cb(data);
}else{
$('#ct').text('No listings found for your search criteria. Please keep searching!');
}
},
});
}
},
},
//etc. etc
}
Again, this works fine in Chrome. It only gives me a 403 Forbidden when I am
on Firefox. Here is the traceback:
# Traceback
## Headers
view source
Content-Type
text/html
Date
Mon, 19 Oct 2015 22:06:07 GMT
Server
WSGIServer/0.1 Python/2.7.3
Vary
Cookie
X-Frame-Options
SAMEORIGIN
view source
Accept
*/*
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Cache-Control
no-cache
Connection
keep-alive
Content-Length
54
Content-Type
application/x-www-form-urlencoded; charset=UTF-8
Cookie
_ga=GA1.1.1619904474.1445292335; _gat=1; TawkConnectionTime=0; __tawkuuid=e||127.0.0.1||mnW1PFpM4y26O8w
+2HatshrE3nWV4w3xD7SAtEMYGtV647bMojOwsqzNlPdxYCdB||2; Tawk_560d98fcc096ea637ec4b8c0=vs15.tawk.to:443
||0
DNT
1
Host
127.0.0.1:8008
Pragma
no-cache
Referer
http://127.0.0.1:8008/properties/
User-Agent
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0
X-CSRFToken
null
X-Requested-With
XMLHttpRequest
## Response
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="robots" content="NONE,NOARCHIVE">
<title>403 Forbidden</title>
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; background:#eee; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; margin-bottom:.4em; }
h1 span { font-size:60%; color:#666; font-weight:normal; }
#info { background:#f6f6f6; }
#info ul { margin: 0.5em 4em; }
#info p, #summary p { padding-top:10px; }
#summary { background: #ffc; }
#explanation { background:#eee; border-bottom: 0px none; }
</style>
</head>
<body>
<div id="summary">
<h1>Forbidden <span>(403)</span></h1>
<p>CSRF verification failed. Request aborted.</p>
<p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This
cookie is required for security reasons, to ensure that your browser is not being hijacked by third
parties.</p>
<p>If you have configured your browser to disable cookies, please re-enable them, at least for this
site, or for 'same-origin' requests.</p>
</div>
<div id="info">
<h2>Help</h2>
<p>Reason given for failure:</p>
<pre>
CSRF cookie not set.
</pre>
<p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
<a
href='http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib- csrf'>Django's
CSRF mechanism</a> has not been used correctly. For POST forms, you need to
ensure:</p>
<ul>
<li>Your browser is accepting cookies.</li>
<li>The view function uses <a
href='http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing- context-requestcontext'
><code>RequestContext</code></a>
for the template, instead of <code>Context</code>.</li>
<li>In the template, there is a <code>{% csrf_token
%}</code> template tag inside each POST form that
targets an internal URL.</li>
<li>If you are not using <code>CsrfViewMiddleware</code>, then you must use <code>csrf_protect</code> on any views that use the <code>csrf_token</code>
template tag, as well as those that accept the POST data.</li>
</ul><p>You're seeing the help section of this page because you have <code>DEBUG =
True</code> in your Django settings file. Change that to <code>False</code>,
and only the initial error message will be displayed. </p>
<p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>
</div>
</body>
</html>
What could be wrong?
* * *
SOLVED: I put @ensure_csrf_cookie on the view that was getting the cookie (NOT
the function the ajax request was calling -- this had confused me). No more
403s on Firefox now. Yay
Answer: In your request headers, I see:
> X-CSRFToken null
So my guess is that the cookie is being set in Firefox. Perhaps it was already
set in Chrome from a previous session.
[The Django docs explain one reason why this may
be](https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax):
> Warning
>
> If your view is not rendering a template containing the csrf_token template
> tag, Django might not set the CSRF token cookie. This is common in cases
> where forms are dynamically added to the page. To address this case, Django
> provides a view decorator which forces setting of the cookie:
> ensure_csrf_cookie().
Try importing the `ensure_csrf_cookie` decorator in your views.py and wrapping
your base view with it. Ex:
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def base_view(request):
# do stuff
return render('base.html', {...})
I'm not sure if this is the root issue, but I hope this helps!
|
In python, when using sqlite3 where are databases stored physically?
Question: Sorry for the basic questions. I'm starting to work with Python. I'm using
Windows 10, Python 3.5, Notepad++ as editor. Python is installed in
`z:\python35` and scripts are in `z:\python\sqlite`, then my script is really
simple:
import sqlite3
conn = sqlite3.connect('sample.db')
c = conn.cursor()
c.execute("CREATE TABLE example (name VARCHAR)")
conn.close()
When I run the script inside Notepad++ (run as administrator) I execute
`z:\python35\python.exe -i "$(FULL_CURRENT_PATH)"`. Looks like the script runs
correctly, since it does nothing the first time run, but the next time it
says:
**`sqlite3.OperationalError: table example already exits`**
And that's okay because I wanted to create the database and the table. Thing
is, where does this **`sample.db`** is stored? I don't find it in the python
directory or my projects directory. Not even by searching in Windows.
How can I delete the whole database?
Answer: It will be in the current working directory. You can see what this is by
import os
print(os.getcwd())
Once you know the directory you can find and delete the `sample.db` file.
|
Find all numbers in a string in Python 3
Question: Newbie here, been searching the net for hours for an answer.
string = "44-23+44*4522" # string could be longer
How do I make it a list, so the output is:
[44, 23, 44, 4522]
Answer: Using the regular expressions as suggested by AChampion, you can do the
following.
string = "44-23+44*4522"
import re
result = re.findall(r'\d+',string)
The r'' signifies raw text, the '\d' find a decimal character and the +
signifies 1 or more occurrences. If you expect floating points in your string
that you don't want to be separated, you might what to bracket with a period
'.'.
re.findall(r'[\d\.]+',string)
|
Installing Network-x
Question: How do I download and install network-x for python version 3.4.0 on mac? Can
someone give me a step by step guide on installing network-x? I tried to quick
'quick install' as suggested by github. When I try to import it on python it
gives me an import error saying no modules were found.
Answer: ### Ok so I have figured out an easier way:
**(Answering my own question)**
I first download the `networkx-1.10.zip (md5)` zip file from
<https://pypi.python.org/pypi/networkx>. Unzipped it. Opened the terminal and
typed `cd`
Then, I dragged and dropped the unzipped folder (`networkx-1.10`) into the
terminal. Hit Enter.
Then I proceeded with the following commands:
python3 --version
ls
umask
sudo python setup.py install
sudo python3 setup.py install
python3
It worked like a charm.
|
Using Memcache in Django/Python 3,4 with Heroku
Question: I have been following [this
tutorial](https://devcenter.heroku.com/articles/django-memcache#further-
reading-and-resources) so that I can use Memcache on my app on Heroku. However
I ran into issues when using `cache.get()` in Heroku's shell (it works fine on
my end):
File "/app/.heroku/python/lib/python3.4/site-packages/django_pylibmc/memcached.py", line 92
except MemcachedError, e:
^
SyntaxError: invalid syntax
I saw [this question](http://stackoverflow.com/questions/29189899/django-
pylibmc-complains-under-django-1-7-and-python-3-4), who had the same issue as
me. My `settings.py` looked like this:
def get_cache():
import os
try:
os.environ['MEMCACHE_SERVERS'] = os.environ['MEMCACHIER_SERVERS'].replace(',', ';')
os.environ['MEMCACHE_USERNAME'] = os.environ['MEMCACHIER_USERNAME']
os.environ['MEMCACHE_PASSWORD'] = os.environ['MEMCACHIER_PASSWORD']
return {
'default': {
'BACKEND': 'django_pylibmc.memcached.PyLibMCCache',
'TIMEOUT': 500,
'BINARY': True,
'OPTIONS': { 'tcp_nodelay': True }
}
}
except:
return {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
}
}
And so I replaced `django_pylibmc.memcached.PyLibMCCache` with
`django.core.cache.backends.memcached.PyLibMCCache`. However then I got a
different error when I tried `cache.get("foo")` again:
File "/app/.heroku/python/lib/python3.4/site-packages/django/core/cache/backends/memcached.py", line 84, in get
val = self._cache.get(key)
_pylibmc.ConnectionError: error 3 from memcached_get(:1:foo): (0x1c4ed40) CONNECTION FAILURE, host: localhost:11211 -> libmemcached/get.cc:314
Could someone help me out? Is there some settings somewhere that I need to
change?
Answer: I decided to switch to using Django's database cache instead.
|
Implementing large data set causing "string index out of range" error in Python?
Question: I am trying to implement the following code:
with open('datapath') as f:
k_mers = f.read()
k_mers_parsed = []
for i in k_mers.split('\n'):
k_mers_parsed.append(i)
genome = k_mers_parsed[0]
for i in range(1,len(k_mers_parsed)):
genome = genome + k_mers_parsed[i][-1]
with open('filepath', 'w') as out:
out.write(genome)
Reading a file that has about 4 lines of code works perfectly and I generate
the solution set needed in a quick manner.
However, whenever I try to import a large scale dataset, one with say, 1000
lines, I get this error:
genome = genome + k_mers_parsed[i][-1]
IndexError: string index out of range
What is the root cause of this and how can I remedy this?
Answer: You likely have an empty line in the file. Also try this:
with open('datapath') as f:
genome = [l[-1] for l in f if l]
|
Interaction with python's matplotlib figure: assign value to selected features
Question: Is it possible to select an area inside a matplotlib's figure window to which
assign the value, say, 0? For example, let's say I want to write a script
that, at a certain point, shows the image inside a figure window
(pyplot.imshow) and asks the user to select an area to which assign the value
0? Hope that was clear enough.
Answer: This works well. Here you have a `pcolormesh` in which you can click and the
`onclick` function that catches the click event will handle it and set the
selected square to zero. The `mpl_connect` function connects the `onclick`
function to the `button_press_event` event. You can see the update directly
after the click.
import numpy as np
import pylab as pl
pl.ioff()
rand_field = np.random.rand(10,10)
fig = pl.figure()
cm = pl.pcolormesh(rand_field, vmin=0, vmax=1)
pl.colorbar()
def onclick(event):
indexx = int(event.xdata)
indexy = int(event.ydata)
print("Index ({0},{1}) will be set to zero".format(indexx, indexy))
rand_field[indexy, indexx] = 0.
cm.set_array(rand_field.ravel())
event.canvas.draw()
cid = fig.canvas.mpl_connect('button_press_event', onclick)
pl.show()
Here you find a more advanced version that can drag a region and handles the
error in case somebody clicks outside of the figure. I leave the drawing of
the rectangle up to you:
import numpy as np
import pylab as pl
pl.ioff()
rand_field = np.random.rand(10,10)
fig = pl.figure()
cm = pl.pcolormesh(rand_field, vmin=0, vmax=1)
pl.colorbar()
x_press = None
y_press = None
def onpress(event):
global x_press, y_press
x_press = int(event.xdata) if (event.xdata != None) else None
y_press = int(event.ydata) if (event.ydata != None) else None
def onrelease(event):
global x_press, y_press
x_release = int(event.xdata) if (event.xdata != None) else None
y_release = int(event.ydata) if (event.ydata != None) else None
if (x_press != None and y_press != None and x_release != None and y_release != None):
(xs, xe) = (x_press, x_release+1) if (x_press <= x_release) else (x_release, x_press+1)
(ys, ye) = (y_press, y_release+1) if (y_press <= y_release) else (y_release, y_press+1)
print("Slice [{0}:{1},{2}:{3}] will be set to zero".format(xs, xe, ys, ye))
rand_field[ys:ye, xs:xe] = 0.
cm.set_array(rand_field.ravel())
event.canvas.draw()
x_press = None
y_press = None
cid_press = fig.canvas.mpl_connect('button_press_event' , onpress )
cid_release = fig.canvas.mpl_connect('button_release_event', onrelease)
pl.show()
|
Split one large .xml file in more .xml files (python)
Question: I've been trying to split one large .xml file in more .xml files in python for
a few days now. The thing is I haven't really succeeded yet. So here I am
asking for your help.
My large .xml file looks like this:
<Root>
<Testcase>
<Info1>[]<Info1>
<Info2>[]<Info2>
</Testcase>
<Testcase>
<Info1>[]<Info1>
<Info2>[]<Info2>
<Testcase>
...
...
...
<Testcase>
<Info1>[]<Info1>
<Info2>[]<Info2>
<Testcase>
</Root>
It has over 2000 children and what I would like to do is to parse this .xml
file and split in smaller .xml files with 100 children each. That would result
in 20 new .xml files.
How can I do that?
Thank you!
L.E.:
I've tried to parse the .xml file using xml.etree.ElementTree
import xml.etree.ElementTree as ET
file = open('Testcase.xml', 'r')
tree = ET.parse(file)
total_testcases = 0
for Testcase in root.findall('Testcase'):
total_testcases+=1
nr_of_files = (total_testcases/100)+1
for i in range(nr_of_files+1):
tree.write('Testcase%d.xml' % (i), encoding="UTF-8")
The thing is I don't know how to specifically get only the Testcases and copy
them to another file...
Answer: Actually, root.findall('Testcase') will return a list of "Testcase" sub
elements. So what need to do is:
1. create root
2. add sub elements to root.
Here is example:
>>> tcs = root.findall('Testcase')
>>> tcs
[<Element 'Testcase' at 0x23e14e0>, <Element 'Testcase' at 0x23e1828>]
>>> len(tcs)
2
>>> r = ET.Element('Root')
>>> r.append(tcs[0])
>>> ET.tostring(r, 'utf-8')
'<Root><Testcase>\n <Info1>[]</Info1>\n <Info2>[]</Info2>\n </Testcase>\n </Root>'
|
How to modify SPSS output files with Python?
Question: I'm making custom tables in SPSS, but when the cell values (percentages) are
rounded to 1 decimal, they sometimes add up to 99,9 or 100,1 in stead of
100,0. My boss asked my to have everything neatly add up to 100. This means
slightly changing some values in the output tables.
I wrote some code to retrieve cell values from tables, which works fine, but I
cannot find any method or class that allows me to change cells in already
generated output. I've tried things like :
Table[(rij,6)] = CellText.Number(11)
and
SpssDataCells[(rij,6)] = CellText.Number(11)
but it keeps giving me "AttributeError: 'SpssClient.SpssTextItem' object has
no attribute 'DataCellArray'"
How do I succesfully change cell values of output tables in SPSS?
My code so far:
import SpssClient, spss
# Python verbinden met SPSS.
SpssClient.StartClient()
OutputDoc = SpssClient.GetDesignatedOutputDoc()
OutputItemList = OutputDoc.GetOutputItems()
# Laatste tabel pakken.
lastTab = OutputItemList.Size()-2
OutputItem = OutputItemList.GetItemAt(lastTab)
Table = OutputItem.GetSpecificType()
SpssDataCells = Table.DataCellArray()
# For loop. Voor iedere rij testen of de afgeronde waarden optellen tot 100.
# Specifieke getallen pakken.
rij=0
try:
while (rij<20):
b14 = float(SpssDataCells.GetUnformattedValueAt(rij,0))
z14 = float(SpssDataCells.GetUnformattedValueAt(rij,1))
zz14 = float(SpssDataCells.GetUnformattedValueAt(rij,2))
b15 = float(SpssDataCells.GetUnformattedValueAt(rij,4))
z15 = float(SpssDataCells.GetUnformattedValueAt(rij,5))
zz15 = float(SpssDataCells.GetUnformattedValueAt(rij,6))
print [b14,z14,zz14,b15,z15,zz15]
rij=rij+1
except:
print 'Einde tabel'
Answer: The
[`SetValueAt`](http://www-01.ibm.com/support/knowledgecenter/SSLVMB_21.0.0/com.ibm.spss.statistics.python.help/python_scripting_spsslabels_setvalueat.htm?lang=en)
method is what you require to change the value of a cell in a table.
_PS. I think your boss should focus on more important things than to spend
billable time on having percentages add up neatly to 100% (due to rounding).
Also ensure you are using as many decimal point precision as possible in your
calculations so to minimize this "discrepancy"._
## Update:
Just to give an example of what you can do with manipulation like this (beyond
fixing round errors):
[](http://i.stack.imgur.com/jobMp.png)
The table above shows the Share of Voice (SoV) of a Respiratory drug brand
(R3) and it's rank among all brands (first two columns of data) and SoV & Rank
also within it's same class of brands only (third and forth column). This is
compared against previous month (July 15) and if the rank has increased then
it is highlighted in green and an upward facing arrow is added and if declined
in rank then highlighted in red and downward red facing arrow added. Just adds
a little, color and visualization to what otherwise can be dull tables.
|
Error trying to open JSON tweet file
Question: I'm getting the following error when attempting to open a json file.
Traceback (most recent call last):
File "C:\Python34\test.py", line 5, in <module>
data = json.load(data_file)
File "C:\Python34\lib\json\__init__.py", line 268, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Python34\lib\json\__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "C:\Python34\lib\json\decoder.py", line 346, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 8300 column 1 (char 157 - 30292811)
This is what I"m doing to open the file in idle:
import json
with open('three_minutes_tweets.json','r', encoding="utf-8") as data_file:
data = json.load(data_file)
print(data_file)
The file is a tweet sample file and looks likes simple dictionaries of
dictionaries. Thank you
Answer: The error message is telling you exactly what the problem is. There is extra
data starting at character 157. In other words, you have invalid JSON data.
There is nothing wrong with your code.
|
How to get a value from json dictionary in python?
Question: The result of running my code is something like:
b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}'
How can I actually get the value of [username] from this response ?
Answer: Use the `json` module to convert your data to json and then it's a simple
access with `get` after that. Observe the demo below with your data structure:
# Python 2 approach
In [5]: import json
In [6]: a = json.loads(b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}')
In [7]: a
Out[7]:
{u'available': False,
u'callback_url': u'http://www.twitter.com/',
u'failed_reason': None,
u'status': u'unavailable',
u'username': u'test'}
In [8]: a.get('username')
Out[8]: u'test'
# Python 3 Approach
You have to be careful in Python 3 as json expects a string, therefore for
your particular case you need to decode `utf-8`. So this example works in
Python 3 as such:
>>> a = b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}'
>>> a = a.decode('utf-8')
>>> import json
>>> a = json.loads(a)
>>> a.get('username')
'test'
Here is Python 2 information on
[json](https://docs.python.org/2/library/json.html)
Here is Python 3 information on
[json](https://docs.python.org/3/library/json.html)
|
How to create a simple message box with a Python script a plattform-independend way?
Question: I have simple Python3-script. It is not a application - just a helper script.
Normaly it would do its job without any human readable output. But when an
error happens I want to have a message window.
I know there are some unixoid commandline tools doing that (`zenity`). Maybe
there is a Python3 package doing the same?
Answer: If all you need is the messagebox then you can use
import tkinter as tk
from tkinter.messagebox import showerror
tk.Tk().withdraw() #Hide window that appears with message
showerror('Title', 'Content') #display message
|
Python going through links randomly in a list
Question: so here is my code
import random
import webbrowser
results = []
with open("al.txt") as inputfile:
for line in inputfile:
results.append(line.strip().split(','))
x = (random.choice(results))
webbrowser.open(x)
i tried to print out what's inside of the random and it's like this:
[["youtube.com"], ["google.com"]]
so i think the "[" key is causing this
i also tried to use it like this in another script
import webbrowser
webbrowser.open(url)
it is working as expected so when i do
webbrowser.open(x)
it just recognize x as ["youtube.com"] or "["youtube.com"]"
how can i solve this problem
Answer:
results.append(line.strip().split(','))
`split` returns a list, so `appending` it to `results` gives you a list of
list of strings, instead of a list of strings.
Use `extend` instead of `append`, so the list remains one dimensional.
results.extend(line.strip().split(','))
|
How to check if a MySQL connection is open in Python?
Question: I am using MySQLdb (<http://mysql-python.sourceforge.net/>). It seems that
connection.open and connection.sqlstate() do not work for me. Below is the
code:
def open(self):
#TODO: check the connection's status
# self.__conn.open OR self.__conn.sqlstate()
try:
print "sqlstate:"+str( self.__conn.sqlstate() )
print "open?"+str( self.__conn.open )
return "00000" == self.__conn.sqlstate()
except Exception as e:
print "Exception while checking MYSQL Connection:"+str(e)
return False
But when I ran "sudo service mysql stop; sleep 60; sudo service mysql start;"
to do the testing. The output is as following. It seems that the following
piece of output repeated for ever (I killed the process finally). When the
server is down, connection.open is 1 and connection.sqlstate() is 00000. But
when server is up, connection.executemany() still throw exceptions. Any ideas?
Thanks.
...
2015-10-20 14:09:06 Exception while executing statement:(2006, 'MySQL server has gone away')
2015-10-20 14:09:06 sqlstate:00000
2015-10-20 14:09:06 open?1
2015-10-20 14:09:06 Reconnected to MYSQL.
2015-10-20 14:09:06 Exception while executing statement:(2006, 'MySQL server has gone away')
2015-10-20 14:09:06 sqlstate:00000
2015-10-20 14:09:06 open?1
2015-10-20 14:09:06 Reconnected to MYSQL.
2015-10-20 14:09:06 Exception while executing statement:(2006, 'MySQL server has gone away')
2015-10-20 14:09:06 sqlstate:00000
2015-10-20 14:09:06 open?1
2015-10-20 14:09:06 Reconnected to MYSQL.
2015-10-20 14:09:06 Exception while executing statement:(2006, 'MySQL server has gone away')
2015-10-20 14:09:06 sqlstate:00000
2015-10-20 14:09:06 open?1
...
**UPDATE**
I tested again. The output is as following. each sleep is 10 seconds. The
output is OK except the connection.open is 1 even when server is down. But
connection.sqlstate() is right (HY000).
2015-10-20 14:35:56 Exception while executing statement:(2006, 'MySQL server has gone away')
2015-10-20 14:35:56 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:35:56 sqlstate:HY000
2015-10-20 14:35:56 open?1
2015-10-20 14:35:56 sleeping...
2015-10-20 14:36:06 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:06 sqlstate:HY000
2015-10-20 14:36:06 open?1
2015-10-20 14:36:06 sleeping...
2015-10-20 14:36:16 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:16 sqlstate:HY000
2015-10-20 14:36:16 open?1
2015-10-20 14:36:16 sleeping...
2015-10-20 14:36:26 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:26 sqlstate:HY000
2015-10-20 14:36:26 open?1
2015-10-20 14:36:26 sleeping...
2015-10-20 14:36:36 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:36 sqlstate:HY000
2015-10-20 14:36:36 open?1
2015-10-20 14:36:36 sleeping...
2015-10-20 14:36:46 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:46 sqlstate:HY000
2015-10-20 14:36:46 open?1
2015-10-20 14:36:46 sleeping...
2015-10-20 14:36:56 Exception while ping:(2003, "Can't connect to MySQL server on '10.1.1.25' (111)")
2015-10-20 14:36:56 sqlstate:HY000
2015-10-20 14:36:56 open?1
2015-10-20 14:36:56 sleeping...
2015-10-20 14:37:06 sqlstate:00000
2015-10-20 14:37:06 open?1
2015-10-20 14:37:06 Reconnected to MYSQL.
Answer: Try this-
import MySQLdb
def main():
# Connect to the MySQL database
db = MySQLdb.connect(host = 'z.cs.utexas.edu', user = 'userName', passwd = 'password', db = 'dbName')
# Check if connection was successful
if (db):
# Carry out normal procedure
print "Connection successful"
else:
# Terminate
print "Connection unsuccessful"
|
Plot text is lost when importing matplotlib images to Microsoft Word 2013
Question: I am using `matplotlib 1.4.3` on `python 2.7` and am saving my plots as ".eps"
files on my linux server.
For my research paper, I need to include these images into `MS Word 2013`
where the text of my research lies. However, when I import the image into MS
word, all the text from the plot is lost e.g. axis labels, tick labels,
legends. Only the non-text parts of the image show up.
I searched multiple forums
I have tried converting the `.eps` file to `.emf` format as well using
<https://cloudconvert.com/eps-to-emf> and few other similar services, but the
issue with this process is that the font of my text changes. I have also used
`Inkscape 0.91`for converting `.eps` to `.emf` and there also the quality is
not good (the font changes, the grey shades become shades of red) and I am not
able to replicate the exact style as was there in `.eps` file.
Has anyone been able to solve this, issue ?
Answer: What seems to work is that I save as .png, then import in Powerpoint, select
and copy it and finally paste special in Word as .jpeg or .gif
|
how to handle os.system sigkill signal inside python?
Question: I have a python script where I call a lengthy process from the operating
system after a long while the process that I call get terminated by the system
by SIGKILL signal ,
is it possible to handle this from inside python like try and catch situation
??
what method should I use to solve this issue it is very important that this
process keep on running as long as possible without any interruptions
Answer: [There is no way to handle `SIGKILL`](http://man7.org/linux/man-
pages/man7/signal.7.html)
> The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored.
If you're looking to handle system shutdown gracefully, you should be handling
`SIGTERM` or a startup/shutdown script such as an [upstart
job](http://upstart.ubuntu.com/getting-started.html) or a [init.d
script](http://www.tldp.org/HOWTO/HighQuality-Apps-HOWTO/boot.html).
|
Reading a specific number of lines of a .csv in python
Question: I have a csv file that I am trying to read into python and then I want to
store the first two columns in a variable called name and gender. The current
code I am using is the following:
import csv
infile = open('blue.csv', 'r')
csvfile = csv.reader(infile)
name = []
gender = []
for row in csvfile:
name.append(row[0])
gender.append(row[1])
There are two problems I am encountering:
1) The csv file has headers so I don't want those included inside the
variables when I store the columns
2) I am missing the gender for the last row of the csv file and so I don't
want to include the last line of the csv file when I store it in a variable.
I am an `R` programmer and so to me, the way I would get around this is to
read in the file excluding the first row and last row but I am unsure of how
to do this in python, or better yet, if there is a better/smarter alternative.
If it helps, here is what a mock dataset would look like:
Name, Gender
Bob, Male
Susan, Female
Doug,
Answer: You wrote
> I am an R programmer and so to me, the way I would get around this is to
> read in the file excluding the first row and last row but I am unsure of how
> to do this in python
This can be done with
[`readlines`](https://docs.python.org/2/tutorial/inputoutput.html) and [list
slicing](https://docs.python.org/2.3/whatsnew/section-slices.html) like so:
open('foo.csv').readlines()[1: -1]
Furthermore, note that
[`csv.reader`](https://docs.python.org/2/library/csv.html) takes both a file
object and a list:
> csvfile can be any object which supports the iterator protocol and returns a
> string each time its next() method is called — file objects and list objects
> are both suitable.
So you can just use:
for l in csv.reader(open('foo.csv').readlines()[1: -1]):
...
|
python: file paths no longer work with imp
Question: I recently started using imports to better organize my code in python. My
original code in `file1.py` used the line:
def foo():
files = [f for f in os.listdir('.') if os.path.isfile(f)]
print files
#do stuff here....
Which referenced all the files in the same folder as the code, `print files`
showing the correct output as an array of filenames.
However, I recently changed the directory structure to something like this:
./main.py
./folder1/file1.py
./folder1/data_file1.csv
./folder1/data_file2.csv
./folder1/......
And in main.py, I use:
import imp
file1 = imp.load_source('file1', "./folder1/file1.py")
.
.
.
file1.foo()
Now, `files` is an empty array. What happened? I have tried absolute filepaths
in addition to relative. Directly declaring an array with `data_file1.csv`
works, but I can't get anything else to work with this import.
What's going on here?
Answer: When you do `os.listdir('.')` , you are trying to list the contents of `'.'`
(which is the current directory) , but this does not need to be the directory
in which the script resides, it would be the directory in which you were in
when you ran the script (unless you used `os.chdir()` inside the python
script).
You should not depend on the current working directory , instead you can use
`__file__` to access the path of the current script, and then you can use
[`os.path.dirname()`](https://docs.python.org/2/library/os.path.html#os.path.dirname)
to get the directory in which the script resides.
Then you can use
[`os.path.join()`](https://docs.python.org/2/library/os.path.html#os.path.join)
to join the paths of the files you get from `os.listdir()` with the directory
of the script and check if those paths are files to create your list of files.
Example -
def foo():
filedir = os.path.dirname(__file__)
files = [f for f in (os.path.join(filedir, fil) for fil in os.listdir(filedir)) if os.path.isfile(f)]
print files
#do stuff here....
|
python 3 import TypeError error
Question: I'm having a bizarre app startup error and was wondering if someone might know
how to debug/resolve it.
I'm running a Flask app using python 3. I kick things off by running: `python
manage.py runserver` and the stacktrace below is generated:
Traceback (most recent call last):
File "/projectbase/manage.py", line 19, in <module>
create_tables()
File "/projectbase/myproject/__init__.py", line 15, in create_tables
from myproject.models.util import Weekday, weekday_type
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 742, in __exit__
File "<frozen importlib._bootstrap>", line 742, in <genexpr>
TypeError: an integer is required (got type NoneType)
**_The problem is, when I run it in a debugger and setup breakpoints the
problem goes away. But if I run it without debugging the problem exists._**
For further reference the `create_tables()` function called by manage.py
code/file looks like:
from myproject.app import app
from myproject.app import db
def create_tables():
from myproject.models.util import Weekday, weekday_type
from myproject.models.activity import Activity, activities_tags, Occurrence, Tag
db.create_all()
And further `Weekday` and `weekday_type` code in question looks like:
from myproject.app import db
from myproject.models.enum import DeclEnum
class Weekday(DeclEnum):
Sunday = 'Sunday', {'offset': 0}
Monday = 'Monday', {'offset': 1}
Tuesday = 'Tuesday', {'offset': 2}
Wednesday = 'Wednesday', {'offset': 3}
Thursday = 'Thursday', {'offset': 4}
Friday = 'Friday', {'offset': 5}
Saturday = 'Saturday', {'offset': 6}
weekday_type = Weekday.db_type(metadata=db.metadata)
weekday_type.register_with_psycopg(db.engine)
The `DeclEnum` type I use is basically just copied from this
[gist](https://gist.github.com/mbirtwell/aaccdb7972e1a7ed094b).
The only adjustment I made to the code was to make `DeclEnum` a little more
flexible so it can take a dictionary of values rather than just a `value` and
`description`. Other than that I changed nothing.
Any ideas what's going on here? Since the act of debugging it _fixes_ things,
I don't know how to go about getting to the bottom of the issue.
Thanks in advance.
Answer: The error is misleading.
Looking at the [gist](https://gist.github.com/mbirtwell/aaccdb7972e1a7ed094b)
I linked to in the original question
The method `register_with_psycopg()` works only if the enum type has first
been created in the database. I was calling the method before the type had
been created. By changing the ordering of things during app startup the error
went away.
|
DataFrame object has no attribute 'sample'
Question: Simple code like this won't work anymore on my python shell:
import pandas as pd
df=pd.read_csv("K:/01. Personal/04. Models/10. Location/output.csv",index_col=None)
df.sample(3000)
The error I get is:
AttributeError: 'DataFrame' object has no attribute 'sample'
DataFrames definitely have a sample function, and this used to work. I
recently had some trouble installing and then uninstalling another
distribution of python. I don't know if this could be related.
I've previously had a similar problem when trying to execute a script which
had the same name as a module I was importing, this is not the case here, and
pandas.read_csv is actually working.
What could cause this?
Answer: As given in the [documentation of
`DataFrame.sample`](http://pandas.pydata.org/pandas-
docs/version/0.17.0/generated/pandas.DataFrame.sample.html) -
> **`DataFrame.sample(n=None, frac=None, replace=False, weights=None,
> random_state=None, axis=None)`**
>
> Returns a random sample of items from an axis of object.
>
> **New in version 0.16.1.**
(Emphasis mine).
`DataFrame.sample` is added in `0.16.1` , you can either -
1. Upgrade your `pandas` version to latest, you can use `pip` for that, Example -
pip install pandas --upgrade
2. Or if you don't want to upgrade, and want to sample few rows from the dataframe, you can also use [`random.sample()`](https://docs.python.org/2/library/random.html#random.sample), Example -
import random
num = 100 #number of samples
sampleddata = df.loc[random.sample(list(df.index),num)]
|
Embedded Python in C++ Threading error
Question: Recently, I needed to create a tool to scrape a page's source so I could parse
out of a public database, for a project that I'm working on. Python seemed
like an easy solution but it was a pain getting it up and running and
currently I have it half working (saves source to file instead of returning).
When I run my c++ code I get a strange error...
Exception ignored in: <module 'threading' from 'C:\\Python34\\Lib\\threading.py'
>
Traceback (most recent call last):
File "C:\Python34\Lib\threading.py", line 1293, in _shutdown
t = _pickSomeNonDaemonThread()
File "C:\Python34\Lib\threading.py", line 1300, in _pickSomeNonDaemonThread
for t in enumerate():
File "C:\Python34\Lib\threading.py", line 1270, in enumerate
return list(_active.values()) + list(_limbo.values())
TypeError: an integer is required (got type NoneType)
My Python Code:
import urllib.request
import sys
def run(a):
req = urllib.request.Request(a)
res = urllib.request.urlopen(req)
d = str(res.read())
with open('temp.dat', 'w') as outfile:
for x in range(0, len(d)):
outfile.write(d[x])
The above code works correctly and doesn't issue any errors, so I feel that
the mistake is somewhere in my c++ implementation. Anyways, I feel that it is
worth mentioning that it successfully saves the websites (parameter a) source
code to the 'temp.dat' file, I'm just trying to get rid of the error
reporting.
My C++ code:
void pyCall(string url, string outfile, char* mod = "Scrape", char * dat = "run")
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue, *pOutfile, *pURL;
int i;
Py_Initialize();
PyObject* sysPath = PySys_GetObject((char*)"path");
PyList_Append(sysPath, PyUnicode_FromString("."));
pName = PyUnicode_FromString(mod);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL)
{
pFunc = PyObject_GetAttrString(pModule, dat);
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc))
{
/* pValue reference stolen here: */
pArgs = Py_BuildValue("(s)", url.c_str());
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL)
{
printf("Result of call: %ld\n", PyLong_AsLong(pValue));
Py_DECREF(pValue);
}
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
Py_Finalize();
}
Now this code is pretty standard and is a 'cookie cutter' example of the code
Python has on their API at
<https://docs.python.org/3.5/extending/embedding.html>; The only differences
is the way that I pass the arguments and appending the path at the beginning.
Any help would be greatly appreciated.
Answer: Just went outside for a fast break and collected my thoughts about what the
error could be and managed to fix it; sorry for the spam. The error was that
my python function doesn't return anything and I was trying to assign it to
pValue.
TypeError: an integer is required (got type NoneType)
I just took out the assignment in my c++ code and it worked.
PyObject_CallObject(pFunc, pArgs);
|
ElasticSearch using python
Question: I am using python to import file into `ElasticSearch`. Simple data I can
Import but facing issue when there is combination of letters and numbers as
well special characters.
I am using below script:
from datetime import datetime
from elasticsearch import Elasticsearch
import os
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
f = open("E:\\ElasticSearch\\test.txt",'r')
fulldata = f.readlines()
f.close()
del fulldata[0]
for line in fulldata:
array = line.split(",")
guid = array[0]
senderid = array[1]
campaign = array[2]
json_body = "{\"guid\" : \""+ guid+"\", \"senderid\" : \""+ senderid+"\", \"campaign\" : "+ str(campaign)+"}}"
print json_body
res = es.index(index="mytest", doc_type="msg", id=guid, body=json_body)
test.txt file contain data like
guid senderid campaign
26fac319-604b-11e5-b1fe,003001,Weekday_EGV_21Sept_4pm_Round2_Tier1_Part1,
I am getting error like
elasticsearch.exceptions.RequestError: TransportError<400, u"MapperParsingException [failed to parse ]; nested: JsonParseException [Unrecognized token 'Weekday_EGV_21Sept_4pm_Round2_Tired1_Part1' : was excepting ('true', 'false' or 'null')\n at [Source: [B@b5685ce; line: 1, column:95}}; ")
Answer: Looking at your code it appears there are 2 errors with your JSON. In it's
original for it produces the follwoing string:
{"guid" : "26fac319-604b-11e5-b1fe", "senderid" : "003001", "campaign" : Weekday_EGV_21Sept_4pm_Round2_Tier1_Part1}}
You are missing quotes around that final field value of `campaign` and you
have an extra `}` at the end. If you make the following change:
json_body = "{\"guid\" : \""+ guid+"\", \"senderid\" : \""+ senderid+"\", \"campaign\" : \""+ str(campaign)+"\"}"
it should resolve the JsonParseException error.
|
How to write to named pipe with the threading module in Python?
Question: I am trying to write a program which communicates to an external program
through named pipes. The python script does not know when the external program
opens up the named pipe/file for reading, so the python script need to open
the pipe in blocking mode, see
[open](http://pubs.opengroup.org/onlinepubs/007908799/xsh/open.html). If the
python script opens in non-blocking mode and the external program has not
opened for reading, the open statement will result in an error.
So to open in blocking mode, the python script could open the named pipe in a
separate thread, and I have tried the threading module. In the below example I
just read from the named pipe in the main thread, but it produces the same
error:
import threading
import os
pipe_name = 'pipe_test'
class WriterNamedPipe(threading.Thread):
def __init__(self, filepath, input):
'''
Write: generate that will output each line of input
'''
# Inherit
threading.Thread.__init__(self, verbose = True)
self.daemon = False
self.filepath = filepath
self.input = input
self.start()
def run(self):
# Open blockingly
with open(self.filepath, 'w') as f:
f.write(self.input)
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
WriterNamedPipe(pipe_name, '1\n' * 100)
with open(pipe_name, 'r') as f:
print f.read()
This would results in a hang/freeze:
MainThread: <WriterNamedPipe(Thread-1, initial)>.start(): starting thread
Thread-1: <WriterNamedPipe(Thread-1, started 1078922160)>.__bootstrap(): thread started
Thread-1: <WriterNamedPipe(Thread-1, started 1078922160)>.__bootstrap(): normal return
Compilation hangup
However, a similar example from [here](http://www.python-course.eu/pipes.php)
works, but with `os.fork`:
import os, time, sys
pipe_name = 'pipe_test'
def child( ):
pipeout = os.open(pipe_name, os.O_WRONLY)
counter = 0
while True:
time.sleep(1)
os.write(pipeout, 'Number %03d\n' % counter)
counter = (counter+1) % 5
def parent( ):
pipein = open(pipe_name, 'r')
while True:
line = pipein.readline()[:-1]
print 'Parent %d got "%s" at %s' % (os.getpid(), line, time.time( ))
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
pid = os.fork()
if pid != 0:
parent()
else:
child()
Why is the example with the threading module hanging?
Answer: This does probably not work due to the
[GIL](http://www.dabeaz.com/python/UnderstandingGIL.pdf). The open statement
in the thread blocks the whole program. This could be avoided by using
[multiprocessing](https://docs.python.org/2/library/multiprocessing.html)
module instead.
|
Convert .txt to .xls from nested folders
Question: I found a Python script to convert .txt to .xls and it is working: [Converting
multiple tab-delimited .txt files into multiple .xls
files](http://stackoverflow.com/questions/17110674/converting-multiple-tab-
delimited-txt-files-into-multiple-xls-files) :
import glob
import csv
import xlwt
import win32com.client as win32
for filename in glob.glob("C:\Users\MSI\Desktop\Python Lab\AGR\\*.txt"):
spamReader = csv.reader((open(filename, 'rb')), delimiter='|',quotechar='"')
encoding = 'latin1'
wb = xlwt.Workbook(encoding=encoding)
sheet=xlwt.Workbook()
sheet = wb.add_sheet('sheet 1')
newName = filename
for rowx, row in enumerate(spamReader):
for colx, value in enumerate(row):
sheet.write(rowx, colx, value)
wb.save(newName.replace('.txt','.xls'))
print "Done"
However, it can only convert the file path but could not convert any files in
nested folders.
How I may modify it to include nested folders?
Answer: Something like the following should work. It uses Python's
[`os.walk`](https://docs.python.org/2/library/os.html?highlight=os.walk#os.walk)
function to traverse all sub folders:
import xlwt
import os
path = r'C:\Users\MSI\Desktop\Python Lab\AGR'
for root, dirs, files in os.walk(path):
for filename in files:
name, ext = os.path.splitext(filename)
if ext.lower() == '.txt':
source = os.path.join(root, filename)
dest = os.path.join(root, name + '.xls')
with open(source, 'rb') as f_input:
spamReader = csv.reader(f_input, delimiter='|',quotechar='"')
wb = xlwt.Workbook(encoding='latin1')
sheet = xlwt.Workbook()
sheet = wb.add_sheet('sheet 1')
for rowx, row in enumerate(spamReader):
for colx, value in enumerate(row):
sheet.write(rowx, colx, value)
wb.save(dest)
print "Done"
|
ImportError: No module named django_crontab
Question: I am trying to set up some cron jobs in Linux using django-crontab 0.6 (which
is installed). I have added 'django_crontab' to INSTALLED_APPS in settings,
and I have specified the jobs using:
CRONJOBS = [
('0 0 * * *', 'proj.app.cron.update_entries'),
('0 * * * *', 'proj.app.cron.delete_queries')
]
When I try to add the jobs using the command:
python3 manage.py crontab add
...I get an error. Here is the traceback:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.2/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.2/dist-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/usr/local/lib/python3.2/dist-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.2/dist-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/usr/local/lib/python3.2/dist-packages/django/apps/config.py", line 86, in create
module = import_module(entry)
File "/usr/lib/python3.2/importlib/__init__.py", line 124, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/usr/lib/python3.2/importlib/_bootstrap.py", line 824, in _gcd_import
raise ImportError(_ERR_MSG.format(name))
ImportError: No module named django_crontab
I am using Django 1.8.4.
Answer: Looks like there awas a bug about it: <https://github.com/kraiz/django-
crontab/issues/20>
> "the correct module_path is myapp.cron not myproj.myapp.cron"
Could you please try the following code:
CRONJOBS = [
('0 0 * * *', 'app.cron.update_entries'),
('0 * * * *', 'app.cron.delete_queries')
]
?
|
Why should I use CamelCase for namedtuple?
Question: Assuming this code snippet (ipython)
In [1]: from collections import namedtuple
In [2]: type(namedtuple)
Out[2]: function
you can see that factory function `namedtuple` is a `function`, of course. I
can't see any hint in PEP-8 to use the naming convention for classes in that
case. I can only see that the
[documentation](https://docs.python.org/dev/library/collections.html#collections.namedtuple)
treating it like a class as a naming convention.
Why should one use the naming convention for classes in that case?
Answer: You're referring to the use of the name `Point` for the type returned by
`namedtuple`. `namedtuple` is a function alright, but it returns a class (a
thing that has the type `type`). And by [PEP-8, class names should look
LikeThis](https://www.python.org/dev/peps/pep-0008/#class-names).
In [1]: from collections import namedtuple
In [2]: Point = namedtuple('Point', ['x', 'y'])
In [3]: type(Point)
Out[3]: type
|
Python-opencv Error import cv2 ImportError: dlopen after update of OS X EI Captain
Question: I have this error when import cv2 after update the system of OS X EI Captain
import cv2
ImportError: dlopen(/usr/local/lib/python2.7/site-packages/cv2.so, 2): Library not loaded: lib/libopencv_shape.3.0.dylib
Referenced from: /usr/local/lib/python2.7/site-packages/cv2.so
Reason: unsafe use of relative rpath lib/libopencv_shape.3.0.dylib in /usr/local/lib/python2.7/site-packages/cv2.so with restricted binary
I have tried the method in [Cannot import cv2 because unsafe use of relative
rpath lib in cv2.so with restricted
binary](https://github.com/Itseez/opencv/issues/5447)
rebuild build use cmake -D BUILD_SHARED_LIBS=OFF -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local ..
But it doesn't work.
Do you have any idea with this error?
Answer: This is because of SIP (System Integrity Protection) introduced in El Capitan
[link](https://support.apple.com/en-us/HT204899).
I too faced the same issue and came across this SO
[link](http://stackoverflow.com/questions/31343299/mysql-improperly-
configured-reason-unsafe-use-of-relative-path). Basically, the relative path
dependencies listed in the shared libs need to be changed to absolute paths.
There are huge number of these to be corrected in opencv libraries. You can
optionally disable SIP. I preferred to change the links instead and wrote the
following python snippet.
Change the ABSPATH and LIBPATHS if required. It can be used for any other
libraries as well. It will create rPathChangeCmd.txt which you can paste in
the terminal. It will also create rPathChangeErr.txt in case of any errors. I
would suggest check error file (if created) before pasting the commands.
import glob
import subprocess
import os.path
ABSPATH = "/usr/local/lib/" # absolute path to relative libraries
# libraries to correct
LIBPATHS = ['/usr/local/lib/python2.7/site-packages/cv2.so', '/usr/local/lib/libopencv*']
PREFIX = 'sudo install_name_tool -change '
assert(ABSPATH.startswith('/') and ABSPATH.endswith('/'),
'please provide absolute library path ending with /')
libs = []
for path in LIBPATHS:
libs += glob.glob(path)
cmd = []
err = []
for lib in libs:
if not os.path.isfile(lib):
err.append(lib+" library not found") # glob should take care
datastr = subprocess.check_output(['otool','-l','-v', lib])
data = datastr.split('\n')
for line in data:
ll = line.split()
if not ll: continue
if (ll[0] == 'name' and ll[1].endswith('.dylib') and not ll[1].startswith('/')):
libname = ll[1].split('/')[-1]
if os.path.isfile(ABSPATH+libname):
cmd.append(PREFIX+ll[1]+" "+ABSPATH+libname+' '+lib)
else:
err.append(ABSPATH+libname+" does not exist, hence can't correct: "+ll[1]+" in: "+lib)
ohandle = open("rpathChangeCmd.txt", 'w')
for lib in cmd:
ohandle.write(lib+'\n')
ohandle.close()
if err:
ehandle = open("rpathChangeErr.txt", 'w')
for e in err:
ehandle.write(e+'\n')
ehandle.close()
|
Bulls and Cows Game - Python programming for beginners
Question: I am a beginer programming Python and for a evaluation assignment I was asked
to program a Bulls and Cows game using very simple code. I have some code
already written, but can't seem to make the function work. The function should
be able to compare the four digit number the user wrote (num_guess) to the
random number generated by the program (stored in a list called num). I can
input the value, but have no further feedback from the program. Could you
please check my code and help me? Thanks!
import random
guess = raw_input("What is your guess? ")
if (len(guess) != 4):
guess = raw_input("Your guess must be 4 characters long! What is your guess?")
num_guess = []
for c in guess:
num_guess.append(int(c))
def compare(num_guess):
num = []
for i in range(4):
n = random.randint(0, 9)
while n in num:
n = random.randint(0, 9)
num.append(n)
if num_guess == num:
print "Congratulations! Your guess is correct"
output = []
if num_guess[0] == num [0]:
output.append["B"]
else:
output.append["C"]
if num_guess[1] == num [1]:
output.append["B"]
else:
output.append["C"]
if num_guess[2] == num [2]:
output.append["B"]
else:
output.append["C"]
if num_guess[3] == num [3]:
output.append["B"]
else:
output.append["C"]
return output
nguesses = 0
while nguesses < 11:
nguesses = nguesses + 1, compare
Answer: Without giving you the corrected code you will want to call the function at
the end of your code. If you want to see result do:
print compare(num_guess)
This will show you an additional issue with all of these parts
output.append[]
I'm not sure if it is just how you pasted it but you may want to clean up the
indentation. Also:
while n in num:
n = random.randint(0, 9)
This above section is not needed. Have fun and figure out how to make it work
well.
|
Plotting a function with matplotlib
Question: So I have defined a function, and for some reason the terminal is returning
the following error:
TypeError: only length-1 arrays can be converted to Python scalars
I'm not sure what I have done wrong exactly?
Here is my self-contained function with corresponding plot:
import matplotlib
import math
import numpy
import matplotlib.pyplot as pyplot
import matplotlib.gridspec as gridspec
def rotation_curve(r):
v_rotation = math.sqrt((r*(1.33*(10**32)))/(1+r)**2)
return v_rotation
curve_range = numpy.linspace(0, 100, 10000)
fig = pyplot.figure(figsize=(16,6))
gridspec_layout = gridspec.GridSpec(1,1)
pyplot = fig.add_subplot(gridspec_layout[0])
pyplot.plot(curve_range, rotation_curve(curve_range))
matplotlib.pyplot.show()
Could anyone advise me where I have gone wrong?
Answer: The problem is in the definition of `rotation_curve(r)`. You input and
manipulate a numpy array (`curve_range`), but you do so using a non-vectorized
function `math.sqrt`:
v_rotation = math.sqrt((r*(1.33*(10**32)))/(1+r)**2)
Instead, use `numpy.sqrt` which broadcasts the sqrt operation across every
element in the array. The multiplication and exponentiation operators are
overloaded in numpy arrays, so those should work fine.
def rotation_curve(r):
v_rotation = numpy.sqrt((r*(1.33*(10**32)))/(1+r)**2)
return v_rotation
|
Can't launch ipython after El Capitan upgrade
Question: Does anyone know how to undo the changes to paths and permissions wrought by
upgrading to El Capitan. Specifically, it appears that OS X is now using the
system python instead of my Canopy installation.
These look ok:
Michaels-Mac-mini:~ mellis$ which python
/Users/mellis/Library/Enthought/Canopy_64bit/User/bin/python
Michaels-Mac-mini:~ mellis$ which ipython
/Users/mellis/bin/ipython
But trying to launch ipython fails:
Michaels-Mac-mini:~ mellis$ ipython
Traceback (most recent call last):
File "/Users/mellis/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/pyth on/pkg_resources.py", line 2793, in <module>
working_set.require(__requires__)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 673, in require
needed = self.resolve(parse_requirements(requirements))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 576, in resolve
raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: ipython==0.11
Answer: A complete update of my installed Canopy packages including ipython seems to
have fixed the problem.
|
Error when running Duplicity on AWS Linux
Question: I have installed Duplicity on some AWS EC2 instances using the folowing
command
yum -y install duplicity rsync gpg python python-devel python-pip -- enablerepo=epel
This was based on an approach described here
<https://rtcamp.com/tutorials/backups/duplicity-amazon-s3/>
However, whenever I try to run a duplictiy command, I get the following
command
Traceback (most recent call last): File "/usr/bin/duplicity", line 42, in <module> from duplicity import log ImportError: No module named duplicity
Anyone have any ideas on how to solve this?
Answer: check that your default PYTHONPATH is set up properly. there are very good
howto's out there, so i am not duplicating them. simply search the net.
if not you can add the location where duplicity modules ended up manually via
PYTHONPATH env var.
..ede/duply.net
PS: in my first answer i posted a link, but some clever editor deleted that
"because the link may change in the future".
|
python cffi parsing error when defining a struct
Question: I am trying to use `python-cffi` to wrap C code. The following
`example_build.py` shows an attempt to wrap `lstat()` call:
import cffi
ffi = cffi.FFI()
ffi.set_source("_cstat",
"""
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
""",
libraries=[])
ffi.cdef("""
struct stat {
mode_t st_mode;
off_t st_size;
...;
};
int lstat(const char *path, struct stat *buf);
""")
if __name__ == '__main__':
ffi.compile()
When compile `python example_build.py` will complain that parsing error for
`mode_t st_mode`.
cffi.api.CDefError: cannot parse "mode_t st_mode;"
:4:13: before: mode_t
A similar example given from the
[manual](https://cffi.readthedocs.org/en/latest/overview.html#real-example-
api-level-out-of-line) doesn't have any problems though. What am I missing?
TIA.
Answer: You need to inform CFFI that `mode_t` and `off_t` are some integer types. The
easiest way is to add these lines first in the cdef():
typedef int... mode_t; /* means "mode_t is some integer type" */
typedef int... off_t;
|
Scrape booking.com with Python against AJAX requests
Question: I am trying to scrape data from booking.com and almost everything is working
now but I am not able to get the prices, I read so far that it is because
those prices are loaded via AJAX calls. Here is my code:
import requests
import re
from bs4 import BeautifulSoup
url = "http://www.booking.com/searchresults.pl.html"
payload = {
'ss':'Warszawa',
'si':'ai,co,ci,re,di',
'dest_type':'city',
'dest_id':'-534433',
'checkin_monthday':'25',
'checkin_year_month':'2015-10',
'checkout_monthday':'26',
'checkout_year_month':'2015-10',
'sb_travel_purpose':'leisure',
'src':'index',
'nflt':'',
'ss_raw':'',
'dcid':'4'
}
r = requests.post(url, payload)
html = r.content
parsed_html = BeautifulSoup(html, "html.parser")
print parsed_html.head.find('title').text
tables = parsed_html.find_all("table", {"class" : "sr_item_legacy"})
print "Found %s records." % len(tables)
with open("requests_results.html", "w") as f:
f.write(r.content)
for table in tables:
name = table.find("a", {"class" : "hotel_name_link url"})
average = table.find("span", {"class" : "average"})
price = table.find("strong", {"class" : re.compile(r".*\bprice scarcity_color\b.*")})
print name.text + " " + average.text + " " + price.text
Using `Developers Tools` from Chrome I noticed that the webpage sends a raw
response with all of the data (including prices). After coping the response
content from one of this tabs, there are raw values with prices, so why I
can't retrieve them using my script, how to solve it?
[](http://i.stack.imgur.com/IWFWr.png)
Answer: The first problem is that the site is ill-formed: one `div` is opened in your
table and an `em` is closed. So the `html.parser` cannot find the `strong` tag
containing the price. This you can fix with installing and using `lxml`:
parsed_html = BeautifulSoup(html, "lxml")
The second problem is in your regex. It does not find anything. Change it to
the following:
price = table.find("strong", {"class" : re.compile(r".*\bscarcity_color\b.*")})
Now you will find prices. However some entries do not contain any price thus
your `print` statement will throw an error. To solve this you can change your
`print` to the following:
print name.text, average.text, price.text if price else 'No price found'
And note that you can separate fields to print with comma (`,`) in Python so
you do not need to concatenate them with `+ " " +`.
|
How to install imapclient
Question: I’m trying to use the IMAP client library:
<https://imapclient.readthedocs.org/en/stable/>
I download the zip:
<https://pypi.python.org/pypi/IMAPClient/0.13>
Next I used windows command prompt and pip to install:
Ran: `pip install imapclient`
This placed/created a director in my site-pages directory
`C:\Python27\ArcGIS10.2\Lib\site-packages\IMAPClient-0.13-py2.7.egg`
which I can open and find all the files, but I can’t open IDE and import
imapclient or run the examples without getting the error:
ImportError: No module named imapclient
Any ideas, what I need to do?
Answer: You'll need to make sure your `PYTHONPATH` is set properly:
<https://docs.python.org/2/using/windows.html#configuring-python>
|
No module named serial
Question: and I got a question when I run my Python code.
I installed Python 2.7 on Windows 7, bit 64. I got an error "No module named
serial" when I compiled my code:
import serial
ser = serial.Serial("COM5", 9600)
ser.write("Hello world")
x = ser.readline()
print(x)
I tried many ways to crack this problem, such as installed Canopy to setup
virtual environment, make sure 'pip' is there, no Python v 3.x installed. But
still cannot get it out.
Any advice would be appreciated.
Answer: Serial is not included with Python. It is a package that you'll need to
install separately.
Since you have pip installed you can install serial from the command line
with:
pip install pyserial
Or, you can use a Windows installer from
[here](https://pypi.python.org/pypi/pyserial). It looks like you're using
Python 3 so click the installer for Python 3.
Then you should be able to import serial as you tried before.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.