text
stringlengths 226
34.5k
|
---|
Read in csv file with one column of strings in the middle
Question: I have a csv input file of standard format with a messy header that I am
stripping off, and then an array of 35 columns and 8760 rows. All of this data
is numeric, except the 6th column, which is text. I have tried allowing
`genfromtxt()` to figure this out on its own, but in the end that column is
turned to `nan`s, I believe because there are no quotes.
Currently, I'm reading this array as follows:
WeaData = np.genfromtxt(FileIn, delimiter=",", skip_header=8)
I have tried specifying the column types manually with
WeaData = np.genfromtxt(FileIn, delimiter=",", skip_header=8, dtype=(float,float,float,float,float,str,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float))
and
WeaData = np.genfromtxt(FileIn, delimiter=",", skip_header=8, dtype=[float for n in range(5)]+['S10']+[float for n in range(29)])
but with no luck. I believe my syntax is wrong in the first option, and the
second returns an array of voids. Is there a simple way to do this, preferably
without specifying 35 column types?
Here are three lines of my csv file for reference, after the header I don't
care about.
1966,1,1,1,60,A7A7A7A7*0?0?0?0?0?0?0?0A7A7A7A7A7A7F8F8A7E7,3.9,1.7,86,102400,0,0,264,0,0,0,0,0,0,0,230,2.1,0,0,24.1,77777,0,999999999,8,0.1000,0,88,0.000,0.0,0.0
1966,1,1,2,60,A7A7A7A7*0?0?0?0?0?0?0?0A7A7A7A7A7A7F8F8A7E7,4.4,0.0,73,102500,0,0,265,0,0,0,0,0,0,0,270,3.6,0,0,24.1,77777,0,999999999,8,0.1000,0,88,0.000,0.0,0.0
1966,1,1,3,60,A7A7A7A7*0?0?0?0?0?0?0?0A7A7A7A7A7A7F8F8A7E7,2.8,-0.6,79,102500,0,0,258,0,0,0,0,0,0,0,310,2.1,0,0,24.1,77777,0,999999999,8,0.1000,0,88,0.000,0.0,0.0
I'm using Python V2.7.
Answer: Use `numpy.loadtxt` with the parameter `usecols` for selecting only the
columns containing float numbers.
>>> import numpy as np
>>> cols = range(0,5) + range(6,35)
>>> data = np.loadtxt("data.txt", delimiter=",", usecols=cols, dtype=np.float)
>>> data
[[ 1.96600000e+03 1.00000000e+00 1.00000000e+00 1.00000000e+00
6.00000000e+01 3.90000000e+00 1.70000000e+00 8.60000000e+01
1.02400000e+05 0.00000000e+00 0.00000000e+00 2.64000000e+02
0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e+00 2.30000000e+02
2.10000000e+00 0.00000000e+00 0.00000000e+00 2.41000000e+01
7.77770000e+04 0.00000000e+00 9.99999999e+08 8.00000000e+00
1.00000000e-01 0.00000000e+00 8.80000000e+01 0.00000000e+00
0.00000000e+00 0.00000000e+00]
[ 1.96600000e+03 1.00000000e+00 1.00000000e+00 2.00000000e+00
6.00000000e+01 4.40000000e+00 0.00000000e+00 7.30000000e+01
1.02500000e+05 0.00000000e+00 0.00000000e+00 2.65000000e+02
0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e+00 2.70000000e+02
3.60000000e+00 0.00000000e+00 0.00000000e+00 2.41000000e+01
7.77770000e+04 0.00000000e+00 9.99999999e+08 8.00000000e+00
1.00000000e-01 0.00000000e+00 8.80000000e+01 0.00000000e+00
0.00000000e+00 0.00000000e+00]
[ 1.96600000e+03 1.00000000e+00 1.00000000e+00 3.00000000e+00
6.00000000e+01 2.80000000e+00 -6.00000000e-01 7.90000000e+01
1.02500000e+05 0.00000000e+00 0.00000000e+00 2.58000000e+02
0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e+00 3.10000000e+02
2.10000000e+00 0.00000000e+00 0.00000000e+00 2.41000000e+01
7.77770000e+04 0.00000000e+00 9.99999999e+08 8.00000000e+00
1.00000000e-01 0.00000000e+00 8.80000000e+01 0.00000000e+00
0.00000000e+00 0.00000000e+00]]
If you want to include the 6th column, then you will have to load the matrix
as object, you can't mix floats with strings.
>>> data = np.loadtxt("data.txt", delimiter=",", dtype=np.object)
So if you need this column, load it separately.
|
Python Pandas Histogram Log Scale
Question: I'm making a fairly simple histogram in with pandas using
`results.val1.hist(bins=120)`
which works fine, but I really want to have a log scale on the y axis, which I
normally (probably incorrectly) do like this:
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
plt.plot(np.random.rand(100))
ax.set_yscale('log')
plt.show()
If I replace the `plt` command with the pandas command, so I have:
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
results.val1.hist(bins=120)
ax.set_yscale('log')
plt.show()
results in many copies of the same error:
Jan 9 15:53:07 BLARG.local python[6917] <Error>: CGContextClosePath: no current point.
I do get a log scale histogram, but it only has the top lines of the bars, but
no vertical bars or colors. Am doing something horribly wrong or is this just
not supported by pandas?
EDIT:
From Paul H code I replaced
Added `bottom=0.1` to `hist` call fixes the problem, I guess there is some
kind of divide by zero thing, or something.
Thanks
Answer: Hard to diagnose without any data. The following works for me:
import numpy as np
import matplotlib.pyplot as plt
import pandas
series = pandas.Series(np.random.normal(size=2000))
fig, ax = plt.subplots()
series.hist(ax=ax, bins=100, bottom=0.1)
ax.set_yscale('log')

The key here is that you pass `ax` to the histogram function and you specify
the `bottom` since there is no zero value on a log scale.
|
How to run Flask-Login, Flask-BrowserID and Flask-SQLAlchemy in harmony?
Question: **The Whole Point**
I am attempting to make a fairly basic website with Flask (noob!) and am
running into trouble with the user login system. I've decided that I want to
use Flask-Login, Flask-BrowserID (Mozilla Persona) and SQLAlchemy. I am going
to have Persona be the part that takes care of storing user passwords and
such, I am going to use Flask-Login once the user has been authenticated to
keep track of their sessions and I am going to use SQLAlchemy to store
everything in an sqlite3 db. I've done a lot of bouncing around and I think I
have almost finished these features, but I cannot seem to get back a specific
error.
**Update 1**
Based on the comment by davidism, I had to add db.Model to the User class.
Unfortunately, that solved the first error, but now there is a new one to deal
with. Traceback found below.
**The Question**
What gives? I am obviously missing something, but I cannot seem to find what
that is.
**Resources I have been working with**
* Flask-BrowserID: <https://github.com/garbados/flask-browserid/wiki>
* Flask-Login: <http://flask-login.readthedocs.org/en/latest/>
* Flask-SQLAlchemy: <http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html#a-minimal-application>
* [Is it possible to store Python class objects in SQLite?](http://stackoverflow.com/questions/2047814/is-it-possible-to-store-python-class-objects-in-sqlite)
* SQLAlchemy Docs: <http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html>
* WORKING Flask-BrowserID: init.py">https://github.com/garbados/flask-browserid/blob/master/tests/**init**.py
**Additional Information**
Here is my main.py and index.html I am using with Flask and the Traceback I am
getting:
**MAIN.py**
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from contextlib import closing
import time
from flask.ext.login import LoginManager, UserMixin
from flaskext.browserid import BrowserID
from flask.ext.sqlalchemy import SQLAlchemy
## SETUP
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/flaskr.db'
db = SQLAlchemy(app)
app.config.from_object(__name__)
app.config['BROWSERID_LOGIN_URL'] = "/login"
app.config['BROWSERID_LOGOUT_URL'] = "/logout"
app.config['SECRET_KEY'] = "deterministic"
app.config['TESTING'] = True
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.UnicodeText, unique=True)
firstname = db.Column(db.Unicode(40))
lastname = db.Column(db.Unicode(40))
date_register = db.Column(db.Integer)
bio = db.Column(db.Text)
facebook = db.Column(db.Unicode(1000))
twitter = db.Column(db.Unicode(1000))
website = db.Column(db.Unicode(1000))
image = db.Column(db.LargeBinary)
def __init__(self, email, firstname=None, lastname=None, date_register=None, bio=None, facebook=None, twitter=None,
website=None, image=None):
self.email = email
self.firstname = firstname
self.lastname = lastname
self.date_register = time.time()
self.bio = bio
self.facebook = facebook
self.twitter = twitter
self.website = website
self.image = image
self.email = email
def __repr__(self):
return '<User %r>' % self.email
### Login Functions ###
def get_user_by_id(id):
"""
Given a unicode ID, returns the user that matches it.
"""
for row in db.session.query(User).filter(User.id == id):
if row is not None:
return row.User
return None
def create_browserid_user(kwargs):
"""
Takes browserid response and creates a user.
"""
if kwargs['status'] == 'okay':
user = User(kwargs['email'])
db.session.add(user)
db.session.commit()
return user
else:
return None
def get_user(kwargs):
"""
Given the response from BrowserID, finds or creates a user.
If a user can neither be found nor created, returns None.
"""
import pdb; pdb.set_trace()
# try to find the user
for row in db.session.query(User).filter(User.email == kwargs.get('email')):
if row is not None:
return row.User
for row in db.session.query(User).filter(User.id == kwargs.get('id')):
if row is not None:
return row.User
# try to create the user
return create_browserid_user(kwargs)
login_manager = LoginManager()
login_manager.user_loader(get_user_by_id)
login_manager.init_app(app)
browserid = BrowserID()
browserid.user_loader(get_user)
browserid.init_app(app)
### Routing ###
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()
**INDEX.html**
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://login.persona.org/include.js" type="text/javascript"></script>
<script type="text/javascript">{{ auth_script|safe }}</script>
</head>
<body>
{% if current_user.is_authenticated() %}
<button id="browserid-logout">Logout</button>
{% else %}
<button id="browserid-login">Login</button>
{% endif %}
</body>
</html>
**Traceback**
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/jzeller/Classes/CS494/main.py", line 106, in home
return render_template('test.html')
File "/Library/Python/2.7/site-packages/flask/templating.py", line 123, in render_template
ctx.app.update_template_context(context)
File "/Library/Python/2.7/site-packages/flask/app.py", line 692, in update_template_context
context.update(func())
File "/Library/Python/2.7/site-packages/flask_login.py", line 799, in _user_context_processor
return dict(current_user=_get_user())
File "/Library/Python/2.7/site-packages/flask_login.py", line 768, in _get_user
current_app.login_manager._load_user()
File "/Library/Python/2.7/site-packages/flask_login.py", line 348, in _load_user
return self.reload_user()
File "/Library/Python/2.7/site-packages/flask_login.py", line 312, in reload_user
user = self.user_callback(user_id)
File "/Users/jzeller/Classes/CS494/main.py", line 60, in get_user_by_id
print "get_user_by_id - " + str(type(row.User)) + " - " + str(row.User)
AttributeError: 'User' object has no attribute 'User'
Answer: ### Answer to original question
The `User` model needs to be a subclass of `db.Model` (or a mapped class) to
work with SQLAlchemy.
class User(UserMixin, db.Model):
...
### Answer to first update
You don't seem to understand what is getting returned by session.query. If you
query a single model, the "rows" that are returned are instances of the model.
The rows will never be None. When you're checking for existence, you should
just use `.first()` if you are applying filters, or `.get(primary_key)` if you
are filtering by primary key. This gets the first result only since the users
are unique anyway
This is what your `get_user_by_id` should look like:
def get_user_by_id(id):
return User.query.get(id)
This is what your `get_user` should look like:
def get_user(kwargs):
u = User.query.filter(db.or_(
User.id == kwargs.get('id'),
User.email == kwargs.get('email')
)).first()
if u is None: # user didn't exist in db
return create_browserid_user(kwargs)
return u
|
Python Incrementing
Question: I am writing a program that will accept text as an input.
The program has a value "tone" that starts at 0. Tone increments by +1 when it
sees a word in that text that is also in a list of words "posfeats." Tone
increments by -1 when it sees a word in that text that is also in a list of
words "negfeats."
However, my code is returning a 0 for the value "tone" no matter what input
text I give it. I feel that this is due to my faulty Python programming rather
than my algorithm.
Here is the code:
import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import movie_reviews #importing two corpora, movie_reviews and stopwords
from nltk.corpus import stopwords
def word_feats(words):
stops = dict([(word, True) for word in stopwords.words('english')]) #English stopwords
features = dict([(word, True) for word in words if word not in stops])#features minus stopwords
return features
def compare(words, negfeats, posfeats):
sentiment=0
for word in words:
if word in negfeats:
sentiment -= 1
if word in posfeats:
sentiment += 1
return sentiment
negReviews = reviews.fileids('neg')
posReviews = reviews.fileids('pos')
negfeats = [(word_feats(reviews.words(fileids=[f])), 'neg') for f in negReviews]
posfeats = [(word_feats(reviews.words(fileids=[f])), 'pos') for f in posReviews]
opinion = raw_input("Why don't you tell me about a movie you watched recently?\n\n")
tone = compare(opinion.split(), negfeats, posfeats)
print(str(tone)) #THIS KEEPS RETURNING 0
Answer:
negfeats = [(word_feats(reviews.words(fileids=[f])), 'neg') for f in negReviews]
posfeats = [(word_feats(reviews.words(fileids=[f])), 'pos') for f in posReviews]
Did you mean to have `dict` calls here? `negfeats` and `posfeats` are lists of
`(word, 'neg')` and `(word, 'pos')` tuples. `compare` will search these lists
for words and not find any, because the words are nested in the tuples. Of
course, it'd be better to use `set`s for unordered collections without
duplicates.
|
Executing different functions based on options selected
Question: I wanted to know if there is a way of populating a option menu with choices
and then each of the different choice gives the build button a different
function
for eg:
Type = cmds.optionMenu('type',w = 300 ,label = 'Type of crowd:')
cmds.menuItem( label='Walking' )
cmds.menuItem( label='Running' )
cmds.menuItem( label='Cheering' )
cmds.button('Build',command = bld)
def walk(*args):
print (walking)
def run(*args)
print (running)
def cheer(*args)
print (cheer)
so if the menu item selected would be walking the button command would execute
the command wak and if the menu item selected would be running then the button
command would execute the command run and so on.... is this even possible in
maya python...????
Answer: There's three parts to the problem.
First, you want your options to be callables. I like functools.partial for
that, so that you could give the same command different parameters and have it
be treated as two different actions:
from functools import partial
bigcircle = functools.partial ( cmds.circle, radius = 10)
littleCircle = functools.partial (cmds.circle, radius = 1)
the second problem is that menuItems in OptionMenus don't fire their commands
directly. They trigger the -cc change command on the owning optionMenu. So we
need something that will turn the label back into a callable object. A little
class will do:
class menuMgr(object):
'''call the function associated with a key in the **callables dictionary'''
def __init__(self, **callables):
self.Callables = callables
def __call__(self, *args):
self.Callables[args[-1]]()
The third part is to match these with a label. You can do this elegantly with
the **kwargs syntax, where you can either pass in a whole dictionary or named
keywords:
def menu_of_functions(**callables):
mmgr = menuMgr(**callables)
Main = cmds.optionMenu('type3',w = 300 ,label = 'Type of crowd:', cc = mmgr)
for key, partial in callables.items():
cmds.menuItem(label = key)
cmds.setParent("..")
Heres the whole thing in working form to inspect:
import maya.cmds as cmds
import functools
bigCircle = functools.partial ( cmds.circle, radius = 10)
littleCircle = functools.partial (cmds.circle, radius = 1)
class menuMgr(object):
def __init__(self, **callables):
self.Callables = callables
def __call__(self, *args):
self.Callables[args[-1]]()
def menu_of_functions(**callables):
mmgr = menuMgr(**callables)
Main = cmds.optionMenu('type3',w = 300 ,label = 'Type of crowd:', cc = mmgr)
for key, partial in callables.items():
cmds.menuItem(label = key)
cmds.setParent("..")
q = cmds.window()
cmds.columnLayout()
menu_of_functions(big = bigCircle, small = littleCircle)
cmds.showWindow(q)
|
ImportError: DLL load failed: %1 is not a valid Win32 application - paramiko
Question: I have a situation in win7 64bit, after I installing paramiko 1.12.1 by using
easy_install paramiko,I'm using 64bit python2.7 , also installed 64bit
pycrypto, there is a import error:
>>> import paramiko
enter code hereenter code hereTraceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import paramiko
File "build\bdist.win-amd64\egg\paramiko\__init__.py", line 65, in <module>
File "build\bdist.win-amd64\egg\paramiko\transport.py", line 33, in <module>
File "build\bdist.win-amd64\egg\paramiko\util.py", line 33, in <module>
File "build\bdist.win-amd64\egg\paramiko\common.py", line 98, in <module>
File "c:\users\yapan\appdata\local\temp\easy_install-6upp3i\pycrypto-2.6-py2.7-win-amd64.egg.tmp\Crypto\Random\__init__.py", line 28, in <module>
File "c:\users\yapan\appdata\local\temp\easy_install-6upp3i\pycrypto-2.6-py2.7-win-amd64.egg.tmp\Crypto\Random\OSRNG\__init__.py", line 34, in <module>
File "c:\users\yapan\appdata\local\temp\easy_install-6upp3i\pycrypto-2.6-py2.7-win-amd64.egg.tmp\Crypto\Random\OSRNG\nt.py", line 28, in <module>
File "c:\users\yapan\appdata\local\temp\easy_install-6upp3i\pycrypto-2.6-py2.7-win-amd64.egg.tmp\Crypto\Random\OSRNG\winrandom.py", line 7, in <module>
File "c:\users\yapan\appdata\local\temp\easy_install-6upp3i\pycrypto-2.6-py2.7-win-amd64.egg.tmp\Crypto\Random\OSRNG\winrandom.py", line 6, in __bootstrap__
ImportError: DLL load failed: %1 is not a valid Win32 application.
Any thoughs?
Answer: This is a problem I ran into as well. I have Windows Server 2012 64 bit and
python 32 bit. What I ended up doing is letting pip solve everything. I have
pip 1.6.dev1.
1. pip install --upgrade paramiko
*if you get this error during upgrade:
> AttributeError: 'str' object has no attribute 'rollback', do:
1. pip uninstall pycrypto and enter (y)
2. pip install pycrypto
3. pip install ecdsa
Basically, just try to run that first command, and follow the tracebacks to
resolve whatever dependency is missing. This worked for me.
I saved my session in txt if you need it for reference.
-Daniel
|
Switch chars with regex
Question: Say I have something like `s='abaabbab'`. Is it possible to change this to
`s='babbaaba'` using regex? I mainly want to know if this is possible, not if
it is reasonable.
I thought perhaps one of these would work (having previously imported
[`re`](http://docs.python.org/2/library/re.html)):
s='ab'
re.sub('a|b',lambda x:['b','a'][x=='a'],s)
#or maybe
re.sub(r'a|b',lambda x:['b','a'][x=='b'],s)
But they just result in `'bb'`.
* * *
I know I could replace all `a`'s with `c`'s, then replace all `b`'s with
`a`'s, then replace all `c`'s with `b`'s, but this seems so long.
[gnibbler suggests this:](http://stackoverflow.com/a/3463853/1896169)
from string import maketrans
trans_table = maketrans(".-a","-.A")
"foo-bar.".translate(trans_table)
But I doesn't seem to work in python 3.
Answer: > Say I have something like s='abaabbab'. Is it possible to change this to
> s='babbaaba' using regex? I mainly want to know if this is possible, not if
> it is reasonable.
Yes - but you should use the correct form of `str.translate` as pointed out by
falsetru for this task...
import re
s = 'abaabbab'
print re.sub('[ab]', lambda L: {'a': 'b', 'b': 'a'}[L.group()], s)
# babbaaba
How this is works is by looking for characters (those defined between the
`[]`) and upon a match, calls the replacement function (here defined by a
lambda) which looks for the suitable replacement character using a dictionary.
|
make from a list the dictionary lists by key
Question: I have a list:
['8C', '2C', 'QC', '5C', '7C', '3C', '6D', 'TD', 'TH', 'AS',
'QS', 'TS', 'JS', 'KS']
I need to get a dictionary something like this: (sorting is not important)
{'C': ['QC', '8C', '7C', '5C', '3C', '2C'],
'S': ['AS', 'KS', 'QS', 'JS', 'TS']
}
code:
def parse_flush(cards):
cards = sort_by_color(cards)
flush_dic = {}
print str(cards)
count = 0
pos = 0
last_index = 0
for color in colors:
for i, card in enumerate(cards):
if card[1] == color:
count += 1
last_index = i+1
if count == 1:
pos = i
if count >= 5:
flush_dic[color] = sort_high_to_low(cards[pos:last_index])
count = 0
return flush_dic
my code now looks like, it works but I do not like its length it is possible
to make it shorter using python tricks?
Answer: You can use simple
[`collections.defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict)
to get the results you wanted
from collections import defaultdict
result = defaultdict(list)
for item in data:
result[item[1]].append(item)
print result
**Output**
{'S': ['AS', 'QS', 'TS', 'JS', 'KS'],
'H': ['TH'],
'C': ['8C', '2C', 'QC', '5C', '7C', '3C'],
'D': ['6D', 'TD']}
You can solve this, using
[`itertools.groupby`](http://docs.python.org/2/library/itertools.html?highlight=itertools#itertools.groupby)
as well
data = ['8C', '2C', 'QC', '5C', '7C', '3C', '6D', 'TD', 'TH', 'AS', 'QS',
'TS', 'JS', 'KS']
from itertools import groupby
from operator import itemgetter
keyFn = itemgetter(1)
print {k:list(grp) for k, grp in groupby(sorted(data, key = keyFn), keyFn)}
**Explanation**
`sorted` returns a sorted list of items, and it uses `keyFn` for sorting the
data.
`groupby` accepts a sorted list and it groups the items based on the `keyFn`,
in this case `keyFn` returns the second elements for each and every items and
the result is as seen in the output.
|
Python on windows subprocess don´t work
Question: I want test to open a winrar password protected file, testing with dictionay
of words. This is my code, but it don't work can any help me ? thanks
import subprocess
def extractFile(rFile, password):
try:
subprocess.call(['c:\\mio\\unrar\\unrar.exe -p'+password+'x C:\\mio\\unrar\\'+rFile,'shell=True'])
return password
except:
return
def main():
rFile = "c:\\mio\\unrar\msploit.rar"
passFile = open("C:\\mio\\unrar\\dic.txt")
for line in passFile.readlines():
password = line.strip('\n')
guess = extractFile(rFile, password)
print(password)
if guess:
print '[+] Password = ' + password + '\n'
break
if __name__ == '__main__':
main()
Answer: First argument to `call()` is an array but you use full command. Try something
like:
subprocess.call(['unrar.exe', 'x', '-p'+password, rarfn], shell=True)
**EDIT:**
I think you will also have to check if output file is created. Maybe `unrar`
with incorrect password will not create output file. Check if it is created
(for example use `os.path.isfile()`). You can also examine `unrar` output to
see where is the problem.
**EDIT2:**
It seems that there was no _x_ `rar` command to _Extract files with full
path_.
This is working example where I rar-ed with password file `Order.htm` into
`Order.rar` and then I deleted `Order.htm`:
rarfn = 'Order.rar'
outfn = 'Order.htm'
if os.path.isfile(outfn):
print('%s already exists!!!' % (outfn))
else:
for password in ('ala', 'ma', 'kota', 'zorro', 'rudy'):
print('testing %s...' % (password))
subprocess.call(['unrar.exe', 'x', '-p'+password, rarfn], shell=True)
if os.path.isfile(outfn):
print('guessed: [%s]' % (password))
break
|
Adding a new column to a FITS file via python
Question: I have created an array named **distance** that contains 1242 values. I want
to add this array as the 11th column in an already existing FITS file that
contains 10 columns.
I am using pyfits.
I tried pyfits.append(filename, distance) which showed no errors but did not
add my column to the FITS file.
Any suggestions??
Answer: Finally they released an updated library that allows the modification of a
table extension in a human way!
Last release of [FITSIO](https://pypi.python.org/pypi/fitsio/). You can easily
add a column with a code looking like the following:
import fitsio
from fitsio import FITS,FITSHDR
...
fits = FITS('file.fits','rw')
fits[-1].insert_column(name = 'newcolumn', data = mydata) # add the extra column
fits.close()
|
Python date conversion
Question: Okay, I give up. Python version 2.7.2
>>> from datetime import datetime
>>> datestr = "2014-01-24"
>>> displaydateobj = datetime.date(datetime.strptime(datestr,'%Y-%d-%m'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 4
What am I missing? I have reviewed the strptime format strings a dozen times.
Answer: Should that be:
`datetime.date(datetime.strptime(datestr,'%Y-%m-%d'))`?
|
Finding a combination in a string using regex in python
Question: I'm trying to find a combination but it is not working
>>> whole = ('\n1. WIPO is located at\n(A) New York\n(B) London\n(C) Geneva\n(D) Paris\n')
>>> match = re.findall('1\.\s(\w+\s)+\w+\n', whole)
>>> print(match)
['located']
I want it to return `"1. WIPO is located at\n"`. But it is just returning
`['located ']`
Answer: Make the group _non-capturing_ , using `(?:...)` instead of `(...)`:
re.findall('1\.\s(?:\w+\s)+\w+\n', whole)
If capturing groups are present, `re.findall()` changes behaviour and only
returns the matched groups; with no captured groups the whole match is
returned instead:
>>> import re
>>> whole = '\n1. WIPO is located at\n(A) New York\n(B) London\n(C) Geneva\n(D) Paris\n'
>>> re.findall('1\.\s(?:\w+\s)+\w+\n', whole)
['1. WIPO is located at\n']
If you only expect there to be the one match, then don't use `re.findall()`
but use `re.search()` instead, and call `.group()` on the resulting `Match`
instance:
>>> re.search('1\.\s(?:\w+\s)+\w+\n', whole).group()
'1. WIPO is located at\n'
Here, it no longer matters if the group is capturing or not.
|
How to test a python eval statement in UWSGI application's ini config?
Question: As far I can tell, my eval statement within a USWGI's app config isn't
working/executing, but I cannot figure out how to test this.
* **OS:** Debian GNU/Linux 7.1 (wheezy)
* **UWSGI:** 1.2.3-debian
* **Python:** 2.7
I'm actually trying to setup Newrelic's application monitoring with the
following in my `app.ini` file (using the [application mounting
method](https://docs.newrelic.com/docs/python/python-agent-and-
uwsgi#application-mounting) for a Django app):
[uwsgi]
chdir = /home/app-user/myapp/bin
wsgi-file = django.wsgi
socket = 127.0.0.1:3031
pythonpath = /home/app-user/myapp/src
logto = /var/log/uwsgi/app/myapp.log
enable-threads = true
single-interpreter = true
eval = import newrelic.agent, django.wsgi; newrelic.agent.initialize('/path/to/newrelic.ini'); application = newrelic.agent.wsgi_application()(django.wsgi.application)
My `newrelic.ini` conf:
log_file = /tmp/newrelic-python-agent.log
After restarting and making some requests to the app (which is up and running
as per usual) the newrelic log_file is not even created, and there is nothing
in the **uwsgi app log** or the **django log** , so I don't know how to tell
what is happening in the eval.
I've tried putting outright syntactically incorrect stuff in the eval, but
uwsgi still restarts successfully.
Is there a way to validate what's in the eval statement as executed by the
uwsgi process?
Answer: I'm late to the party, but your problem was that you had `wsgi-file` option
that made `eval` useless. (Same goes for `module` option - this is the case I
had.)
So, to make uWSGI wrap any WSGI application with a middleware, you just had to
remove the offending options. I.e.:
; DON'T USE THIS: wsgi-file=myproject/wsgi.py
; NEITHER THIS: module=myproject.wsgi
eval=import myproject.wsgi, myfancymw; application = myfancymw.wrap(myproject.wsgi.application)
|
PyQt crashing out as a Windows APPCRASH
Question: I have a [very short PyQt program](http://pythonfiddle.com/pyqt-crashing-
example) (n.b. that is a PythonFiddle link - this seems to crash horribly in
Firefox, so code is also posted below) which prints output to a `QTextEdit`
(using code [from this SO
answer](http://stackoverflow.com/questions/8356336/how-to-capture-output-of-
pythons-interpreter-and-show-in-a-text-widget)). When I run the code (on
Windows), it results in an APPCRASH. Some observations:
* if I add a `time.sleep` call (i.e. uncomment out line 53), then the program completes fine
* if I don’t redirect the output to the QEdit (i.e. comment out line 34) then it works regardless of whether the `time.sleep` call is commented out or not
I assume that this implies that the code redirecting the `stdout` is broken
somehow - but I'm struggling to understand what's wrong with it to result in
this behaviour - any pointers gratefully received!
* * *
**Full error message**
Problem signature:
Problem Event Name: APPCRASH
Application Name: pythonw.exe
Application Version: 0.0.0.0
Application Timestamp: 5193f3be
Fault Module Name: QtGui4.dll
Fault Module Version: 4.8.5.0
Fault Module Timestamp: 52133a81
Exception Code: c00000fd
Exception Offset: 00000000005cbdb7
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 2057
Additional Information 1: 5c9c
Additional Information 2: 5c9c27bb85eb40149b414993f172d16f
Additional Information 3: bc7e
Additional Information 4: bc7e721eaea1ec56417325adaec101aa
* * *
Pythonfiddle crashes horribly on Firefox (for me at least), so code below too:
import os, sys, time, calendar, math
from PyQt4 import QtCore, QtGui
class EmittingStream(QtCore.QObject):
textWritten = QtCore.pyqtSignal(str)
def write(self, text): self.textWritten.emit(str(text))
class myWrapper(QtGui.QMainWindow):
def __init__(self):
super(myWrapper, self).__init__()
self.toolbar = self.addToolBar("MainMenu")
self.toolbar.addAction(QtGui.QAction("myProg", self, triggered=self.myProgActions))
def myProgActions(self): self.setCentralWidget(myWidget())
class myWidget(QtGui.QWidget):
def __init__(self):
super(myWidget, self).__init__()
self.myBtn = QtGui.QPushButton('Run!', self)
self.myBtn.clicked.connect(self.startTest)
self.outputViewer = QtGui.QTextEdit()
self.grid = QtGui.QGridLayout()
self.grid.addWidget(self.myBtn)
self.grid.addWidget(self.outputViewer)
self.setLayout(self.grid)
def startTest(self):
self.myLongTask = TaskThread()
sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
self.myLongTask.start()
def normalOutputWritten(self, text):
cursor = self.outputViewer.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(text)
self.outputViewer.setTextCursor(cursor)
self.outputViewer.ensureCursorVisible()
QtGui.qApp.processEvents()
class TaskThread(QtCore.QThread):
def __init__(self): super(TaskThread, self).__init__()
def run(self): myProgClass()
class myProgClass:
def __init__(self):
for i in range(0,100):
print "thread", i+1, " ", math.sqrt(i)
#time.sleep(0.005)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
myApp = myWrapper()
myApp.show()
sys.exit(app.exec_())
Answer: Ok, one thing first about the thread safety of your program. Because you are
connecting a `QObject` to stdout, calls to `print` will interact with this
`QObject`. But you should only interact with a `QObject` from the thread it
was created in. The implementation you have is potentially thread **unsafe**
if you call `print` from a thread other than the one the `QObject` resides in.
In your case, you are calling `print` from a `QThread` while the
`EmmittingStream(QObject)` resides in the main thread. I suggest you thus
change your code to make it threadsafe, like so:
self.myLongTask = TaskThread()
sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
sys.stdout.moveToThread(self.myLongTask)
self.myLongTask.start()
**Note that now calling`print` from the MainThread of your application will
result in thread-unsafe behaviour. Since you aren't doing that at the moment,
you are OK for now, but be warned!**
I really suggest you read <http://qt-project.org/doc/qt-4.8/threads-
qobject.html> and get your head around everything it talks about.
Understanding that document is the key to avoiding annoying crashes due to
threads.
\--
Now, The issue with the crash is apparently caused by your call to
`processEvents()`. I haven't worked out **why** (I imagine it is related to
threads somehow...), but I can tell you that you do not need that line!
Because you are using signals/slots, once the `normalOutputWritten` method
runs, control returns to the Qt Event Loop anyway, and it will continue to
process events as normal. There is thus no need to force Qt to process events!
Hope that helps!
**EDIT:** For an example of how to make your `EmittingStream`/`print` calls
thread-safe, see here: [Redirecting stdout and stderr to a PyQt4 QTextEdit
from a secondary
thread](http://stackoverflow.com/questions/21071448/redirecting-stdout-and-
stderr-to-a-pyqt4-qtextedit-from-a-secondary-thread/21071865#21071865)
|
How do I finish this Rock, Paper, Scissors game in Python?
Question:
import random
userscore = 0
computerscore = 0
print("Welcome to the Rock, Paper, Scissors Game")
while True:
print("User Score = ", userscore, " Computer Score = ", computerscore)
print("Rock, Paper or Scissors?")
userweapon = str(input())
print("You chose ", userweapon)
computerweapon = random.randint(1,3)
if computerweapon == 1:
computerweapon = "Rock"
elif computerweapon == 2:
computerweapon = "Paper"
else:
computerweapon = "Scissors"
print("Computer chose ", computerweapon)
if userweapon == computerweapon:
print("You chose the same Weapon, it's a draw.")
elif userweapon == "Rock" and computerweapon == "Paper":
print("Computer Point.")
computerscore +=1
elif userweapon == "Rock" and computerweapon == "Scissors":
print("User Point.")
userscore +=1
elif userweapon == "Paper" and computerweapon == "Rock":
print("User Point.")
userscore +=1
elif userweapon == "Paper" and computerweapon == "Scissors":
print("Computer Point.")
computerscore +=1
elif userweapon == "Scissors" and computerweapon == "Rock":
print("Computer point.")
computerscore +=1
elif userweapon == "Scissors" and computerweapon == "Paper":
print("User Point.")
How do I ask the User to type in how many points they want to pay upto and how
do I use this information to end the game when input() has been reached?
I know this code looks pretty bad, but I'm a beginner, it's the best I can do.
Thanks for reading I will vote for best answer.
Answer: instead of
while True:
Try this (and this has no error checking of the input):
rounds = int(input('How many rounds do you want to play?'))
for i in range(rounds):
|
What does "del" do exactly?
Question: Here is my code:
from memory_profiler import profile
@profile
def mess_with_memory():
huge_list = range(20000000)
del huge_list
print "why this kolaveri di?"
This is what the output is, when I ran it from interpreter:
# Line # Mem usage Increment Line Contents
3 7.0 MiB 0.0 MiB @profile
4 def mess_with_memory():
5
6 628.5 MiB 621.5 MiB huge_list = range(20000000)
7 476.0 MiB -152.6 MiB del huge_list
8 476.0 MiB 0.0 MiB print "why this kolaveri di"
If you notice the output, creating the huge list consumed 621.5 MB while
deleting it just freed up 152.6 MB. When i checked the
[docs](http://docs.python.org/2/tutorial/classes.html), I found the below
statement:
the statement del x removes the binding of x from the namespace referenced by the local scope
So I guess, it didn't delete the object itself, but just unbind it. **But,
what did it do in unbinding that it freed up so much of space(152.6 MB)**. Can
somebody please take the pain to explain me what is going on here?
Answer: Python is a garbage-collected language. If a value isn't "reachable" from your
code anymore, it will eventually get deleted.
The `del` statement, as you saw, removes the binding of your variable.
Variables aren't values, they're just names for values.
If that variable was the only reference to the value anywhere, the value will
eventually get deleted. In CPython in particular, the garbage collector is
built on top of reference counting. So, that "eventually" means
"immediately".* In other implementations, it's usually "pretty soon".
If there were other references to the same value, however, just removing one
of those references (whether by `del x`, `x = None`, exiting the scope where
`x` existed, etc.) doesn't clean anything up.**
* * *
There's another issue here. I don't know what the `memory_profiler` module
(presumably [this one](https://pypi.python.org/pypi/memory_profiler)) actually
measures, but the description (talking about use of `psutil`) sounds like it's
measuring your memory usage from "outside".
When Python frees up storage, it doesn't always—or even usually—return it to
the operating system. It keeps "free lists" around at multiple levels so it
can re-use the memory more quickly than if it had to go all the way back to
the OS to ask for more. On modern systems, this is rarely a problem—if you
need the storage again, it's good that you had it; if you don't, it'll get
paged out as soon as someone else needs it and never get paged back in, so
there's little harm.
(On top of that, which I referred to as "the OS" above is really an
abstraction made up of multiple levels, from the `malloc` library through the
core C library to the kernel/pager, and at least one of those levels usually
has its own free lists.)
If you want to trace memory use from the inside perspective… well, that's
pretty hard. It gets a lot easier in Python 3.4 thanks to the new
[`tracemalloc`](http://docs.python.org/3.4/library/tracemalloc.html#module-
tracemalloc) module. There are various third-party modules (e.g.,
`heapy`/[`guppy`](https://pypi.python.org/pypi/guppy),
[`Pympler`](https://pypi.python.org/pypi/Pympler/0.3.1),
[`meliae`](https://pypi.python.org/pypi/meliae/0.4.0.final.0)) that try to get
the same kind of information with earlier versions, but it's difficult,
because getting information from the various allocators, and tying that
information to the garbage collector, was very hard before [PEP
445](http://www.python.org/dev/peps/pep-0445/).
* * *
* In some cases, there _are_ references to the value… but only from other references that are themselves unreachable, possibly in a cycle. That still counts as "unreachable" as far as the garbage collector is concerned, but not as far as reference counts are concerned. So, CPython also has a "cycle detector" that runs every so often and finds cycles of mutually-reachable but not-reachable-from-anyone-else values and cleans them up.
** If you're testing in the interactive console, there may be hidden
references to your values that are hard to track, so you might _think_ you've
gotten rid of the last reference when you haven't. In a script, it should
always be _possible_ , if not _easy_ , to figure things out. The
[`gc`](http://docs.python.org/2/library/gc.html) module can help, as can the
debugger. But of course both of them _also_ give you new ways to add
additional hidden references.
|
extracting and listing word in python
Question: i have difficult to do this project python script to extract and list all
words that meets the following conditions:
(1) words with two consonants next to each other.
(2) words of length 5 or more that start and ends with a vowel.
(3) words of length 7 or more that starts with consonant and ends with a
vowel.
(4) Abbreviate 2-3 words that all start with a capital letter.
Any pointers on how to code this, helps, or even code examples would be much
appreciated. need your help.
Answer: First, how to include regular expressions in a Python program:
import re
if re.match(pattern, string_to_match):
# there is a match
else:
# there is no match
Then, the first regular expression you need. As you haven't given any code,
and this question smells of homework I won't give you the others.
re.match(r"^[aeiou].{,3}[aeiou]$", string_to_match)
Explanation:
The `^` and `$` ensure that the match is from the beginning to end of the
string. The `[aeiou]` checks for a character that is a vowel. The `.{,3}`
checks for up to 3 repetitions of any character (represented by `.`).
You may find the [documentation](http://docs.python.org/3/library/re.html)
helpful.
|
returning one value from a dict key with multiple values in python
Question: I am trying to return "runnerName" from the following dict:
{u'marketId': u'1.112422365',
u'marketName': u'1m Mdn Stks',
u'runners': [{u'handicap': 0.0,
u'runnerName': u'La Napoule',
u'selectionId': 8095372,
u'sortPriority': 1},
{u'handicap': 0.0,
u'runnerName': u'Swivel',
u'selectionId': 701378,
u'sortPriority': 2},
{u'handicap': 0.0,
u'runnerName': u'Deanos Devil',
u'selectionId': 8100420,
u'sortPriority': 3},
{u'handicap': 0.0,
u'runnerName': u'Bishan Bedi',
u'selectionId': 8084336,
u'sortPriority': 4},
{u'handicap': 0.0,
u'runnerName': u'In Seine',
u'selectionId': 8199415,
u'sortPriority': 5},
{u'handicap': 0.0,
u'runnerName': u'Needs The Run',
u'selectionId': 8199416,
u'sortPriority': 6},
{u'handicap': 0.0,
u'runnerName': u'Appellez Baileys',
u'selectionId': 8148513,
u'sortPriority': 7},
{u'handicap': 0.0,
u'runnerName': u'Jessy Mae',
u'selectionId': 7652545,
u'sortPriority': 8},
{u'handicap': 0.0,
u'runnerName': u'Redy To Rumble',
u'selectionId': 7366163,
u'sortPriority': 9}]}
I have tried many different ways but cannot figure out how to access a value
from a key with multiple values.
Answer: 1. You can use list comprehension, like this, to retrieve the runner names from the dictionary of runners.
print [runner["runnerName"] for runner in runners_dict["runners"]]
2. Or you can use [`operator.itemgetter`](http://docs.python.org/2/library/operator.html#operator.itemgetter), like this
from operator import itemgetter
print map(itemgetter("runnerName"), runners_dict["runners"])
**Output**
[u'La Napoule', u'Swivel', u'Deanos Devil', u'Bishan Bedi', u'In Seine',
u'Needs The Run', u'Appellez Baileys', u'Jessy Mae', u'Redy To Rumble']
|
Wsgiref Error: AttributeError: 'NoneType' object has no attribute 'split'
Question: I am trying to implement my own version of wsgiref for learning purpose and i
ended up here.
from wsgiref.simple_server import make_server
class DemoApp():
def __init__(self, environ, start_response):
self.environ = environ
self.start = start_response
def __iter__(self, status):
self.status = '200 OK'
response_headers = [('Content-type','text/plain')]
self.start(status, response_headers)
return ["Hello World"]
if __name__ == '__main__':
httpd = make_server('', 1000, DemoApp)
print("Serving on port 1000")
httpd.serve_forever()
When i go to port 1000, i am getting the attribute error.
AttributeError: 'NoneType' object has no attribute 'split'
Where i am leaving mistakes ?
Stacktrace
Serving on port 1000
Traceback (most recent call last):
File "C:\Python27\lib\wsgiref\handlers.py", line 86, in run
self.finish_response()
File "C:\Python27\lib\wsgiref\handlers.py", line 131, in finish_response
self.close()
File "C:\Python27\lib\wsgiref\simple_server.py", line 33, in close
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
127.0.0.1 - - [11/Jan/2014 12:40:09] "GET / HTTP/1.1" 500 59
Traceback (most recent call last):
File "C:\Python27\lib\SocketServer.py", line 295, in _handle_request_noblock
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 54469)
self.process_request(request, client_address)
File "C:\Python27\lib\SocketServer.py", line 321, in process_request
self.finish_request(request, client_address)
File "C:\Python27\lib\SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python27\lib\SocketServer.py", line 649, in __init__
self.handle()
File "C:\Python27\lib\wsgiref\simple_server.py", line 124, in handle
handler.run(self.server.get_app())
File "C:\Python27\lib\wsgiref\handlers.py", line 92, in run
self.close()
File "C:\Python27\lib\wsgiref\simple_server.py", line 33, in close
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
Answer: `DemoApp` is called; The return value of `DemoApp.__init__` is used.
`DemoApp.__init__` returns nothing (You can't return anything in constructor).
Try following instead of `DemoApp` class:
def DemoApp(environ, start_response):
response_headers = [('Content-type','text/plain')]
start_response('200 OK', response_headers)
return ["Hello World"]
Using class (Use `__call__` instead of `__iter__`):
from wsgiref.simple_server import make_server
class DemoApp:
def __call__(self, environ, start_response):
response_headers = [('Content-type','text/plain')]
start_response('200 OK', response_headers)
return ["Hello World"]
if __name__ == '__main__':
httpd = make_server('', 1000, DemoApp()) # Don't forget instantiate a class.
# ^^
print("Serving on port 1000")
httpd.serve_forever()
|
pyglet on_draw event occurs only when mouse moves
Question: I have a strange problem. When pyglet app starts it just draws 1-2 frames then
freezes. on_draw event just stops occuring. But everytime I move mouse or
press keys, on_draw event dispatches as well. In short I have to move mouse to
make my pyglet application basically work.
This is actually happens in Windows. In Ubuntu with compiz I've to move mouse
just once then application starts working normally.
This is my code example:
#!/usr/bin/env python
import pyglet
win = pyglet.window.Window(width=800, height=600)
label = pyglet.text.Label('Abc', x=5, y=5)
@win.event
def on_draw():
win.clear()
label.x += 1
label.draw()
pyglet.app.run()
Here's [a video](http://viert.fm/pyglet_on_draw_event.swf) explaining things.
Answer: I came across this last night while trying to figure out the same problem. I
figured out what causes this.
I had used a decorator and put my updates in the on_draw method, and it would
run okay for a little while, then it would freeze, only to start working again
when I moved the mouse or hit the keyboard. I tried all sorts of tricks to
figure it out, I finally thought that maybe things were just running too fast,
and that putting them in a batch and letting pyglet decide when to update them
would be better. It worked.
I also scheduled things so that they would run about twice as fast as my
refresh rate, but not so fast it would bog anything down. This is more than
enough for smooth animations.
needles_list = [gauges.speedometer.Needle(speedometer_data, needle, batch=batch, group=needles),
gauges.tachometer.Needle(tachometer_data, needle, batch=batch, group=needles)]
def update(dt):
for needle in needles_list:
needle.update(dt)
pyglet.clock.schedule_interval(update, 1/120.0)
gauges.speedometer.Needle and gauges.tachometer.Needle are subclasses of
pyglet.sprite.Sprite, and I wrote an update method for each of them. I then
called their draw method in on_draw as normal.
@window.event()
def on_draw():
window.clear()
batch.draw()
I know this question has been up for a while, and the asker may have given up
already, but hopefully it will help anyone else that's having this problem.
|
How to import text file from different folder?
Question: I have my project folder `\FNAL PROJ\project` and I need to open `file.txt`
from folder `\FNAL PROJ\project\data`
How to do it in Python?
Answer: Assuming your main script is somewhere on \FNAL PROJ\project folder:
with open("data/file.txt", "r") as f:
file_content = f.read()
|
How to change the images in python
Question: I'm working on xbmc to run four images with my own python script. I have set
up the keyboard control using keymap.xml as I want to change the images in
python when pressing on the left arrow on the keyboard.
I'm using xml file to store the parser path for the images.
Here's the xml file that I use:
<?xml version="1.0" encoding="utf-8"?>
<window type="dialog">
<allowoverlay>no</allowoverlay>
<coordinates>
<system>1</system>
<posx>0</posx>
<posy>0</posy>
</coordinates>
<controls>
<control type="image" id="1">
<posx>0</posx>
<posy>0</posy>
<width>1280</width>
<height>720</height>
<texture>background-defeat.png</texture>
<animation effect="fade" start="0" end="100" time="6500">WindowOpen</animation>
</control>
<control type="image" id="2">
<description>Image 2</description>
<posx>307</posx>
<posy>7</posy>
<width>154</width>
<height>95</height>
<visible>true</visible>
<texture>Image 2.png</texture>
<animation effect="fade" start="0" end="100" time="1500">WindowOpen</animation>
</control>
<control type="image" id="3">
<description>Image 3</description>
<posx>460</posx>
<posy>7</posy>
<width>188</width>
<height>95</height>
<visible>true</visible>
<texture>Image 3.png</texture>
<animation effect="fade" start="0" end="100" time="1500">WindowOpen</animation>
</control>
<control type="image" id="4">
<description>Image 4</description>
<posx>648.5</posx>
<posy>7</posy>
<width>165</width>
<height>95</height>
<visible>true</visible>
<texture>Image 4.png</texture>
<animation effect="fade" start="0" end="100" time="1500">WindowOpen</animation>
</control>
</controls>
</window>
Here is the python script:
import xbmc
import xbmcgui
import os
#get actioncodes from keymap.xml
ACTION_MOVE_LEFT = 1
ACTION_MOVE_RIGHT = 2
ACTION_MOVE_UP = 3
ACTION_MOVE_DOWN = 4
ACTION_PREVIOUS_MENU = 10
ACTION_BACKSPACE = 110
class MyClass(xbmcgui.WindowXML):
def onAction(self, action):
if action == ACTION_PREVIOUS_MENU:
self.close()
if action == ACTION_BACKSPACE:
self.close()
if action == ACTION_MOVE_LEFT:
if os.path.exists(xbmc.translatePath("special://home/addons/script.tvguide/resources/skins/Default/media/Image 2.png")):
self.strAction = xbmcgui.ControlLabel(300, 200, 600, 200, '', 'font14', '0xFF00FF00')
self.addControl(self.strAction)
self.strAction.setLabel('you are pressing on the left button. Now let change the image')
When I press the left arrow button on the keyboard, I can get pass on the if
statement as the image `Image 2.png` is exist. Now I would like to change the
images which I want to change it from Image 2.png to Image 3.png.
Does anyone know how I could do that?
Answer: You need to get the `ImageControl` as control-object (by ID defined in your
XML) and use the `setImage()` method to change its texture.
Example code:
if action == ACTION_MOVE_LEFT:
image_control = self.getControl(4)
image_control.setImage("special://home/addons/script.tvguide/resources/skins/Default/media/Image 2.png")
You should really read The xbmcgui docs: <http://mirrors.xbmc.org/docs/python-
docs/12.2-frodo/xbmcgui.html>
|
My program in python to count the number of different words only returns the value six. Any ideas why?
Question: Here is my code. I am using Python:
import re
file = open('TEST.txt')
text = file.read()
file.close()
words = list(text.split())
myset= set(words)
num = len(myset)
print (num)
When I run it, it prints 6 no matter how long the text file is. Why would this
be and how would I fix it?
Answer: You are using a `set()`; your file consists of only six _unique_ words.
Repeating the same 6 words over and over again won't make the count go up.
Either don't use a set (which can only hold unique values), or use other words
in your file:
>>> words = ['foo', 'bar', 'baz', 'foo', 'bar', 'baz']
>>> len(words)
6
>>> len(set(words))
3
>>> set(words)
set(['baz', 'foo', 'bar'])
You are also using a _relative_ filename; `TEST.txt` will be opened in the
current directory; change your current directory (in your terminal, using
`os.chdir()`, etc.) and a different file will be opened if there is _another_
`TEST.txt` file there.
Use `print(words)` to see if you are still opening the right text file, check
for the current directory with `import os; print(os.getcwd())`, or better
still, use an absolute file path (with all the directories specified
explicitly).
|
How to generate a deck of cards in Python
Question: How do you generate a full deck of 52 cards the most efficiently in list
format in Python so that the list will look like this:
`['1 of Spades', '1 of Hearts', '1 of Clubs', '1 of Diamonds', '2 of Spades',
'2 of Hearts'` etc.
Answer: I would prefer the following code, as in Python `Readability Counts`
>>> faces = range(2,11) + ["King","Queen","Jack","Ace"]
>>> colour = ["Spades", "Hearts", "Clubs", "Diamonds"]
>>> from itertools import product
>>> ["{} of {}".format(*card) for card in product(faces, colour)]
|
Running django tutorial tests fail - No module named polls.tests
Question: I'm playing with django 1.6 tutorial but i can't run tests. My project (name
mydjango) and app structure (name is polls) are as shown below in a
virtualenv. (.nja files are just created by ninja-ide the ide i'm using)
.
├── __init__.py
├── manage.py
├── mydjango
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── mydjango.nja
│ ├── settings.py
│ ├── settings.pyc
│ ├── templates
│ │ └── admin
│ │ └── base_site.html
│ ├── urls.py
│ ├── urls.pyc
│ ├── wsgi.py
│ └── wsgi.pyc
├── polls
│ ├── admin.py
│ ├── admin.pyc
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── models.py
│ ├── models.pyc
│ ├── templates
│ │ ├── __init__.py
│ │ └── polls
│ │ ├── detail.html
│ │ ├── index.html
│ │ ├── __init__.py
│ │ └── results.html
│ ├── tests.py
│ ├── tests.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── views.py
│ └── views.pyc
└── polls.nja
I followed the tutorial to understand how django works but i'm stuck in the
test part. As tutorial suggest i created a file named tests.py into the app
folder, the pretty strighforward file is:
# -*- coding: utf-8 -*-
from django.test import TestCase
import datetime
from django.utils import timezone
from polls.models import Question
# Create your tests here.l
class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_poll(self):
"""
was_published_recently dovrebbe ritornare falso se si mette una data nel futuro
"""
future_question = Question(pub_date=timezone.now() + datetime.timedelta(hours=50))
self.assertEqual(future_question.was_published_recently(), False)
then i installed unittest2 into the virtualenv with
$pip install unittest2
and run
$python manage.py test polls
Creating test database for alias 'default'...
E
======================================================================
ERROR: mydjango.polls.tests (unittest2.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: mydjango.polls.tests
Traceback (most recent call last):
File "/home/sergio/.virtualenvs/django4/local/lib/python2.7/site-packages/unittest2/loader.py", line 260, in _find_tests
module = self._get_module_from_name(name)
File "/home/sergio/.virtualenvs/django4/local/lib/python2.7/site-packages/unittest2/loader.py", line 238, in _get_module_from_name
__import__(name)
ImportError: No module named polls.tests
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Destroying test database for alias 'default'...
No way to have the test working, also if don't pass the app name it returns
the same error:
$ python manage.py test
Creating test database for alias 'default'...
E
======================================================================
ERROR: mydjango.polls.tests (unittest2.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: mydjango.polls.tests
Traceback (most recent call last):
File "/home/sergio/.virtualenvs/django4/local/lib/python2.7/site-packages/unittest2/loader.py", line 260, in _find_tests
module = self._get_module_from_name(name)
File "/home/sergio/.virtualenvs/django4/local/lib/python2.7/site-packages/unittest2/loader.py", line 238, in _get_module_from_name
__import__(name)
ImportError: No module named polls.tests
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Destroying test database for alias 'default'...
My INSTALLED_APPS are:
INSTALLED_APPS = (
'south',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
Can't understand what's i'm doing wrong - any help should be really
appreciated. Thank u
Answer: I had exactly the same issue with my Django project:
$ python manage test polls.tests
worked fine whereas the following failed with an import error:
$ python manage test polls
$ python manage test
(...)
ImportError: Failed to import test module: mydjango.polls.tests
Traceback (most recent call last):
(...)
ImportError: No module named polls.tests
Check carefully the error message: Django's test runner tries to import the
tests from **mydjango.polls.tests** where _mydjango_ is the name of the root
directory (the container for your project).
I fixed this issue by deleting the `__init__.py` file in _mydjango_ directory
(at the same level than manage.py file). This directory is not supposed to be
a python module and it seems to mess up with Django's test runner if it is the
case.
**So just deleting the __init_ _.py file should fix our problem**:
$ rm mydjango/__init__.py
|
How to put random lines from a file into a string in python?
Question: what i want to do is write a code that has a file (in the code, no need to be
input by user), and the code picks a random line from the file - whatever it
is, a long line, an ip or even a word and at the end of the loop puts it into
a string so i could use that in other parts of the code.
i tried using `randomchoice(lines)` but wasn't sure how to continue from here.
after that i tried using:
import random
def random_line(afile):
line = next(afile)
for num, aline in enumerate(afile):
if random.randrange(num + 2): continue
line = aline
return line
which also for some reason didnt work for me.
Answer: The last method you posted worked for me. Maybe you are not opening the file
correctly. Here is another approach, using `random.choice`
import random
def random_line(f):
return random.choice([line for line in f])
f = open("sample.txt", 'r')
print random_line(f)
**Edit:**
Another way would be (thanks to @zhangxaochen):
def random_line(f):
return random.choice(f.readlines())
|
Python regex findall to capture repeated groups
Question: # Context
I am using python [regex](https://pypi.python.org/pypi/regex "regex") to parse
some HTMLs because they are too broken to use processors better suited for
those tasks (e.g. scrapy selectors). An excerpt of the HTML I want to parse
looks like this:
<LI><B>First list title</B> Additional info
<UL>
<LI><I>List element 1</I> additional info
</UL>
<LI><B>Second list title</B> Additional info
<UL>
<LI><I>List element 1</I> additional info1
<LI><I>List element 2</I> additional info2
<LI><I>List element 3</I> additional info3
<LI><I>List element 4</I> additional info4
</UL>
<!-- many more elements like the ones above -->
I need to capture the List title (and additional information), and for each
title all nested elements it has with their additional information as well.
# Approaches
import regex as re
## re.findall
reg = re.compile("<li><b>(.*)\n\s*<ul>\n(\s*<li>.+\n)+\s*</ul>", re.IGNORECASE)
g_info = re.findall(reg, response.body)
If we look info g_info in the above example we will see that for those with
one list element is fine:
g_info[0] <- ('First list title</B> Additional info', " <LI><I>List element 1</I> additional info\n")
But when there are multiple sublist elements, only the last one is obtained.
g_info[1] <- ('Second list title</B> Additional info', " <LI><I>List element 4</I> additional info4\n")
I would like it to be something like:
g_info[1] <- ('Second list title</B> Additional info', " <LI><I>List element 1</I> additional info1\n", " <LI><I>List element 2</I> additional info2\n", ...)
## re.search and .captures
Using the same regular expression I can use the .captures function to get all
the elements captured. I will tune it slightly so it works with this example:
reg = re.compile("<li><b>(.*)\n\s*<ul>\n(\s*<li>.+\n){2,}\s*</ul>", re.IGNORECASE)
g_info = re.search(reg, response.body)
But this way (I would further parse each element with another simpler regexp
to obtain what I want) I only get the first match and not all of them.
g_info.captures() <-- '<LI><B>Second list title</B> Additional info\n <UL>\n <LI><I>List element 1</I> additional info1\n <LI><I>List element 2</I> additional info2\n ...'
If I could get all of them in this format it would suffice for me.
## re.findall and additional looping and filtering
I could use a simpler regexp to get all of them. Then I could further detect
which is a subelement and which not, because list titles always start with a
bold tag and the others don't.
reg = re.compile("(\s*<li>.+\n)", re.IGNORECASE)
g_info = re.findall(reg, response.body)
What I get is something like this:
g_info[0] <- '\n\n<LI><B>First list title</B> Additional info\n'
g_info[1] <- '\n <LI><I>List element1</I> additional info\n'
g_info[2] <- '\n\n<LI><B>Second list title</B> Additional info\n'
g_info[3] <- '\n <LI><I>List element</I> additional info1\n'
g_info[4] <- ' <LI><I>List element2</I> additional info2\n'
g_info[5] <- ' <LI><I>List element3</I> additional info3\n'
# Solutions?
The only workable approach I found was the last one, which imho is not
elegant. Could you help me find a better solution? Thanks
Answer:
import re
pattern = re.compile("(?<=<li><b>).*?(?=</ul>)", re.IGNORECASE | re.DOTALL)
print re.findall(pattern, data)
**Output**
['First list title</B> Additional info\n <UL>\n <LI><I>List element 1</I> additional info\n ',
'Second list title</B> Additional info\n <UL>\n <LI><I>List element 1</I> additional info1\n <LI><I>List element 2</I> additional info2\n <LI><I>List element 3</I> additional info3\n <LI><I>List element 4</I> additional info4\n ']
|
Using Surface.copy() sometimes loses transparency
Question: For some (but not all!) images, copying a surface using `surface.copy()` loses
the transparency. So I've got two questions?
1. **Why does copy lose the transparency?** The [docs](http://www.pygame.org/docs/ref/surface.html) sound like _everything_ about the new surface should be the same, but that's obviously not happening.
2. Why does this happen with some images and not others?
Here is an example "bad" image -- when copied, the transparency is lost

Here is an example "good" image -- when copied, the transparency is **not**
lost.

And here is the code that you can run to see the difference:
import pygame
def test():
screen = pygame.display.set_mode((320, 240))
bad_original = pygame.image.load('bad-image.gif')
bad_copied = bad_original.copy()
good_original = pygame.image.load('good-image.gif')
good_copied = good_original.copy()
while True:
for event in pygame.event.get():
if (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE or
event.type == pygame.QUIT):
pygame.quit()
screen.fill((150, 150, 150))
screen.blit(bad_original, (0,0))
screen.blit(bad_copied, (100, 0))
screen.blit(good_original, (0,100))
screen.blit(good_copied, (100, 100))
pygame.display.flip()
if __name__ == '__main__':
test()
And heck, for completion, here's what a screenshot of running the above code
looks like. 
Please note that I'm **not looking for workarounds** ; I just want to know
what I am not understanding about `surface.copy`, or anything you think I may
not understand about working with Pygame surfaces.
I'm using Python 3.3 and Pygame 1.9.2pre on a Windows 7 machine.
Answer: You need to use .convert_alpha()
Try:
pygame.image.load('my_image.gif').convert_alpha()
See:
<http://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert_alpha>
"Creates a new copy of the surface with the desired pixel format. The new
surface will be in a format suited for quick blitting to the given format with
per pixel alpha. If no surface is given, the new surface will be optimized for
blitting to the current display.
Unlike the Surface.convert() method, the pixel format for the new image will
not be exactly the same as the requested source, but it will be optimized for
fast alpha blitting to the destination."
In pygame anytime you load and image, or create a surface, with the intent of
displaying it you should .convert() it if it has no transparency, or
.convert_alpha() it if it has transparency. This yields both a big speedup AND
solves the mystery of, 'Why is my transparency doing that?'.
|
'tuple' object has no attribute 'update'
Question: I'd like to extend my user profiles using custom models. Unfortunately
whenever I'm visiting the page where the profile is located I receive 'tuple'
object has no attribute 'update'
I've tried to get around this myself but after 2,5hrs it did hit me that I'm
stuck.
Could anyone enlighten me please?
Model:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Skills(models.Model):
description = models.CharField(max_length=3000)
class UserProfile(models.Model):
#Choices
STAFF = (
('AD', 'Super User'),
('MA', 'Manager'),
)
DEPT = (
('TD', 'Tech Service'),
('CS', 'Customer Service'),
)
user = models.OneToOneField(User, blank=False, unique=True)
staff = models.CharField(max_length=2, choices=STAFF)
dept = models.CharField(max_length=3, choices=DEPT)
team = models.BooleanField(default=False)
skill = models.ManyToManyField(Skills)
email = models.EmailField()
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
forms
from django import forms
from models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('staff', 'dept', 'team', 'skill', 'email')
view
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from forms import UserProfileForm
from django.contrib.auth.decorators import login_required
@login_required
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = ()
args.update(csrf(request))
args['form'] = form
return render_to_response(profile.html, args)
app urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^profile/$', 'userprofile.views.user_profile'),
)
and standard urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tms_core.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('userprofile.urls')),
)
Finally the traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/profile/
Django Version: 1.6.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'userprofile')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/home/user/projects/tms5/tms_core/userprofile/views.py" in user_profile
20. args.update(csrf(request))
Exception Type: AttributeError at /accounts/profile/
Exception Value: 'tuple' object has no attribute 'update'
Also, I'm running this project in a virtual env.
Any help would be appreciated.
Answer: In your view `args` should be dict not tuple:
# args = ()
args = {}
|
Iterating Swap Algorithm Python
Question: I have an algorithm. I want that last solution of the algorithm if respect
certains conditions become the first solution. In my case I have this:
1. First PArt
Split the multidimensional array q in 2 parts
split_at = q[:,3].searchsorted([1,random.randrange(LB,UB-I)])
D = numpy.split(q, split_at)
Change and rename the splitted matrix:
S=B[1]
SF=B[2]
S2=copy(SF)
S2[:,3]=S2[:,3]+I
Define a function f:
f=sum(S[:,1]*S[:,3])+sum(S2[:,1]*S2[:,3])
This first part is an obligated passage.
1. Second Passage
Then I split again the array in 2 parts:
split_at = q[:,3].searchsorted([1,random.randrange(LB,UB-I)])
D = numpy.split(q, split_at)
I rename and change parts of the matrix(like in the first passage:
T=D[1]
TF=D[2]
T2=copy(TF)
T2[:,3]=T2[:,3]+I
u=random.sample(T[:],1) #I random select an array from T
v=random.sample(T2[:],1) #random select an array from T2
u=array(u)
v=array(v)
Here is my first problem: I want to continue the algorithm only if
v[0,0]-u[0,0]+T[-1,3]<=UB, if not I want to repeat Second Passage until the
condition is verified.
Now I swap 1 random array from T with another from T2:
x=numpy.where(v==T2)[0][0]
y=numpy.where(u==T)[0][0]
l=np.copy(T[y])
T[y],T2[x]=T2[x],T[y]
T2[x],l=l,T2[x]
I modified and recalculate some in the matrix:
E=np.copy(T)
E2=np.copy(T2)
E[:,3]=np.cumsum(E[:,0])
E2[:,3]=np.cumsum(E2[:,0])+I
Define f2:
f2=sum(E[:,1]*E[:,3])+sum(E2[:,1]*E2[:,3])
Here my second and last problem. I need to iterate this algorithm. If f-f2<0
my new starting solution has to be E and E2 and my new f has to be f2 and
iterate excluding last choice the algorithm (recalcultaing a new f and f2).
Thank you for the patience. I'm a noob :D
EDIT: I have an example here(this part goes before the code I have written on
top)
import numpy as np
import random
p=[ 29, 85, 147, 98, 89, 83, 49, 7, 48, 88, 106, 97, 2,
107, 33, 144, 123, 84, 25, 42, 17, 82, 125, 103, 31, 110,
34, 100, 36, 46, 63, 18, 132, 10, 26, 119, 133, 15, 138,
113, 108, 81, 118, 116, 114, 130, 134, 86, 143, 126, 104, 52,
102, 8, 90, 11, 87, 37, 68, 75, 69, 56, 40, 70, 35,
71, 109, 5, 131, 121, 73, 38, 149, 20, 142, 91, 24, 53,
57, 39, 80, 79, 94, 136, 111, 78, 43, 92, 135, 65, 140,
148, 115, 61, 137, 50, 77, 30, 3, 93]
w=[106, 71, 141, 134, 14, 53, 57, 128, 119, 6, 4, 2, 140,
63, 51, 126, 35, 21, 125, 7, 109, 82, 95, 129, 67, 115,
112, 31, 114, 42, 91, 46, 108, 60, 97, 142, 85, 149, 28,
58, 52, 41, 22, 83, 86, 9, 120, 30, 136, 49, 84, 38,
70, 127, 1, 99, 55, 77, 144, 105, 145, 132, 45, 61, 81,
10, 36, 80, 90, 62, 32, 68, 117, 64, 24, 104, 131, 15,
47, 102, 100, 16, 89, 3, 147, 48, 148, 59, 143, 98, 88,
118, 121, 18, 19, 11, 69, 65, 123, 93]
p=array(p,'double')
w=array(w,'double')
r=p/w
LB=12
UB=155
I=9
j=p,w,r
j=transpose(j)
k=j[j[:,2].argsort()]
c=np.cumsum(k[:,0])
q=k[:,0],k[:,1],k[:,2],c
q=transpose(q)
o=sum(q[:,1]*q[:,3])
split_at = q[:,3].searchsorted([1,UB-I])
B = numpy.split(q, split_at)
S=B[1]
SF=B[2]
S2=copy(SF)
S2[:,3]=S2[:,3]+I
f=sum(S[:,1]*S[:,3])+sum(S2[:,1]*S2[:,3])
split_at = q[:,3].searchsorted([1,random.randrange(LB,UB-I)])
D = numpy.split(q, split_at)
T=D[1]
TF=D[2]
T2=copy(TF)
T2[:,3]=T2[:,3]+I
u=random.sample(T[:],1)
v=random.sample(T2[:],1)
u=array(u)
v=array(v)
x=numpy.where(v==T2)[0][0]
y=numpy.where(u==T)[0][0]
l=np.copy(T[y])
T[y],T2[x]=T2[x],T[y]
T2[x],l=l,T2[x]
E=np.copy(T)
E2=np.copy(T2)
E[:,3]=np.cumsum(E[:,0])
E2[:,3]=np.cumsum(E2[:,0])+I
f2=sum(E[:,1]*E[:,3])+sum(E2[:,1]*E2[:,3])
I tried:
def DivideRandom(T,T2):
split_at = q[:,3].searchsorted([1,random.randrange(LB,UB-I)])
D = numpy.split(q, split_at)
T=D[1]
TF=D[2]
T2=copy(TF)
T2[:,3]=T2[:,3]+I
Divide(T,T2)
def SelectJob(u,v):
u=random.sample(T[:],1)
v=random.sample(T2[:],1)
u=array(u)
v=array(v)
SelectJob(u,v)
d=v[0,0]-u[0,0]+T[-1,3]
def Swap(u,v):
x=numpy.where(v==T2)[0][0]
y=numpy.where(u==T)[0][0]
l=np.copy(T[y])
T[y],T2[x]=T2[x],T[y]
T2[x],l=l,T2[x]
E=np.copy(T)
E2=np.copy(T2)
E[:,3]=np.cumsum(E[:,0])
E2[:,3]=np.cumsum(E2[:,0])+I
f2=sum(E[:,1]*E[:,3])+sum(E2[:,1]*E2[:,3])
while True:
if d<=UB
Swap(u,v)
if d>UB
DivideRandom(T,T2)
SelectJob(u,v)
if d<UB:
break
Answer: You can iterate indefinitely using `while True`, then stop whenever your
conditions are met using `break`:
count = 0
while True:
count += 1
if count == 10:
break
So for your second example you can try:
while True:
...
if f - f2 < 0:
# use new variables
f, E = f2, E2
else:
break
Your first problem is similar; loop, test, reset the appropriate variables.
|
no python output using print
Question: Hi am new to python and just trying to read a simple csv file and output to
the terminal using:
import csv
with open('cancerdata.csv', 'rb') as csvfile:
data = csv.reader(csvfile, delimiter=' ')
for row in data:
print row
However when I run:
python program.py
I get no output, yet no errors.
What simple noob error have I made?
Answer: As stated in the comments it's _very likely_ that your `cancerdata.csv` file
is **empty**. See:
$ touch cancerdata.csv
$ python myprogram.py
_No output_.
$ echo "1,2,3\n" > cancerdata.csv
$ echo "3,4,5\n" > cancerdata.csv
$ python myprogram.py
['3,4,5\\n']
**We have output!**
|
How to dismiss a dialog box displayed by MS Word when openning document in Python/Win32
Question: I'm trying to write a script that would go though content of all ms word docs
in a folder and collect some information. I use Python 2.7.3 and Ms Office
2007 The issue I have is that sometimes MS Word is coming with a warning/error
popup window when opening a document. An example of the error message is
'Microsoft Visual Basic: Sub or Function not defined'. Another error is that
too many grammar mistakes in the doc. These events suspend the processing
until you manually press OK button. After that the scrip continues processing
the document. An interesting note is that when I open the document manually in
word it doesn't produce the 'Sub or Function not defined' error.
So, is there a way to suppress these errors/warnings so that the script could
process the files in a batch mode?
Here is the code I use to open the word files:
import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.Visible = False
...
doc = word.Documents.OpenNoRepairDialog(fname, False, True) # Popup window appears on this line
Answer: The `OpenNoRepairDialog` method does not appear to have any error suppression
options, as per;
<http://msdn.microsoft.com/en-us/library/office/ee426710(v=office.12).aspx>
It's possible you could disable these errors within Word preference somewhere.
Alternatively, try using `pywin32`?
<http://www.galalaly.me/index.php/2011/09/use-python-to-parse-microsoft-word-
documents-using-pywin32-library/>
These might also be relevant;
[Reading/Writing MS Word files in
Python](http://stackoverflow.com/questions/188444/reading-writing-ms-word-
files-in-python)
<https://github.com/mikemaccana/python-docx>
|
python or awk comparing files
Question: I have two files that are tab delimited.I need to compare file 1 column 3 to
file 2 column 1 .If there is a match I need to write column 2 of file 2 next
to the matching line in file 1.here is a sample of my file:
file 1:
a rao rocky1 beta
b rao buzzy2 beta
c Rachel rocky2 alpha
file 2:
rocky1 highlightpath
rimper2 darkenpath
rocky2 greenpath
output:
new file:
a rao rocky1 beta highlightpath
b rao buzzy2 beta
c Rachel rocky2 alpha greenpath
the problem is file 1 is huge ! file 2 is also big but not as much. So far I
tried awk command , it worked partially. what I mean is number of lines in
file 1 and output file which is newfile should be same, which is not what I
got ! I get a difference of 20 lines.
awk 'FNR==NR{a[$3]=$0;next}{if($1 in a){p=$1;$1="";print a[p],$0}}' file1 file2 > newfile
So I thought I could try python to do it, but I am a novice at python. All I
know so far is I would like to make a dictionary for file 1 and file 2 and
compare. I know how to read a file into dictionary and then I am blank.Any
help and suggestion with the code will help. Thanks
Answer:
import sys
# Usage: python SCRIPT.py FILE1 FILE2 > OUTPUT
file1, file2 = sys.argv[1:3]
# Store info from the smaller file in a dict.
d = {}
with open(file2) as fh:
for line in fh:
k, v = line.split()
d[k] = v
# Process the bigger file line-by-line, printing to standard output.
with open(file1) as fh:
for line in fh:
line = line.rstrip()
k = line.split()[2]
if k in d:
print line, d[k]
else:
print line
|
Mouser Cart API Request
Question: I don't know if I'm going to post it here but I am trying to request to the
Mouser Cart API using python, and the suds library
def updateCart():
url = "https://mews.mouser.com/cartservice.asmx?op=UpdateCart&wsdl"
client = Client(url)
xmlns = Attribute("xmlns", "http://tempuri.org/XMLSchema.xsd")
xmlnsXSD = Attribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")
xmlnsXSI = Attribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
cartGUID = Attribute("CartGUID", "")
requestor = Attribute("Requestor", "richeve")
cartMessage = Element("CartMessage") \
.append(xmlns) \
.append(xmlnsXSD) \
.append(xmlnsXSI) \
.append(cartGUID)\
.append(requestor)
partNumber = Attribute("MouserPartNumber", "941-CCS050M12CM2")
quantity = Attribute("Quantity", "5")
cartItem = Element("CartItem").append(partNumber).append(quantity)
cartMessage.append(cartItem)
xmlCartMessage = Element("xmlCartMessage").append(cartMessage)
result = client.service.UpdateCart(xmlCartMessage)
print result
print client
return True
The problem with this is that I always get operation timed out. I don't know
if their API or server is malfunctioning. Or I am missing something in my
code.
Answer: I just fought the python <-> Mouser cart API battle and won today. Here is
what I learned.
1. The timeout is caused by an incorrect endpoint at the bottom of the WSDL. It specifies port 9001, but there is nothing listening there. Overriding the suds client location to remove the port specification makes it work.
url = 'https://mews.mouser.com/cartservice.asmx?WSDL'
location = 'https://mews.mouser.com/cartservice.asmx'
client = Client(url, location=location, cache=None)
2. `client.service.UpdateCart()` wants a _string_ XML document. This is what worked for me:
xmlCartMessage = Document()
xmlCartMessage.append(cartMessage)
result = client.service.UpdateCart(xmlCartMessage.plain())
3. The response from Mouser is also text—a `suds.sax.text.Text` XML fragment. See <https://lists.fedoraproject.org/pipermail/suds/2011-October/001537.html> for a description of this behavior. I used <https://github.com/martinblech/xmltodict> to wrangle it into a dict.
import xmltodict
d = xmltodict.parse(result)
|
Parsing JSON with Python Requests for Django App
Question: I'm having trouble parsing this request. It looks like this:
{"randomnumber": {"id":blah, "name":blah, ... }, "randomnumber22": { ... }}
Using python requests, I retrieve the url that returns that data, and decode
it so I can try to loop through the fields. I then endup with something like:
{u'randomnumber': {u'id':u'blah', ... }, u'randomnumber22': { .. }}
And when I try to use a for-loop to stroll through the data, it complains that
I need to use numbers for string indices. How can I handle this problem
properly?
My simplified code:
import requests
network = requests.get('http://example.com')
networkoffers = network.json()
for offers in networkoffers:
offer['name']
So I'm trying to access network['randomnumber']['name'], going by my initial
example of the request data.
Answer: You are iterating through the dict's keys, so you need to account for this in
your `for` loop like this:
for offer in networkoffers: # will look through keys, which are strings and not dicts
networkoffers[offer]['name']
`networkoffers` is a `dict`, and `offers` (or `offer`, note the discrepancy)
is a key (a `string`). `offers['name']` means nothing to Python, since offers
is a string. But `networkoffers[offers]` is a dict (a value of
`networkoffers`).
|
Scipy Sparse - distance matrix (Scikit or Scipy)
Question: I am trying to compute nearest neighbour clustering on a Scipy sparse matrix
returned from scikit-learn's `DictVectorizer`. However, when I try to compute
the distance matrix with scikit-learn I get an error message using 'euclidean'
distance through both `pairwise.euclidean_distances` and
`pairwise.pairwise_distances`. I was under the impression that scikit-learn
could calculate these distance matrices.
My matrix is highly sparse with a shape of: `<364402x223209 sparse matrix of
type <class 'numpy.float64'> with 728804 stored elements in Compressed Sparse
Row format>`.
I have also tried methods such as `pdist` and `kdtree` in Scipy but have
received other errors of not being able to process the result.
Can anyone please point me to a solution that would effectively allow me
calculate the distance matrix and/or the nearest neighbour result?
Some example code:
import numpy as np
from sklearn.feature_extraction import DictVectorizer
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import pairwise
import scipy.spatial
file = 'FileLocation'
data = []
FILE = open(file,'r')
for line in FILE:
templine = line.strip().split(',')
data.append({'user':str(int(templine[0])),str(int(templine[1])):int(templine[2])})
FILE.close()
vec = DictVectorizer()
X = vec.fit_transform(data)
result = scipy.spatial.KDTree(X)
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/scipy/spatial/kdtree.py", line 227, in __init__
self.n, self.m = np.shape(self.data)
ValueError: need more than 0 values to unpack
Similarly, if I run:
scipy.spatial.distance.pdist(X,'euclidean')
I get the following:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/scipy/spatial/distance.py", line 1169, in pdist
[X] = _copy_arrays_if_base_present([_convert_to_double(X)])
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/scipy/spatial/distance.py", line 113, in _convert_to_double
X = X.astype(np.double)
ValueError: setting an array element with a sequence.
Finally, running `NearestNeighbor` in scikit-learn results in a memory error
using:
nbrs = NearestNeighbors(n_neighbors=10, algorithm='brute')
Answer: First, you can't use `KDTree` and `pdist` with sparse matrix, you have to
convert it to dense (your choice whether it's your option):
>>> X
<2x3 sparse matrix of type '<type 'numpy.float64'>'
with 4 stored elements in Compressed Sparse Row format>
>>> scipy.spatial.KDTree(X.todense())
<scipy.spatial.kdtree.KDTree object at 0x34d1e10>
>>> scipy.spatial.distance.pdist(X.todense(),'euclidean')
array([ 6.55743852])
Second, from [the docs](http://scikit-learn.org/0.12/modules/neighbors.html):
> Efficient brute-force neighbors searches can be very competitive for small
> data samples. However, as the number of samples N grows, the brute-force
> approach quickly becomes infeasible.
You might want to try 'ball_tree' algorithm and see if it can handle your
data.
|
Python not calling Jython using 'subprocess' module
Question: I'm trying to call a Jython script from a Python file.
I've the **Jython file:`testing.py`**, which contains:
print "Hello"
Then, I've the **Python file`caller.py`** that contains:
import subprocess
subprocess.call(['jython', 'testing.py'])
If I execute the python file that calls the jython script, I get an error:
Traceback (most recent call last):
File "C:\Documents and Settings\Administrador\workspace\Interfaz\bashpython.py", line 3, in <module>
subprocess.call(['jython', 'testing.py'])
File "C:\Python27\lib\subprocess.py", line 486, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python27\lib\subprocess.py", line 672, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 882, in _execute_child
startupinfo)
WindowsError: [Error 2] El sistema no puede hallar el archivo especificado
The thing is that if I change the caller.py function to call it to another
Python function instead of a Jython one, works perfectly (it prints the
`Hello`string):
import subprocess
subprocess.call(['python', 'testing.py'])
I'm using Eclipse Standard 4.3.1. and PyDev.
Thanks in advance
Answer: If `testing.py` and `caller.py` are in same folder then the above code should
work. But if they are not in same location then it is obvious that you have to
provide the location of the file.
I have `caller.py` in `/home/reuben/caller.py` and `testing.py` in
`/home/reuben/Documents/testing.py` . And I have given the full path of
testing.py in caller.py.
subprocess.call(['jython', '/home/reuben/Documents/testing.py'])
And all that is working for me.
|
mpi4py Send/Recv with tag
Question: How can I pass a the rank of a process as a tag to the
mpi4py.MPI.COMM_WORLD.Send() function and correctly receive it with
mpi4py.MPI.COMM_WORLD.Recv()?
I'm referring to the following code example for [sending and receiving
messages between two processes using Send and Recv
functions](http://jeremybejarano.zzl.org/MPIwithPython/pointToPoint.html)
#passRandomDraw.py
import numpy
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
randNum = numpy.zeros(1)
if rank == 1:
randNum = numpy.random.random_sample(1)
print "Process", rank, "drew the number", randNum[0]
comm.Send(randNum, dest=0)
if rank == 0:
print "Process", rank, "before receiving has the number", randNum[0]
comm.Recv(randNum, source=1)
print "Process", rank, "received the number", randNum[0]
I want to pass the rank of the sending process as a tag so that the receiving
process can identify it in case there are multiple senders. This is what I do
#passRandomDraw.py
import numpy
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
randNum = numpy.zeros(1)
rnk = -1 # EDIT
if rank == 1:
randNum = numpy.random.random_sample(1)
print "Process", rank, "drew the number", randNum[0]
comm.Send(randNum, dest=0, tag=rank) # EDIT
if rank == 0:
print "Process", rank, "before receiving has the number", randNum[0]
print "Sender rank:", rnk
comm.Recv(randNum, 1, rnk) # EDIT
print "Process", rank, "received the number", randNum[0]
print "Sender rank:", rnk # EDIT
I expect the value of rnk to be 1 for the receiving process (which has
rank=0), but it is still -1.
Can someone tell me what I'm doing wrong here? Thanks!
Answer: The function `Recv` will store a received message inside a variable. You have
to supply the rank of the expected sender. Thus you always know who the sender
is. A message passing interface does never need to identify someone, that
information is always intrinsic to the system.
If you expect multiple message from the same sender you can distinguish these
using tags. You need to supply these tags yourself, there is no natural way to
obtain these. Just label the messages somehow, number them.
If you have a tag, the `Recv` function will only return when a message has
been received which has a fitting source **and** tag. This is a blocking
function call.
In your case, `tag=-1` is equal to the universal constant `MPI.ANY_TAG`
(verify via `print MPI.ANY_TAG`) and thus the `Recv` will accept any tag. But
it will in no way overwrite its input variable `rnk`. Try `rnk = -2 # EDIT`
and you'll see.
You can write your code differently, though this will not change the
underlying logic (i.e. you as a programmer must always know the sender) it
just hides it, makes it implicit:
#passRandomDraw.py
import numpy
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
randNum = numpy.zeros(1)
rnk = -1 # EDIT
if rank == 1:
randNum = numpy.random.random_sample(1)
print "Process", rank, "drew the number", randNum[0]
comm.Send(randNum, dest=0, tag=rank) # EDIT
if rank == 0:
print "Process", rank, "before receiving has the number", randNum[0]
print "Sender rank:", rnk
status = MPI.Status()
comm.Recv(randNum, source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG, status=status) # EDIT
rnk = status.Get_source()
print "Process", rank, "received the number", randNum[0]
print "Sender rank:", rnk # EDIT
|
Why don't a singleton-shaped Thread-subclass instance's attributes of type Event return the same value?
Question: I have this part of code:
from threading import Thread, Event
class mySubThread(Thread):
instance = []
def __new__(cls):
if not cls.instance:
cls.instance.append(object.__new__(cls))
return cls.instance[0]
def __init__(self):
self.enabled = Event()
self.exit = Event()
Thread.__init__(self)
def run(self):
while self.enabled.wait():
if self.exit.is_set():
break
# ... boring useful stuff ...
enable = lambda self: self.enabled.set()
disable = lambda self: self.enabled.clear()
def quit(self):
self.enabled.set()
self.exit.set()
When I set attributes which are instances of class `Event`, I get different
values from their method `.is_set()` whether I take the attribute from
`mySubThread()` or a name which is initialised as equal to it. And if I get
the method from `mySubThread()`, then, from the named one, I see the value
obtained is then equal to `mySubThread.attr.is_set()`. To make it more clear
(even to me, what I wrote seems a bit confused), I have:
>>> named = mySubThread()
>>> named.enabled.is_set()
False
>>> named.enable()
>>> named.enabled.is_set()
True
>>> named is mySubThread()
True
>>> mySubThread().enabled.is_set()
False
>>> named.enabled.is_set()
False
While `mySubThread().enable()` sets `x.enabled.is_set()` to `True`,
`mySubThread().enabled.is_set()` is always `False`.
Does anyone know if I did anything wrong, or is it a bug in Python?
I work on OS X.9.1 with Python 3.3.3 and GCC 4.2.1.
Answer: `__init__` is called on the object returned from `__new__`. When you call
`mySubThread()` the second time, your `__new__` returns a reference to the
`named` object, and your `__init__` overwrites its attributes.
|
Python Pysftp Error
Question: My code:
import pysftp
s = pysftp.Connection(host='test.rebex.net', username='demo', password='password')
data = s.listdir()
s.close()
for i in data:
print i
I'm getting an error trying to connect to a SFTP server using pysftp.
This should be straight forward enough but I get the error below:
Traceback (most recent call last):
File "/Users/gavinhinfey/Documents/Python Files/sftp_test.py", line 3, in <module>
s = pysftp.Connection(host='test.rebex.net', username='demo', password='password')
File "build/bdist.macosx-10.6-intel/egg/pysftp.py", line 55, in __init__
File "build/bdist.macosx-10.5-intel/egg/paramiko/transport.py", line 303, in __init__
paramiko.SSHException: Unable to connect to test.rebex.net: [Errno 60] Operation timed out
Exception AttributeError: "'Connection' object has no attribute '_tranport_live'" in <bound method Connection.__del__ of <pysftp.Connection object at 0x101a5a810>> ignored
I've tried using different versions of python (mostly 2.7), I have all
dependencies installed and I tried numerous sftp connections. I'm using OS X
10.9.1.
Answer: updating the package didn't work for me, as it was already up-to-date (latest
for python 2.7 at least)
Found a better aproach
[here](https://bitbucket.org/dundeemt/pysftp/issues/97/pysftp-029-breaks-
builds).
1) You can manualy add the ssh key to the known_hosts file
ssh test.rebex.net
2) Or you can set a flag to ignore it
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None # disable host key checking.
with pysftp.Connection('host', username='me',private_key=private_key,
private_key_pass=private_key_password,
cnopts=cnopts) as sftp
# do stuff here
|
python 2.7 : appending log return to csv
Question: With the following code I'm trying to grab data from a website every 5 mins,
timestamp it, calculate its logn return and append all that to a csv file.
Grabbing the data, time stamping it and appending to csv works, but when I try
to figure out how to include the log return I'm kind of stuck.
import time
from time import strftime, gmtime
import numpy as np
import urllib2
from urllib2 import urlopen
from math import log
coiAr = []
dateAr = []
logReAr = []
def mcapGrab():
while True:
try:
sourceCode = urllib2.urlopen('http://coinmarketcap.com').read()
mcapUSD = sourceCode.split('<strong>Total Market Cap: <span id="total-marketcap" data-usd="')[1].split('"')[0]
coiAr.append(float(mcapUSD.replace(',','')))
date = strftime('%d %b %Y %H:%M:%S', gmtime())
dateAr.append(date)
# if len(coiAr) > 0:
# indexLog = 1
# logRe = log(coiAr[indexLog]/coiAr[indexLog-1])
# logReAr.append(logRe)
# indexLog += 1
# else:
# logReAr.append(0)
for eachMcap in coiAr:
saveLine = date+','+str(eachMcap)+'\n'
saveFile = open('mcapdata.csv', 'a')
saveFile.write(saveLine)
saveFile.close()
s = 0
print dateAr[s]+','+str(coiAr[s])
time.sleep(300)
s+= 1
except Exception, e:
print 'Failed to grab market cap', str(e)
mcapGrab()
I've commented out the section where I attempt to calc and append log return
but doesn't work.
Any help would be appreciated!
Answer: Don't use global lists; just write each entry to the file _as you find it_.
Using the `csv` module would make this all a bit easier still:
import csv
sourceCode = urllib2.urlopen('http://coinmarketcap.com').read()
mcapUSD = sourceCode.split('<strong>Total Market Cap: <span id="total-marketcap" data-usd="')[1].split('"')[0]
mcap = float(mcapUSD.replace(',','')
# read previous value from the CSV first
with open('mcapdata.csv', 'rb') as infh:
last = None
for row in csv.reader(infh):
last = row[1] # second column
# Now calculate the log value based on the last value
logRe = log(mcap/float(last))
# write new values
with open(mcapdata.csv', 'ab') as outfh:
date = strftime('%d %b %Y %H:%M:%S', gmtime())
csv.writer(outfh).writerow([date, mcap, logRe])
This code will read the `mcapdata.csv` file, picking out just the last value
written to it. You could instead also keep all of the rows in memory and just
picking out the last entry in a list of lists.
|
Scrapy: How do I set an HTTP proxy to connect to HTTPS websites (HTTP works)?
Question: I'm using a middleware to enable a proxy like this:
I have this in settings.py
HTTP_PROXY='127.0.0.1:8080'
This is my middleware
from mybot.settings import HTTP_PROXY
class ProxyMiddleware(object):
def process_request(self, request, spider):
request.meta['proxy'] = 'http://%s' % HTTP_PROXY
It works fine for HTTP sites but not for HTTPS. What am I doing wrong? I have
tested the proxy using curl and it can connect to HTTPS without a problem.
This is the error:
[<twisted.python.failure.Failure <class 'twisted.internet.error.ConnectionDone'>>]
Answer: You need to enable proxy for **http** and **https** both. For example in
Windows, you can do it directly from shell like
set http_proxy = 127.0.0.1:8080
set https_proxy = 127.0.0.1:8080
|
NotImplementedError Django Command
Question: I created a simple django command and when I want to test it from the command
line (terminal) I get a NotImplementedError.
My code:
from django.db import models
from django.core.management.base import NoArgsCommand
from email.mime.text import MIMEText
import logging
from datetime import date, timedelta
logger = logging.getLogger('dataimport')
class Command(NoArgsCommand):
def handele_noargs(self, **options):
# Sending all the errors
logger.info("test")
The error I get:
> Traceback (most recent call last):
>
> File "manage.py", line 11, in execute_manager(settings)
>
> File "/.../python2.7/site-packages/django/core/management/**init**.py", line
> 459, in execute_manager utility.execute()
>
> File "/.../python2.7/site-packages/django/core/management/**init**.py", line
> 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv)
>
> File "/.../python2.7/site-packages/django/core/management/base.py", line
> 196, in run_from_argv self.execute(*args, **options.**dict**)
>
> File "/.../python2.7/site-packages/django/core/management/base.py", line
> 232, in execute output = self.handle(*args, **options)
>
> File "/.../python2.7/site-packages/django/core/management/base.py", line
> 371, in handle return self.handle_noargs(**options)
>
> File "/.../python2.7/site-packages/django/core/management/base.py", line
> 378, in handle_noargs raise NotImplementedError()
>
> NotImplementedError
Answer: You made a typo:
def handele_noargs(self, **options):
should be:
def handle_noargs(self, **options):
One could only dream of having Java `@Override` annotation in Python. Or one
could write it: <http://stackoverflow.com/a/8313042/1240162>
|
How to round up to 32 using the math module (Python 3,)
Question: Is it possible to round upwords using the built-in math module? I know that
you can use math.floor() to round down, but is there a way to round up?
Currently, I use this to round:
def roundTo32(x, base=32):
return int(base * round(float(x) / base))
but that doesn't always round up.
Answer: Use [`math.ceil()`](http://docs.python.org/2/library/math.html#math.ceil) to
round float values up:
import math
def roundTo32(x, base=32):
return int(base * math.ceil(float(x) / base))
Demo:
>>> import math
>>> def roundTo32(x, base=32):
... return int(base * math.ceil(float(x) / base))
...
>>> roundTo32(15)
32
>>> roundTo32(33)
64
|
Custom pyqtSignal implementation
Question: In PyQt, you can use `QtCore.pyqtSignal()` to create custom signals.
I tried making my own implementation of the Observer pattern in place of
`pyqtSignal` to circumvent some of its limitations (e.g. no dynamic creation).
It works for the most part, with at least one difference.
**Here is my implementation so far**
class Signal:
def __init__(self):
self.__subscribers = []
def emit(self, *args, **kwargs):
for subs in self.__subscribers:
subs(*args, **kwargs)
def connect(self, func):
self.__subscribers.append(func)
def disconnect(self, func):
try:
self.__subscribers.remove(func)
except ValueError:
print('Warning: function %s not removed from signal %s'%(func,self))
The one thing noticed was a difference in how `QObject.sender()` works.
I generally stay clear of `sender()`, but if it works differently then so may
other things.
With regular `pyqtSignal` signals, the sender is always the widget closest in
a chain of signals.
In the example at the bottom, you'll see two objects, `ObjectA` and `ObjectB`.
`ObjectA` forwards signals from `ObjectB` and is finally received by Window.
With `pyqtSignal`, the object received by `sender()` is `ObjectA`, which is
the one forwarding the signal from `ObjectB`.
With the Signal class above, the object received is instead `ObjectB`, the
first object in the chain.
Why is this?
**Full example**
# Using PyQt5 here although the same occurs with PyQt4
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
object_a = ObjectA(self)
object_a.signal.connect(self.listen)
layout = QBoxLayout(QBoxLayout.TopToBottom, self)
layout.addWidget(object_a)
def listen(self):
print(self.sender().__class__.__name__)
class ObjectA(QWidget):
signal = Signal()
# signal = pyqtSignal()
def __init__(self, parent=None):
super(ObjectA, self).__init__(parent)
object_b = ObjectB()
object_b.signal.connect(self.signal.emit)
layout = QBoxLayout(QBoxLayout.TopToBottom, self)
layout.addWidget(object_b)
class ObjectB(QPushButton):
signal = Signal()
# signal = pyqtSignal()
def __init__(self, parent=None):
super(ObjectB, self).__init__('Push me', parent)
self.pressed.connect(self.signal.emit)
if __name__ == '__main__':
import sys
app = QApplication([])
win = Window()
win.show()
sys.exit(app.exec_())
[More reference](http://trevorius.com/scrapbook/python/binding-singals-
dynamically/#respond)
**Edit:**
Apologies, I should have provided a use-case.
Here are some of the limitations of using pyqtSignals:
pyqtSignal:
1. ..only works with class attributes
2. ..cannot be used in an already instantiated class
3. ..must be pre-specified with the data-types you wish to emit
4. ..produces signals that does not support keyword arguments and
5. ..produces signals that cannot be modified after instantiation
Thus my main concern is using it together with baseclasses.
Consider the following.
6 different widgets of a list-type container widget share the same interface,
but look and behave slightly different. A baseclass provides the basic
variables and methods, along with signals.
Using pyqtSignal, you would have to first inherit your baseclass from at least
QObject or QWidget.
The problem is neither of these can be use in as mix-ins or in multiple
inheritance, if for instance one of the widgets also inherits from
QPushButton.
class PinkListItem(QPushButton, Baseclass)
Using the Signal class above, you could instead make baseclasses without any
previously inherited classes (or just object) and then use them as mix-ins to
any derived subclasses.
Careful not to make the question about whether or not multiple inheritance or
mix-ins are good, or of other ways to achieve the same thing. I'd love your
feedback on that as well, but perhaps this isn't the place.
I would be much more interested in adding bits to the Signal class to make it
work similar to what pyqtSignal produces.
**Edit 2:**
Just noticed a down-vote, so here comes some more use cases.
**Key-word arguments when emitting.**
signal.emit(5)
Could instead be written as
signal.emit(velocity=5)
**Use with a Builder or with any sort of dependency injection**
def create(type):
w = MyWidget()
w.my_signal = Signal()
return w
**Looser coupling**
I'm using both PyQt4 and PyQt5. With the Signal class above, I could produce
baseclasses for both without having it depend on either.
Answer: You can do this with a metaclass that inherits from `pyqtWrapperType`. Inside
`__new__`, call `pyqtSignal()` as needed and set the attributes on the result
class.
|
virtualenv AssertionError with Red Hat Enterprise Linux Server release 6.3
Question: I am using RHEL 6.3 and have 2.6.6. I need to use the Python 2.7.6. I compiled
python from source, installed pip and virtual env.
Now I am trying in different ways:
virtualenv-2.7 testvirtualenv
virtualenv --python=/usr/local/bin/python2.7 myenv
However I am getting AssertionError. Full trace:
New python executable in testvirtualenv/bin/python2.7
Also creating executable in testvirtualenv/bin/python
Installing setuptools, pip...
Complete output from command /tmp/testvirtualenv/bin/python2.7 -c "import sys, pip; pip...ll\"] + sys.argv[1:])" setuptools pip:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv_support/pip-1.5-py2.py3-none-any.whl/pip/__init__.py", line 9, in <module>
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv_support/pip-1.5-py2.py3-none-any.whl/pip/log.py", line 8, in <module>
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv_support/setuptools-2.0.2-py2.py3-none-any.whl/pkg_resources.py", line 2696, in <module>
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv_support/setuptools-2.0.2-py2.py3-none-any.whl/pkg_resources.py", line 429, in __init__
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv_support/setuptools-2.0.2-py2.py3-none-any.whl/pkg_resources.py", line 443, in add_entry
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv_support/setuptools-2.0.2-py2.py3-none-any.whl/pkg_resources.py", line 1722, in find_in_zip
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv_support/setuptools-2.0.2-py2.py3-none-any.whl/pkg_resources.py", line 1298, in has_metadata
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv_support/setuptools-2.0.2-py2.py3-none-any.whl/pkg_resources.py", line 1614, in _has
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv_support/setuptools-2.0.2-py2.py3-none-any.whl/pkg_resources.py", line 1488, in _zipinfo_name
AssertionError: /usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/EGG-INFO/PKG-INFO is not a subpath of /usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv_support/setuptools-2.0.2-py2.py3-none-any.whl/
----------------------------------------
...Installing setuptools, pip...done.
Traceback (most recent call last):
File "/usr/local/bin/virtualenv-2.7", line 9, in <module>
load_entry_point('virtualenv==1.11', 'console_scripts', 'virtualenv-2.7')()
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv.py", line 820, in main
symlink=options.symlink)
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv.py", line 988, in create_environment
install_wheel(to_install, py_executable, search_dirs)
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv.py", line 956, in install_wheel
'PIP_NO_INDEX': '1'
File "/usr/local/lib/python2.7/site-packages/virtualenv-1.11-py2.7.egg/virtualenv.py", line 898, in call_subprocess
% (cmd_desc, proc.returncode))
OSError: Command /tmp/testvirtualenv/bin/python2.7 -c "import sys, pip; pip...ll\"] + sys.argv[1:])" setuptools pip failed with error code 1
Answer: I had the same problem. What I found and how I solve it:
There is an issue with the virtualenv 1.11 version:
<https://bitbucket.org/pypa/setuptools/issue/129/assertionerror-egg-info-pkg-
info-is-not-a>
My solution:
Start again the installation specifying an older version of virtualenv.
(1.10.1 is ok)
/usr/local/bin/easy_install-2.7 virtualenv==1.10.1
Then you can proceed with the rest of the installation:
virtualenv-2.7 testvirtualenv
|
What is the best way to capture output from a process using python?
Question: I am using python's `subprocess` module to start a new process. I would like
to capture the output of the new process in real time so I can do things with
it (display it, parse it, etc.). I have seen many examples of how this can be
done, some use custom file-like objects, some use `threading` and some attempt
to read the output until the process has completed.
[**File Like Objects Example (click
me)**](http://stackoverflow.com/questions/2297933/creating-a-custom-sys-
stdout-class)
* I would prefer not to use custom file-like objects because I want to allow users to supply their own values for `stdin`, `stdout` and `stderr`.
[**Threading Example (click
me)**](http://codereview.stackexchange.com/questions/6567/how-to-redirect-a-
subprocesses-output-stdout-and-stderr-to-logging-module/17959#17959)
* I do not really understand why threading is required so I am reluctant to follow this example. If someone can explain why the threading example makes sense I would be happy listen. However, this example also restricts users from supplying their own `stdout` and `stderr` values.
**Read Output Example (see below)**
The example which makes the most sense to me is to read the `stdout`, `stderr`
until the process has finished. Here is some example code:
import subprocess
# Start a process which prints the options to the python program.
process = subprocess.Popen(
["python", "-h"],
bufsize=1,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# While the process is running, display the output to the user.
while True:
# Read standard output data.
for stdout_line in iter(process.stdout.readline, ""):
# Display standard output data.
sys.stdout.write(stdout_line)
# Read standard error data.
for stderr_line in iter(process.stderr.readline, ""):
# Display standard error data.
sys.stderr.write(stderr_line)
# If the process is complete - exit loop.
if process.poll() != None:
break
My question is,
**Q.** Is there a recommended approach for capturing the output of a process
using python?
Answer: First, your design is a bit silly, since you can do the same thing like this:
process = subprocess.Popen(
["python", "-h"],
bufsize=1,
stdout=sys.stdout,
stderr=sys.stderr
)
… or, even better:
process = subprocess.Popen(
["python", "-h"],
bufsize=1
)
However, I'll assume that's just a toy example, and you might want to do
something more useful.
* * *
The main problem with your design is that it won't read anything from `stderr`
until `stdout` is done.
Imagine you're driving an MP3 player that prints each track name to stdout,
and logging info to stderr, and you want to play 10 songs. Do you really want
to wait 30 minutes before displaying any of the logging to your users?
If that _is_ acceptable, then you might as well just use `communicate`, which
takes care of all of the headaches for you.
Plus, even if it's acceptable for your model, are you sure you can queue up
that much unread data in the pipe without it blocking the child? On every
platform?
Just breaking up the loop to alternate between the two won't help, because you
could end up blocking on `stdout.readline()` for 5 minutes while `stderr` is
piling up.
So that's why you need some way to read from both at once.
* * *
How do you read from two pipes at once?
This is the same problem (but smaller) as handling 1000 network clients at
once, and it has the same solutions: threading, or multiplexing (and the
various hybrids, like doing green threads on top of a multiplexor and event
loop, or using a threaded proactor, etc.).
The best sample code for the threaded version is
[`communicate`](http://hg.python.org/cpython/file/7f176a45211f/Lib/subprocess.py#l880)
from the 3.2+ source code. It's a little complicated, but if you want to
handle all of the edge cases properly on both Windows and Unix there's really
no avoiding a bit of complexity.
For multiplexing, you can use the
[`select`](http://docs.python.org/3/library/select.html) module, but keep in
mind that this only works on Unix (you can't `select` on pipes on Windows),
and it's buggy without 3.2+ (or the `subprocess32` backport), and to really
get all the edge cases right you need to add a signal handler to your
`select`. Unless you really, really don't want to use threading, this is the
harder answer.
But the _easy_ answer is to use someone else's implementation. There are a
dozen or more modules on PyPI specifically for async subprocesses.
Alternatively, if you already have a good reason to write your app around an
event loop, just about every modern event-loop-driven async networking library
(including the stdlib's
[`asyncio`](http://docs.python.org/dev/library/asyncio.html)) includes
subprocess support out of the box, that works on both Unix and Windows.
* * *
> Is there a recommended approach for capturing the output of a process using
> python?
It depends on who you're asking; a thousand Python developers might have a
thousand different answers… or at least half a dozen. If you're asking what
the core devs would recommend, I can take a guess:
If you don't need to capture it asynchronously, use `communicate` (but make
sure to upgrade to at least 3.2 for important bug fixes). If you do need to
capture it asynchronously, use `asyncio` (which requires 3.4).
|
Why is Django calling my datetimes naive when they are not?
Question: I've got a blog system I'm building in Django 1.6, and I'm trying to render a
YearArchiveView, or at least get a list of years with posts, from my Post
model's DateTimeField, pub_date. It keeps telling me my pub_date is naive, but
I've explicitly changed them not to be.
Here's some puttering I've done on the python shell:
>>> for post in posts:
... post.pub_date
...
datetime.datetime(2014, 1, 14, 3, 23, 2, tzinfo=<UTC>)
datetime.datetime(2014, 1, 14, 3, 23, 2, tzinfo=<UTC>)
datetime.datetime(2014, 1, 14, 3, 23, 2, tzinfo=<UTC>)
datetime.datetime(2014, 1, 14, 3, 23, 2, tzinfo=<UTC>)
datetime.datetime(2014, 1, 14, 3, 23, 2, tzinfo=<UTC>)
datetime.datetime(2014, 1, 14, 3, 23, 2, tzinfo=<UTC>)
datetime.datetime(2014, 1, 14, 3, 23, 2, tzinfo=<UTC>)
>>> years = Post.live.datetimes('pub_date', 'year', order='DESC')
/Users/.../django/db/models/fields/__init__.py:903: RuntimeWarning: DateTimeField Post.pub_date received a naive datetime (2014-01-13 21:40:01.051109) while time zone support is active.
RuntimeWarning)
>>> years
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/.../django/db/models/query.py", line 71, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/Users/.../db/models/query.py", line 96, in __iter__
self._fetch_all()
File "/Users/.../django/db/models/query.py", line 854, in _fetch_all
self._result_cache = list(self.iterator())
File "/Users/.../django/db/models/sql/compiler.py", line 1107, in results_iter
raise ValueError("Database returned an invalid value "
ValueError: Database returned an invalid value in QuerySet.dates(). Are time zone definitions and pytz installed?
>>> import pytz
>>> posts[0].posted
datetime.datetime(2013, 9, 26, 0, 48, 8, tzinfo=<UTC>)
>>>
What the hell is going on? I'm going crazy!
Answer: Check that `USE_TZ` is true. See the
[docs](https://docs.djangoproject.com/en/dev/releases/1.6/#queryset-dates-
returns-date-objects) on Django 1.6 changes to queryset.dates
|
How to Install pre-requisites with setup.py
Question: I have pure python package that relies on 3 other python packages: I'm using
distutils.core.setup to do the installation.
This is my code from setup.py:
from distutils.core import setup
setup(
name='mypackage',
version='0.2',
scripts=['myscript'],
packages=['mypackage'],
install_requires=[
'netifaces > 0.5',
'IPy > 0.75',
'yaml > 3.10'])
I specified the modules I need with install_requires, but it seems to have no
effect when I run
python ./setup.py install
How can I ensure that the modules that mypackage depends on are installed?
Answer: `distutils` has no functionality for downloading, or even verifying,
prerequisites; its `install_requires` is only there for documentation.
If you want that, you need the third-party library
[`setuptools`](https://pypi.python.org/pypi/setuptools).
Most people already have `setuptools`, and hopefully `pip`, and will be using
them to install your package anyway (assuming you plan to distribute over
PyPI), but if you include the `setuptools` bootstrap, it will take care of
installing `setuptools` if needed to install those dependencies.
|
Python: Is there syntax-level support for unpacking, from tuples, the arguments to an *anonymous* function?
Question: Suppose we have the following:
args = (4,7,5)
def foo(a,b,c): return a*b%c
Python conveniently allows tuple unpacking:
foo(4,7,5) # returns 3
foo(*args) # returns foo(4,7,5), i.e. 3
So that we don't have to do this:
foo(t[0], t[1], t[2]) # a repulsive, verbose, and error-prone synonym
Now suppose we had a list of similar 3-tuples and wanted a list of `foo(t)`
for each tuple `t`. There is "one obvious way to do it":
list(map(lambda t: foo(*t), listoftuples))
But now suppose `foo` is just a throw-away function. We don't want rubbish
polluting our namespace. Let's sweep it under the rug of anonymity!:
list(map(lambda t: (lambda a, b, c: a*b%c)(*t), listoftuples))
Well, we now have nested lambdas. Sure, we can parse that. But we run the risk
of being mistaken for a schemer who delights in constructing cryptic spells
for the sole purpose of stumping those presumptuous enough to review our code.
Furthermore, this is kinda verbose for such a simple idea. This just does not
seem pythonic. (In scala, the equivalent of that inner lambda is `(_*_%_)`,
assuming context allows type inference. If this _was_ pythonic, wouldn't it be
similarly concise?).
We could remove that inner lambda this way:
list(map((lambda t: t[0] * t[1] % t[2]), listoftuples))
That's shorter, but repulsive. I have found that using magic numbers (rather
than names) to refer to parameters tends to cause errors.
It would be great if it looked much more like this:
list(map((lambda a, b, c: a*b%c), listoftuples))
Of course, it couldn't be that. That's like trying to call `foo(args)`. We
need an asterisk, so to speak. Here's one possible asterisk:
def unpackInto(func): return lambda t: func(*t)
It makes for pleasantly readable code:
list(map(unpackInto(lambda a, b, c: a*b%c), listoftuples))
But we'd have to import that from a personal module all the time. That's not
suitable for collaboration, and it's kind of annoying for one-time use.
**TL;DR**
I want `unpackInto` to be part of the language. Is it already supported in
syntax? In standard libraries?
Answer: In python2 it _was_ possible to use tuple-unpacking for this:
>>> def func((a,b,c)):
... return a+b+c
...
>>> func((1,2,3))
6
However this feature was _removed_ in python3. See [PEP
3113](http://www.python.org/dev/peps/pep-3113/). The reasons why it was
removed are:
* They are very difficult to introspect
* They don't introduce any functionality since you can create a function like:
def func(a_b_c):
a,b,c = a_b_c
And achieve the same result
* They provided ugly error messages
With this removal python currently does _not_ support what you want with any
syntax nor any stdlib function.
Since this syntax was removed with a PEP I highly doubt that the core
developers will accept your `unpack_into` function. _However_ there may be a
_small_ chance to add something like that into the
[`functools`](http://docs.python.org/3.3/library/functools.html) module which
should contain this kind of things. You should probably ask to the python
developers about this, but be sure to provide good arguments to support your
request.
|
Fitting gaussian to a curve in Python II
Question: I have two lists .
import numpy
x = numpy.array([7250, ... list of 600 ints ... ,7849])
y = numpy.array([2.4*10**-16, ... list of 600 floats ... , 4.3*10**-16])
They make a U shaped curve. Now I want to fit a gaussian to that curve.
from scipy.optimize import curve_fit
n = len(x)
mean = sum(y)/n
sigma = sum(y - mean)**2/n
def gaus(x,a,x0,sigma,c):
return a*numpy.exp(-(x-x0)**2/(2*sigma**2))+c
popt, pcov = curve_fit(gaus,x,y,p0=[-1,mean,sigma,-5])
pylab.plot(x,y,'r-')
pylab.plot(x,gaus(x,*popt),'k-')
pylab.show()
I just end up with the noisy original U-shaped curve and a straight horizontal
line running through the curve.
I am not sure what the -1 and the -5 represent in the above code but I am sure
that I need to adjust them or something else to get the gaussian curve. I have
been playing around with possible values but to no avail.
Any ideas?
Answer: First of all, your variable `sigma` is actually variance, i.e. sigma squared
--- <http://en.wikipedia.org/wiki/Variance#Definition>. This confuses the
curve_fit by giving it a suboptimal starting estimate.
Then, your fitting ansatz, `gaus`, includes an amplitude `a` and an offset, is
this what you actually need? And the starting values are `a=-1` (negated bell
shape) and offset `c=-5`. Where do they come from?
Here's what I'd do:
* fix your fitting model. Do you want just a gaussian, does it need to be normalized. If it does, then the amplitude `a` is fixed by `sigma` etc.
* Have a look at the actual data. What's the tail (offset), what's the sign (amplitude sign).
If you're actually want just a gaussian without any bells and whistles, you
might not actually need `curve_fit`: a gaussian is fully defined by two first
moments, `mean` and `sigma`. Calculate them as you do, plot them over the data
and see if you're not all set.
|
ElementTree and UnicodeEncodeError:
Question: I'm processing the following xml file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<tag>…</tag>
Just like python documentation says:
import xml.etree.cElementTree as ET
tree = ET.parse('file.xml')
print(tree.getroot().text)
But unfortunately I've got such an error:
Traceback (most recent call last):
File "main.py", line 48, in <module>
print(tree.getroot().text)
File "C:\Python33\lib\encodings\cp852.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2026' in position 0: character maps to <undefined>
What am I doing so wrong?
Answer: Don't print the value. Processing it (what you more likely are about to do)
will work just fine.
If you really want to print it, first convert the unicode string to something
your output medium can handle (e. g. a UTF-8 encoded string). In case there
are strange characters in there, you can use this to convert at least the
rest:
byteString = value.encode(sys.stdout.encoding, 'ignore')
originalWithoutTrouble = byteString.decode(sys.stdout.encoding)
print(originalWithoutTrouble)
But of course, then some characters might be missing (in this case the
ellipsis `…`, as Martijn pointed out).
|
Jython by Keyword-Parameter passing to invoke Java methods
Question: I have this Java class,
public class sample {
public Integer foo(Integer x){
return x+5;
}
}
And with Jython I want to call `.foo` while passing "keyword-parameter" to the
argument. I ended up with the following Python code,
java_file = sample()
kwargs = {'x':3}
print java_file.foo(**kwargs)
But this results in an error,
print java_file.foo(**kwargs)
TypeError: foo(): takes no keyword arguments
Is there a way to do this? Thanks
Answer: From this [Jython FAQ](http://www.jython.org/archive/22/userfaq.html):
> **5.3 Supporting *args and **kw in Java methods**
>
> In Jython you can support keyword arguments on Java methods by defining a
> method like so (the parameters are the important point):
>
>
> public PyObject foo(PyObject[] args, String[] keywords);
>
>
> The keywords array contains all of the keywords for the keyword-defined
> arguments. For example, if you called foo with:
>
>
> foo(1,2,3,four=4,five=5)
>
>
> args would be: [1, 2, 3, 4, 5] and keywords would be: ['four', 'five'] (an
> array of 2 elements.)
>
> Additionally, you can use the experimental argument parser
> org.python.core.ArgParser to deal with mapping these two arrays. Consult the
> Javadocs (or source) for further details on org.python.core.ArgParser.
In the example above, the sample class might look like this:
public class sample {
public Integer foo(PyObject[] args, String[] keywords) {
ArgParser argParser = new ArgParser("foo", args, keywords, "x");
Integer x = argParser.getInt(0);
return x + 5;
}
}
|
Async Thread Deadlock in Julia When Used With PyCall
Question: I'm trying to implement a basic client-server socket structure using Python
and Julia, where the producer is in Python and the consumer is in Julia.
My code on the Python side looks like this:
def startServer(host='127.0.0.1', port=4002):
connected = False
s = socket.socket()
s.bind((host, port))
s.listen(5)
scon, addr = s.accept()
print 'Got connection from', addr
return scon, addr
On the Julia side, it looks like this:
using PyCall
@pyimport server as sdlib
@async begin
sleep(10)
print("In the async thread\n")
s,a = sdlib.startServer("127.0.0.1",4002)
print("Server started\n")
end
print("After the async thread\n")
print("Connecting...\n")
connected = false
while !connected
try
connected = true
c = connect(4002)
print("Connected = $(connected), $(c)\n")
catch ex
print("$(ex)\n")
connected = false
sleep(1)
end
end
print("Connection established: $(c)\n")
The output looks like this:
After the async thread
Connecting...
connect: connection refused (ECONNREFUSED)
connect: connection refused (ECONNREFUSED)
connect: connection refused (ECONNREFUSED)
connect: connection refused (ECONNREFUSED)
connect: connection refused (ECONNREFUSED)
connect: connection refused (ECONNREFUSED)
connect: connection refused (ECONNREFUSED)
connect: connection refused (ECONNREFUSED)
connect: connection refused (ECONNREFUSED)
connect: connection refused (ECONNREFUSED)
In the async thread
What seems to be happening is that as soon as the Python listener starts, the
thread locks waiting for a connect. Control never seems to pass back to the
main thread to allow the client to connect.
Appreciate any help I can get on this.
Thanks, Ravi
Answer: I am way outside my area of knowledge here, but as nobody answers in 10 hours,
I will make an attempt.
I think the problem is that julia does not have an aggressive scheduler. You
can use concurrency features, but they will be scheduled cooperatively in the
same process. Since PyCall does not return or call a (julia?) sleep, the
control will not return to the client. You might try addprocs or start julia
with -p 2, but I'm not sure it will help.
See also <http://docs.julialang.org/en/release-0.2/manual/parallel-computing/>
where this is much better explained.
|
Calling methods of a Java subclass using Jython
Question: I have this Java class,
public class sample {
public Integer foo1(Integer x){
return x+5;
}
}
class SubClass extends sample{
public Integer foo2(Integer x){
return x+100;
}
}
And with Jython I want to call `foo2` of the class `SubClass`. I ended up with
the following Python code,
import SubClass, sample
java_file = SubClass()
print java_file.foo2(3)
But running the Python code returns this error,
AttributeError: 'SubClass' object has no attribute 'foo2'
I also want to print the super class of a class and it's signature including
the attributes like public, abstract, etc.
Is there a way to do this? Thanks!
Answer: You have to first create a instance... the invoke the method... like the
following example:
Beach.java
public class Beach {
private String name;
private String city;
public Beach(String name, String city){
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Using Beach.java in Jython
>>> import Beach
>>> beach = Beach("Cocoa Beach","Cocoa Beach")
>>> beach.getName()
u'Cocoa Beach'
>>> print beach.getName()
Cocoa Beach
You can read more
[here](http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html#using-
java-within-jython-applications)
|
Predefine routine in scala sbt console?
Question: I am recently writing scala, using sublimetext to write *.scala and run sbt in
another window.
When I use sbt console to debug, every time I need to manually import packages
and do routines.
It's really annoying to repeat copying codes again and again after I recompile
and restart console.
I wonder is there a way to set a predefined environment to do it manually?
Another question I want to know is in console REPL can I auto complete lines
by the initial characters? For example in python IDLE one can use Alt+p to
search history. It's really convenience.
Answer: ### Initial commands
You could add this line to your `build.sbt`:
initialCommands in console := "import scalaz._, Scalaz._"
Result:
$ sbt console
[info] Starting scala interpreter...
[info]
import scalaz._
import Scalaz._
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
Type in expressions to have them evaluated.
Type :help for more information.
scala>
### REPL auto complete
You could tap `Tab` key to get limited auto complete:
scala> List(1, 2, 3)
res0: List[Int] = List(1, 2, 3)
scala> res0.ap
First `Tab` \- auto complete and options:
scala> res0.apply
apply applyOrElse
Second `Tab` \- method signature:
scala> res0.apply
def apply(n: Int): A
### History
You could use `Ctrl+R` to search in history (including history from previous
REPL sessions). Use addition `Ctrl+R` to get next result.
|
Python - OSError: [WinError 17] The system cannot move the file to a different disk drive:
Question: I'm using
os.rename()
to try to move pdf files between drives. Attempting this I receive the error:
OSError: [WinError 17] The system cannot move the file to a different disk drive
Is anyone aware of a function which contains similar functionality to
os.rename and allows for across disk file transfer?
Answer: `os.rename()` change the path of the file but doesn't move its actual data on
the disk. this is why you can't move (rename) it from one drive to another.
moving between drives is actually copy it first, and then delete the source
file. you can use `shutil.move()` method which do it when you trying to
transfer files between two drives
import shutil
shutil.move(src,dest)
|
Python2.7, the use of import matplotlib results in function output being assigned to a list twice
Question: I've been testing the use of an accumulate function in the following python
code. This code works well in producing the correctly accumulated output,
however it assigns the output to the list "test" twice. If I comment out
'import matplotlib', it only assigns it once. I need to use matplotlib for the
rest of the code I'll be developing. I'd appreciate if anyone has some
suggestions about why this might be/ a workaround? Thanks:
#!/usr/bin/env python2.7
import os
import sys
import numpy as np
import matplotlib
import math
from itertools import groupby, islice
def accumulate(iterable): # in py 3 use itertools.accumulate
''' Simplified version of accumulate from python 3'''
it = iter(iterable)
total = next(it)
yield total
for element in it:
total += element
yield total
print total
x=[1,2,3,4]
test=list(accumulate(x))
print "test: ", test # why does this print twice when matplotlib is imported?
Answer: It doesn't when I save this code in a text file named "test.py" with chmod 755
and run with "./test.py" on my linux box. I get
10
test: [1, 3, 6, 10]
the 10 presumably comes from the line
print total
If I comment out the line
import matplotlib
it gives the same output
|
How to use the sublime plugin api to create a new layout and open a file in each cell
Question: I'm trying to write a plugin that will allow me to open a group of related
files in one go. The premise being:
1. The plugin presents the user with a list of directories (ostensibly self contained ui components)
2. The user chooses a directory
3. The plugin creates a new 3 column layout
4. A .js file is opened in the first column from the selected directory
5. A .html file is opened in the second column from the selected directory
6. A .scss file is opened in the third column from the selected directory
So far, I've got the plugin presenting the user with a choice of directories,
and creating the three column layout, but I can;t figure out how to traverse
the three column layout to open files in new views
import sublime, sublime_plugin, os
class OpenSesameCommand(sublime_plugin.TextCommand):
def run(self, edit):
#This is the directory where the components are kept
self.thedir = '/Users/tom/Documents/Tradeweb/tradeweb-uscc/src/js/components'
self.window = sublime.active_window()
#Get all directories in the component directory
self.listings = [ name for name in os.listdir(self.thedir) if os.path.isdir(os.path.join(self.thedir, name)) ]
#Show all directories in the quick panel
self.window.show_quick_panel(self.listings, self.open_component, sublime.MONOSPACE_FONT)
def open_component(self, index):
# Generate file paths to the relevant files
compName = self.listings[index]
jsFile = self.create_file_ref(compName, 'js')
htmlFile = self.create_file_ref(compName, 'html')
sassFile = self.create_file_ref(compName, 'scss')
#create a new layout
self.window.set_layout({
"cols": [0.0, 0.3, 0.6, 1.0],
"rows": [0.0, 1.0],
"cells": [ [0, 0, 1, 1], [1, 0, 1, 1], [2, 0, 2, 1]]
})
# ??? how can I set the focus on different columns
#open files
#self.window.open_file(htmlFile)
#self.window.open_file(jsFile)
#self.window.open_file(sassFile)
def create_file_ref(self, component, type):
componentDir = self.thedir + '/' + component + '/'
return componentDir + component + '.' + type
Looking through the
[API](http://www.sublimetext.com/docs/2/api_reference.html) I get the
impression it's going to have something to do with the `view` and `group`
related methods on the `Window` object but I can't for the life of me piece it
together.
If someone could point out how I could open a file in the third column for
example, I'm sure I could take it from there.
BTW: This is the first time I've used python so please forgive any bad-
practices (but please point them out).
Answer: You'll want to use
self.window.focus_group(0)
self.window.open_file(htmlFile)
self.window.focus_group(1)
self.window.open_file(jsFile)
self.window.focus_group(2)
self.window.open_file(sassFile)
or, equivalently,
for i, file in enumerate([htmlFile, jsFile, sassFile]):
self.window.focus_group(i)
self.window.open_file(file)
To set the layout, use
[this](http://www.sublimetext.com/forum/viewtopic.php?f=6&t=7284) reference. A
cache is
[here](http://webcache.googleusercontent.com/search?q=cache%3Awww.sublimetext.com%2Fforum%2Fviewtopic.php%3Ff%3D6%26t%3D7284),
'cause it's down all the time.
|
How do I get MathJax to enable the mhchem extension in ipython notebook
Question: Okay, this has been a very frustrating adventure for me. I have spent many
hours over several successive days trying to get MathJax to enable and
recognize the mhchem extension within a Markdown cell in ipython notebook.
Math expressions worked fine, but the mhchem macros `\ce` `\cf` `\cee` just go
unrecognized. I have tried enabling the extension in the
`MathJax/config/default.js` file. I tried putting the following script code
with the Markdown window
<script type="text/x-mathjax-config">
MathJax.Hub.Config({TeX: {extensions:["TeX/mhchem.js"]}
...
});
</script>
I have tried every trick and tip I could find on the internet. Nothing seems
to work.
I am running debian wheezy. I thought maybe the default mhchem and MathJax
packages were causing the problem, so I installed a custom version of MathJax
for ipython notebook into my profile_default/static directory and configured
ipython to use this. Again, math fine, chemistry a no go. I am able to use the
mhchem extensions directly from TeX but MathJax just refuses to load the
extension or recognize the `\ce` tags.
I am stumped!
Anyone have any ideas?
Answer: Thanks for your answer. I had tried loading the script with an without the
`Tex/`. I had tried `/ce` `\ce`. Just about everything imaginable. I finally
found a solution and it was as follows:
If I use the 'non-standard' `/require` macro within a math expression to force
load the mhchem extension everything works great.
I added the following code at the top of the Markdown cell
$$\require{mhchem}$$
Strangely, once I have done this in the first line of the first markdown cell,
it seems to work flawlessly throughout the notebook. Even from within a code
page where I was executing the following to test the mhchem extensions:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
display(Math(r'\ce{H2O}'))
Without the `/require` macro, the above code would generate the math function
correctly but the chemistry formula would simply be rendered as '\ceH2O'
By including the `/require` line, all mhchem usage in the notebook seems to
work fine.
Also, I should note that I was running the ipython packages installed from the
Debian Jesse repositories. Turns out that is still 0.13. In the end, I removed
these packages and installed 1.10 directly using the setuptools. The MathJax
worked out of the box with this install.
Anyway, hopefully, this will save some other poor chemistry user some
frustration
|
input() error - NameError: name '...' is not defined
Question: I am getting an error when I try to run this simple python script:
input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)
Lets say I type in "dude", the error I am getting is:
line 1, in <module>
input_variable = input ("Enter your name: ")
File "<string>", line 1, in <module>
NameError: name 'dude' is not defined
I am running Mac OS X 10.9.1 and I am using the Python Launcher app that came
with the install of python 3.3 to run the script.
Edit: I realized I am somehow running these scripts with 2.7. I guess the real
question is how do I run my scripts with version 3.3? I thought if I dragged
and dropped my scripts on top of the Python Launcher app that is inside the
Python 3.3 folder in my applications folder that it would launch my scripts
using 3.3. I guess this method still launches scripts with 2.7. So How do I
use 3.3?
Answer: **TL;DR**
`input` function in Python 2.7, evaluates whatever your enter, as a Python
expression. If you simply want to read strings, then use `raw_input` function
in Python 2.7, which will not evaluate the read strings.
If you are using Python 3.x, `raw_input` has been renamed to `input`. Quoting
the [Python 3.0 release
notes](https://docs.python.org/3.0/whatsnew/3.0.html#builtins),
> `raw_input()` was renamed to `input()`. That is, the new `input()` function
> reads a line from `sys.stdin` and returns it with the trailing newline
> stripped. It raises `EOFError` if the input is terminated prematurely. To
> get the old behavior of `input()`, use `eval(input())`
* * *
**In Python 2.7** , there are two functions which can be used to accept user
inputs. One is
[`input`](http://docs.python.org/2/library/functions.html#input) and the other
one is
[`raw_input`](http://docs.python.org/2/library/functions.html#raw_input). You
can think of the relation between them as follows
input = eval(raw_input)
Consider the following piece of code to understand this better
>>> dude = "thefourtheye"
>>> input_variable = input("Enter your name: ")
Enter your name: dude
>>> input_variable
'thefourtheye'
`input` accepts a string from the user and evaluates the string in the current
Python context. When I type `dude` as input, it finds that `dude` is bound to
the value `thefourtheye` and so the result of evaluation becomes
`thefourtheye` and that gets assigned to `input_variable`.
If I enter something else which is not there in the current python context, it
will fail will the `NameError`.
>>> input("Enter your name: ")
Enter your name: dummy
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'dummy' is not defined
**Security considerations with Python 2.7's`input`:**
Since whatever user types is evaluated, it imposes security issues as well.
For example, if you have already loaded `os` module in your program with
`import os`, and then the user types in
os.remove("/etc/hosts")
this will be evaluated as a function call expression by python and it will be
executed. If you are executing Python with elevated privileges, `/etc/hosts`
file will be deleted. See, how dangerous it could be?
To demonstrate this, let's try to execute `input` function again.
>>> dude = "thefourtheye"
>>> input("Enter your name: ")
Enter your name: input("Enter your name again: ")
Enter your name again: dude
Now, when `input("Enter your name: ")` is executed, it waits for the user
input and the user input is a valid Python function invocation and so that is
also invoked. That is why we are seeing `Enter your name again:` prompt again.
So, you are better off with `raw_input` function, like this
input_variable = raw_input("Enter your name: ")
If you need to convert the result to some other type, then you can use
appropriate functions to convert the string returned by `raw_input`. For
example, to read inputs as integers, use the `int` function, like shown in
[this answer](http://stackoverflow.com/a/20449433/1903116).
**In python 3.x** , there is only one function to get user inputs and that is
called [`input`](http://docs.python.org/3/library/functions.html#input), which
is equivalent to Python 2.7's `raw_input`.
|
Loop with after() in Tkinter
Question: I am a newbie with Tkinter and am still very unsure of the things I am trying
to do, hopefully it is not to stupid. Every help is welcome.
I want to use my Rasberry Pi to controll some motors. These motors put
ingredients together. It works fine in Python, but I want to have a GUI with a
few buttons. Each button should put a recipe in a function makerecipe. A
recipe consists of a list of times how long the different motors should be
activated. Makerecipe will activate the the GPIO pins.
Then a new function motor should start. Here it checks when the motors should
be deactivated. It is a simpel trick which works in Python, but I don't know
how to make it work in Tkinter. Every second a loop checks whether the time
passed is equal to what is in the recipe. If this is so, the motor is
deactivated.
from Tkinter import *
import ttk
import time
root = Tk()
var = StringVar()
uitput = StringVar() #I want to print what is happening to label L2
uitput.set('Nothing') #when program starts it says
conversie = [7, 11, 15] #I will use pins 7, 11 and 15 on the RPi,
moj = [0, 0, 2] #recipe 1, through Button 1, number of seconds the pins are True
sob = [4, 0, 0] #recipe 2, through Button 2, number of seconds the pins are True
#The following function activates the pins which are used in making the recipe
#later this will just activate the pins, for now it shows it in a label on screen.
#this seems to work
def makerecipe(argu):
aa=[]
for i in range(len(argu)):
if argu[i]==0:
a=('GPIO.output(', str(conversie[i]), 'False)')
aa.append(a)
else:
b=('GPIO.output(', str(conversie[i]), 'True)')
aa.append(b)
uitput.set(aa)
root.update_idletasks()
root.motor(argu)
#Next I want to have a function that looks at recipe and reads how long the
#GPIO pins should be active. Then turns them off one at a time. I just don't
#understand the after function.
#I think, but probably wrong, that my recipe was loaded in makerecipe and argu
#has the value of the recipe because of the button, and I hoped I could pass argu
#along to the function motor.
def motor(motorinput):
resultaat=('bla')
uitput.set(resultaat)
`enter code here` cc=[]
for MotorNum in range(max(motorinput)+1):
if MotorNum in motorinput:
if motorinput.index(MotorNum)==0:
c=("GPIO.output(",conversie[motorinput.index(MotorNum)],", False)")
cc.append(c)
elif motorinput.index(MotorNum)==1:
d=("GPIO.output(",conversie[motorinput.index(MotorNum)],", False)")
cc.append(d)
elif motorinput.index(MotorNum)==2:
e=("GPIO.output(",conversie[motorinput.index(MotorNum)],", False)")
cc.append(e)
uitput.set(cc)
root.update_idletasks()
#root.after(1000, motor(alfa)) #This goes wrong.
B= Button(root, text="optie 1", command=lambda: makerecipe(moj))
B.pack()
L2=Label(root, textvariable=uitput, width=100)
L2.pack()
root.mainloop()
The reason I am printing my entire code here is that it might help to know
what the hell I am trying, it probably looks dreadful but I am trying to get
better at it.
First question is I apparently don't understand how to call the next function
motor inside my first function. It stops there and gives me: AttributeError:
motor
Second question is I know how to work with time.sleep, but I read everywhere
on this forum that you should not do this. So I am trying to use after, but
don't know how to use this properly.
I hope somebody can help this total novice. I understand the logic of Python
quite well, but Tkinter is a new way of thinking for me.
Answer: > First question is I apparently don't understand how to call the next
> function motor inside my first function. It stops there and gives me:
> AttributeError: motor
The problem is in last line of _makerecipe_ function:
root.motor(argu)
The variable _root_ is a TK object which does not have a motor function.
That's the reason for AttributeError. Changing this line to:
motor(argu)
Would remove this error.
> Second question is I know how to work with time.sleep, but I read everywhere
> on this forum that you should not do this. So I am trying to use after, but
> don't know how to use this properly.
You should use after because Tk has an eventloop running (the
_root.mainloop()_ call) to react based on events (like calling your functions
when a button is clicked, or a certain time has passed). But if you use
_time.sleep_ in your code, you might interfere with this eventloop.
The fix is that you should pass a function reference to _after_ , so Tk
eventloop would call that function when the right time comes. But here, you
are calling the function right away:
root.after(1000, motor(alfa)) #This goes wrong.
This line is calling _motor_ (and passing _alfa_ as argument) and then passing
the return value of motor (which could be anything) to _root.after_.
This line should be like this:
root.after(1000, motor, alfa)
Now we are telling _root_ to call _motor_ with the _alfa_ argument, after 1
second.
|
Python exec() when called in class breaks on lambda
Question: I'm doing code generation and I end up with a string of source that looks like
this:
**Source**
import sys
import operator
def add(a,b):
return operator.add(a,b)
def mul(a,b):
return operator.mul(a,b)
def saveDiv(a,b):
if b==0:
return 0
else:
return a/b
def subtract(a,b):
return operator.sub(a,b)
def main(y,x,z):
y = int(y)
print y
x = int(x)
print x
z = int(z)
print z
ind = lambda y,x,z: mul(saveDiv(x, add(z, z)), 1)
return ind(y,x,z)
print main(**sys.argv)""
**Execution**
When I'm executing code using `exec()` and then piping it through `stdoutIO()`
**Working**
args={'x':"1",'y':"1",'z':"1"}
source = getSource()
sys.argv = args
with stdoutIO() as s:
exec source
s.getvalue
**Not Working**
class Coder():
def start(self):
args={'x':"1",'y':"1",'z':"1"}
source = getSource()
sys.argv = args
with stdoutIO() as s:
exec source
return s.getvalue
print "out:", Coder().start()
And the `stdoutIO()` is implemented like this:
class Proxy(object):
def __init__(self,stdout,stringio):
self._stdout = stdout
self._stringio = stringio
def __getattr__(self,name):
if name in ('_stdout','_stringio','write'):
object.__getattribute__(self,name)
else:
return getattr(self._stringio,name)
def write(self,data):
self._stdout.write(data)
self._stringio.write(data)
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = Proxy(sys.stdout,stdout)
yield sys.stdout
sys.stdout = old
**Problem**
If I execute the execution code outside of the class everything works however
when I run it inside a class it breaks with this error. How can I fix it or
avoid this problem?
File "<string>", line 29, in <module>
File "<string>", line 27, in main
File "<string>", line 26, in <lambda>
NameError: global name 'add' is not defined
Thanks
Answer: When you run `exec expression`, it executes the code contained in `expression`
in the current scope (see
[here](http://docs.python.org/2/reference/simple_stmts.html#exec)). Apparently
inside a class, the function in your expression are dropping out of scope
before `main` is run. I honestly have no idea why (it seems to me like it
should work) but maybe someone can add a complete explanation in a comment.
Anyway, if you specifically provide a scope for the expression to be evaluated
in, (which is good practice anyway so that you don't pollute your namespace),
it works fine inside the class.
So, replace the line:
exec source
with
exec source in {}
and you should be right!
Here we provide an empty dictionary as a the globals() and locals()
dctionaries during the evaluation of your expression. You can keep this
dictionary if you want, or let it be garbage collected immediately as I have
demonstrated in my code. This is all explained in the exec documentation in
the link above.
|
Label textvariable wont display on secondary window. Python 3/Tkinter
Question: I want to display the same label (textvariable) on multiple windows at once
but it will only show the content on the window that is created first. The
label appears on the other but it is basically an empty field.
Something interesting to note is that if I replace `textvariable` with `text`
(and other necessary changes) It will display the static text as expected.
example code below:
from tkinter import *
root = Tk()
root.overrideredirect(1)
root2 = Tk()
root2.protocol("WM_DELETE_WINDOW", exit)
class SubsLight(Frame):
def __init__(self, parent=None, **kw):
Frame.__init__(self, parent, kw)
self.T1Subs = 'A'
self.T2Subs = 'B'
self.T1Subsstr = StringVar()
self.T2Subsstr = StringVar()
self.Subset()
def Subset(self):
self.T1Subsstr.set(self.T1Subs)
self.T2Subsstr.set(self.T2Subs)
T1Sub = Label(root, textvariable=self.T1Subsstr, font=("Arial", 20), fg='#fff188188', bg='black', width=1, padx=5, pady=5)
T2Sub = Label(root, textvariable=self.T2Subsstr, font=("Arial", 20), fg='#fff188188', bg='black', width=1, padx=5, pady=5)
T1Sub.grid()
T2Sub.grid()
T12Sub = Label(root2, textvariable=self.T1Subsstr, font=("Arial", 20), fg='#fff188188', bg='black', width=1, padx=5, pady=5)
T12Sub.grid()
T12Sub = Label(root2, textvariable=self.T2Subsstr, font=("Arial", 20), fg='#fff188188', bg='black', width=1, padx=5, pady=5)
T12Sub.grid()
sub = SubsLight(root)
def main():
sub.grid()
root.mainloop()
if __name__ == '__main__':
main()
I can get the label to display in the other window by moving `root2` to above
`root` but then I have the opposite problem.
first of all why doesn't it work as it is, and how do I get it to work as I
described.
I realize having two windows isn't a common thing, but it is necessary for
this project as one is the main display and the other is the controls.
Answer: The problem is that you have two instances of `Tk`. Tkinter is designed to
work with exactly one instance of that class. If you want more than one
window, create instances of `Toplevel`
|
Python 2.7: log displayed twice when `logging` module is used in two python scripts
Question: # Context:
Python 2.7.
Two files in the same folder:
* First: main script.
* Second: custom module.
# Goal:
Possibility to use the `logging` module without any clash (see output below).
# Files:
## a.py:
import logging
from b import test_b
def test_a(logger):
logger.debug("debug")
logger.info("info")
logger.warning("warning")
logger.error("error")
if __name__ == "__main__":
# Custom logger.
logger = logging.getLogger("test")
formatter = logging.Formatter('[%(levelname)s] %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
# Test A and B.
print "B"
test_b()
print "A"
test_a(logger)
## b.py:
import logging
def test_b():
logging.debug("debug")
logging.info("info")
logging.warning("warning")
logging.error("error")
# Output:
As one could see below, the log is displayed _twice_.
python a.py
B
WARNING:root:warning
ERROR:root:error
A
[DEBUG] debug
DEBUG:test:debug
[INFO] info
INFO:test:info
[WARNING] warning
WARNING:test:warning
[ERROR] error
ERROR:test:error
Would anyone have a solution to this?
EDIT: not running `test_b()` will cause no log duplication and correct log
formatting (expected).
Answer: I'm not sure I understand your case, because the description doesn't match the
output… but I think I know what your problem is.
As [the
docs](http://docs.python.org/2/library/logging.html#logging.Logger.propagate)
explain:
> **Note:** If you attach a handler to a logger and one or more of its
> ancestors, it may emit the same record multiple times. In general, you
> should not need to attach a handler to more than one logger - if you just
> attach it to the appropriate logger which is highest in the logger
> hierarchy, then it will see all events logged by all descendant loggers,
> provided that their propagate setting is left set to True. A common scenario
> is to attach handlers only to the root logger, and to let propagation take
> care of the rest.
And that "common scenario" usually works great, but I assume you need to
attach a custom handler to "test", without affecting the root logger.
So, if you want a custom handler on "test", and you don't want its messages
also going to the root handler, the answer is simple: turn off its `propagate`
flag:
logger.propagate = False
* * *
The reason this only happens if you call `test_b` is that otherwise, the root
logger never gets initialized. The first time you log to any logger that
hasn't been configured, it effectively does a `basicConfig()` on that logger.
So, calling `logging.getLogger().info(msg)` or `logging.info(msg)` will
configure the root logger. But propagating from a child logger will not.
I believe this is explained somewhere in the logging HOWTO or cookbook, both
under [HOWTOs](http://docs.python.org/2/howto/), but in the actual module
docs, it's buried in the middle of a note about threading under
[`logging.log`](http://docs.python.org/2/library/logging.html#logging.log):
> **Note:** The above module-level functions which delegate to the root logger
> should not be used in threads, in versions of Python earlier than 2.7.1 and
> 3.2, unless at least one handler has been added to the root logger before
> the threads are started. **These convenience functions call basicConfig() to
> ensure that at least one handler is available;** ; in earlier versions of
> Python, this can (under rare circumstances) lead to handlers being added
> multiple times to the root logger, which can in turn lead to multiple
> messages for the same event.
It's pretty easy to see how you could have missed that!
|
Factorial function works in Python, returns 0 for Julia
Question: I define a factorial function as follows in Python:
def fact(n):
if n == 1:
return n
else:
return n * fact(n-1)
print(fact(100))
and as follows in Julia:
function fact(n)
if n == 1
n
else
n * fact(n-1)
end
end
println(fact(100))
The python program returns a very large number for the evaluation of 100 (as
expected). Julia returns 0. With a smaller number (like 10) they both work.
I have two questions:
1. Why does Python handle this OK and Julia not.
2. Why doesn't Julia throw an error and just print 0 instead?
Answer: Julia has separate fixed-size integer types, plus a BigInt type. The default
type is `Int64`, which is of course 64 bits.
Since 100! takes about 526 bits, it obviously overflows an `Int64`.
You can solve this problem by just doing `fact(BigInt(100))` (assuming you've
`require`d it), or of course you can do the conversion in the `fact` function.
* * *
Python used to be the same, once upon a time. It had separate types `int`,
which was 16 or 32 or 64 bits depending on your machine, and `long`, which was
arbitrary-length. If you ran your program on Python 1.5, it would either wrap
around just like Julia, or raise an exception. The solution would be to call
`fact(100L)`, or to do the conversion to `long` inside the `fact` function.
However, at some point in the 2.x series, Python tied the two types together,
so any `int` that overflows automatically becomes a `long`. And then, in 3.0,
it merged the two types entirely, so there is no separate `long` anymore.
* * *
So, why does Julia just overflow instead of raising an error?
The FAQ actually explains [Why does Julia use native machine integer
arithmetic](http://docs.julialang.org/en/latest/manual/faq/#why-does-julia-
use-native-machine-integer-arithmetic). Which includes the wraparound behavior
on overflow.
* * *
By "native machine arithmetic", people generally mean "what C does on almost
all 2s-complement machines". Especially in languages like Julia and Python
that were originally built on top of C, and stuck pretty close to the metal.
In the case of Julia, this is not just a "default", but an intentional choice.
In C (at least as it was at the time), it's actually up to the implementation
what happens if you overflow a signed integer type like `int64`… but on almost
any platform that natively uses 2's complement arithmetic (which is almost any
platform you'll see today), the exact same thing happens: it just truncates
everything above the top 64 bits, meaning you wrap around from positive to
negative. In fact, _unsigned_ integer types are _required_ to work this way in
C. (C, meanwhile, works this way because that's how most CPUs work.)
In C (_unlike_ most CPUs' machine languages), there is no way to detect that
you've gotten an overflow after the fact. So, if you want to raise an
`OverflowError`, you have to write some logic that detects that the
multiplication will overflow before doing it. And you have to run that logic
on every single multiplication. You may be able to optimize this for some
platforms by writing inline assembly code. Or you can cast to a larger type,
but (a) that tends to make your code slower, and (b) it doesn't work if you're
already using the largest type (which `int64` is on many platforms today).
In Python, making each multiplication up to 4x slower (usually less, but it
can be that high) is no big deal, because Python spends more time fetching the
bytecode and unboxing the integer objects than multiplying anyway. But Julia
is meant to be faster than that.
As John Myles White explains in [Computers are
Machines](http://www.johnmyleswhite.com/notebook/2013/01/03/computers-are-
machines/):
> In many ways, Julia sets itself apart from other new languages by its
> attempt to recover some of the power that was lost in the transition from C
> to languages like Python. But the transition comes with a substantial
> learning curve.
* * *
But there's another reason for this: overflowing signed arithmetic is actual
useful in many cases. Not nearly as many as overflowing _unsigned_ arithmetic
(which is why C has defined unsigned arithmetic to work that way since before
the first ANSI spec), but there are use cases.
And, even though you probably want type conversions more often than you want
rollover, it is a lot _easier_ to do the type conversions manually than the
rollover. If you've ever done it in Python, picking the operand for `%` and
getting the signs right is certainly easy to get wrong; casting to `BigInt` is
pretty hard to screw up.
* * *
And finally, in a strongly-typed language, like both Python and Julia, type
stability is important. One of the reasons Python 3 exists was that the old
`str` type magically converting to `unicode` caused problems. It's far less
common for your `int` type magically converting to `long` to cause problems,
but it can happen (e.g., when you're grabbing a value off the wire, or via a C
API, and expect to write the result out in the same format). Python's dev team
argued over this when doing the `int`/`long` unification, quoting
"practicality beats purity" and various other bits of the Zen, and ultimately
deciding that the old behavior caused more problems than the new behavior
would. Julia's designed made the opposite decision.
|
How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"
Question:
as3:~/ngokevin-site# nano content/blog/20140114_test-chinese.mkd
as3:~/ngokevin-site# wok
Traceback (most recent call last):
File "/usr/local/bin/wok", line 4, in
Engine()
File "/usr/local/lib/python2.7/site-packages/wok/engine.py", line 104, in init
self.load_pages()
File "/usr/local/lib/python2.7/site-packages/wok/engine.py", line 238, in load_pages
p = Page.from_file(os.path.join(root, f), self.options, self, renderer)
File "/usr/local/lib/python2.7/site-packages/wok/page.py", line 111, in from_file
page.meta['content'] = page.renderer.render(page.original)
File "/usr/local/lib/python2.7/site-packages/wok/renderers.py", line 46, in render
return markdown(plain, Markdown.plugins)
File "/usr/local/lib/python2.7/site-packages/markdown/init.py", line 419, in markdown
return md.convert(text)
File "/usr/local/lib/python2.7/site-packages/markdown/init.py", line 281, in convert
source = unicode(source)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 1: ordinal not in range(128). -- Note: Markdown only accepts unicode input!
how to fix it?
but in some other python-based static blog apps,chinese post can be published
successfully. such as this app: <http://github.com/vrypan/bucket3> .in my site
<http://bc3.brite.biz/,chinese> post can be published successfully.
Answer: **Finally I got it:**
as3:/usr/local/lib/python2.7/site-packages# cat sitecustomize.py
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
**Let me check:**
as3:~/ngokevin-site# python
Python 2.7.6 (default, Dec 6 2013, 14:49:02)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.getdefaultencoding()
'utf8'
>>>
The above shows the default encoding of python is `utf8`. Then the error is no
more.
|
Error in for loop. (Finding three integers)
Question: So, our teacher gave us an assignment to find three integers a, b c. They are
in all between 0 and 450 using Python.
a = c + 11 if b is even
a = 2c-129 if b is odd
b = ac mod 2377
c = (∑(b-7k) from k = 0 too a-1) +142 (Edited. I wrote it wrong. Was -149)
I tired my code that looks like this: (Still a newbie. I guess a lot of my
code is wrong)
for a, b, c in range(0, 450):
if b % 2 == 0:
a = c + 11
else:
a = 2 * c - 129
b = (a * c) % 2377
c = sum(b - 7 * k for k in range(0, a - 1))
but I get the error:
for a, b, c in range(0, 450):
TypeError: 'int' object is not iterable
What am I doing wrong and how can I make it check every number between 0 and
450?
Answer:
import itertools
for b, c in itertools.product(*[range(450)]*2):
if b % 2 == 0:
a = c + 11
else:
a = 2 * c - 129
derived_b = (a * c) % 2377
derived_c = sum(b - 7 * k for k in range(0, a - 1))
if derived_b == b and derived_c == c:
print a, b, c
|
Dynamic INSERT Statement in Python
Question: I am working on updating some Python code I have been working with and was
looking for some advice on the best way to deal with an idea I am working
with. The part of my code that I wish to change is :
my_reader = csv.reader(input, delimiter = ',',quotechar='|')
mouse.executemany("INSERT INTO Example_Input (ID,Name,Job,Salary) VALUES (?,?,?,?)", my_reader)
The code works. My question is, can I change the "(?,?,?,?)" into something
more dynamic like 'range()' to allow user input. I understand that I would
also have to have a dynamic create table statement, so another solution might
be to count the number of inputs.
To be a little more clear: for example if I had raw_input("How many variables
does the table contain?: ") and the input was 2, the program would know to run
as if (?,?).
Thoughts?
(also I am using SQLite3 and python 2.7)
Answer: Assuming your csv had a header field, you could use a
[DictReader](http://docs.python.org/2/library/csv.html#csv.DictReader) and
generate the field names and parameters its
[fieldnames](http://docs.python.org/2/library/csv.html#csv.csvreader.fieldnames)
property.
The constructor for
[DictReader](http://docs.python.org/2/library/csv.html#csv.DictReader) allows
you to specify the fieldnames if they are not in the file, so you could ask
the user for that information if required.
Assuming the headers are in the file, this example code should work:
import csv
import sqlite3
#Give the table a name and use it for the file as well
table_name = 'Example'
a = open(table_name + '.csv', 'r')
#Use a dict reader
my_reader = csv.DictReader(a)
print my_reader.fieldnames # Use this to create table and get number of field values,etc.
# create statement
create_sql = 'CREATE TABLE ' + table_name + '(' + ','.join(my_reader.fieldnames) + ')'
print create_sql
#open the db
conn = sqlite3.connect('example.db')
c = conn.cursor()
# Create table using field names
c.execute(create_sql)
insert_sql = 'insert into ' + table_name + ' (' + ','.join(my_reader.fieldnames) + ') VALUES (' + ','.join(['?'] * len(my_reader.fieldnames))+ ')'
print insert_sql
values = []
for row in my_reader:
row_values = []
for field in my_reader.fieldnames:
row_values.append(row[field])
values.append(row_values)
c.executemany(insert_sql, values)
|
ignore socket.error in python
Question: using a simple code to get hostname from ip address.
#!/usr/bin/python
import socket
import os
import sys
try:
fdes = open ("ip.txt","r")
for line in fdes.readlines():
print socket.gethostbyaddr(line)
except Exception:
pass
e.g ip.txt have ip address:
> 10.10.1.10, 10.10.1.20, 10.10.1.30, 10.10.1.40, 10.10.1.50, 10.10.1.60,
> 10.10.1.70,
there is no hostname for 10.10.1.40, so the code breaks here, do not continue
further, Error is **"socket.herror:[errno 1] Unknown Host"**
how i can forcefully ignore the error if a hostname is not available for as ip
address ?
Answer: This moves the hostname related code into the try/except block, while keeping
the file reading stuff out of it; so if an exception is thrown your file
reading code will still continue.
fdes = open("ip.txt","r")
for line in fdes.readlines():
try:
print socket.gethostbyaddr(line)
except socket.error:
pass
Note: this code only ignores `socket.error` exceptions while leaving all other
exceptions unhandled (so a Ctrl+C which throws a KeyboardInterrupt will still
stop the program).
|
cogent.db.ensembl cookbook's example of .getGeneByStableId() returns 'ProgrammingError'
Question: I get an error using PyCogent to query EnsEMBl's database - could this bug
result from updates in EnsEMBL or PyCogent?
When trying to reproduce the code for the PyCogent Cookbook's [Querying
Ensembl](http://pycogent.org/examples/query_ensembl.html#query-ensembl) doc
page ("Selecting Gene's" section) I get _"ProgrammingError"._

**Here's the failing cookbook code** (I indicate the line where error occurs):
#!/usr/bin/python
import os
#----------------------------------------------------------
# Interrogating a Genome
#----------------------------------------------------------
from cogent.db.ensembl import HostAccount, Genome
human = Genome(Species='human', Release=Release, account=account)
#----------------------------------------------------------
# Selecting Genes
#----------------------------------------------------------
brca1 = human.getGeneByStableId(StableId='ENSG00000012048') #<--- ERRORS OUT HERE
print brca1.Description
**Here's the error:**
ProgrammingError: (ProgrammingError) (1146, "Table 'homo_sapiens_variation_74_37.flanking_sequence' doesn't exist") 'DESCRIBE flanking_sequence' ()
**Extra info:**
* Python 2.7.3
* PyCogent 1.5.1-2
* Ubuntu 12.04
* Ensmbl release 74
Answer: That error arises because Ensembl dropped the flanking_seq database from
release 70 on. This issue was fixed in the PyCogent github repository.
|
flask isnt reading or interpreting css file
Question: Im basically trying to follow this tutorial (
<http://net.tutsplus.com/tutorials/python-tutorials/an-introduction-to-
pythons-flask-framework/>)
Now when the css part comes in, and i copy the code it simply wont come out
styled even afterr main.css is added it still shows up unstyled like if it
wasnt importing the css file heres html code
<!DOCTYPE html>
<html>
<head>
<title>Flask</title>
<strong><link rel="stylesheet" type"text/css" href="{{ url_for('static', filename='css/main.css') }}"></strong>
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Flask App</h1>
</div>
</header>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
layout.html ^
Home.html v
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Flask app<h2>
<h3>This is the home page for the Flask app<h3>
</div>
{% endblock %}
routes.py v
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
Answer: This is probably due to the directory structure of your app. By default, flask
looks for the static directory in the same level as the file that the app
object is created in. This is the example structure for a small application
from the flask docs.
/yourapplication
/yourapplication.py
/static
/style.css
/templates
layout.html
index.html
login.html
You can also change the location of the static files by setting the
"static_folder" attribute on the app object. [Check the docs here for setting
the static_folder](http://flask.pocoo.org/docs/api/)
|
Pandas: import multiple csv files into dataframe using a loop and hierarchical indexing
Question: I would like to read multiple CSV files (with a different number of columns)
from a target directory into a single Python Pandas DataFrame to efficiently
search and extract data.
Example file:
Events
1,0.32,0.20,0.67
2,0.94,0.19,0.14,0.21,0.94
3,0.32,0.20,0.64,0.32
4,0.87,0.13,0.61,0.54,0.25,0.43
5,0.62,0.21,0.77,0.44,0.16
Here is what I have so far:
# get a list of all csv files in target directory
my_dir = "C:\\Data\\"
filelist = []
os.chdir( my_dir )
for files in glob.glob( "*.csv" ) :
filelist.append(files)
# read each csv file into single dataframe and add a filename reference column
# (i.e. file1, file2, file 3) for each file read
df = pd.DataFrame()
columns = range(1,100)
for c, f in enumerate(filelist) :
key = "file%i" % c
frame = pd.read_csv( (my_dir + f), skiprows = 1, index_col=0, names=columns )
frame['key'] = key
df = df.append(frame,ignore_index=True)
(the indexing isn't working properly)
Essentially, the script below is exactly what I want (tried and tested) but
needs to be looped through 10 or more csv files:
df1 = pd.DataFrame()
df2 = pd.DataFrame()
columns = range(1,100)
df1 = pd.read_csv("C:\\Data\\Currambene_001y09h00m_events.csv",
skiprows = 1, index_col=0, names=columns)
df2 = pd.read_csv("C:\\Data\\Currambene_001y12h00m_events.csv",
skiprows = 1, index_col=0, names=columns)
keys = [('file1'), ('file2')]
df = pd.concat([df1, df2], keys=keys, names=['fileno'])
I have found many related links, however I am still not able to get this to
work:
* [Reading Multiple CSV Files into Python Pandas Dataframe](http://stackoverflow.com/questions/15843123/reading-multiple-csv-files-into-python-pandas-dataframe)
* [Merge of multiple data frames of different number of columns into one big data frame](http://stackoverflow.com/questions/13572550/merge-of-multiple-data-frames-of-different-number-of-columns-into-one-big-data-f)
* [import multiple csv files into python pandas and concatenate into one dataframe](http://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-python-pandas-and-concatenate-into-one-dataframe)
Answer: You need to decide in what axis you want to append your files. Pandas will
always try to do the right thing by:
1. Assuming that each column from each file is different, and appending digits to columns with similar names across files if necessary, so that they don't get mixed;
2. Items that belong to the same row index across files are placed side by side, under their respective columns.
The trick to appending efficiently is to tip the files sideways, so you get
the desired behaviour to match what `pandas.concat` will be doing. This is my
recipe:
from pandas import *
files = !ls *.csv # IPython magic
d = concat([read_csv(f, index_col=0, header=None, axis=1) for f in files], keys=files)
Notice that `read_csv` is transposed with `axis=1`, so it will be concatenated
on the column axis, preserving its names. If you need, you can transpose the
resulting DataFrame back with `d.T`.
**EDIT:**
For different number of columns in each source file, you'll need to supply a
header. I understand you don't have a header in your source files, so let's
create one with a simple function:
def reader(f):
d = read_csv(f, index_col=0, header=None, axis=1)
d.columns = range(d.shape[1])
return d
df = concat([reader(f) for f in files], keys=files)
|
launch external shell python instance in shell from python
Question: I'd like to call a separate non-child python program from a python script and
have it run externally in a new shell instance. The original python script
doesn't need to be aware of the instance it launches, it shouldn't block when
the launched process is running and shouldn't care if it dies. This is what I
have tried which returns no error but seems to do nothing...
import subprocess
python_path = '/usr/bin/python'
args = [python_path, '&']
p = subprocess.Popen(args, shell=True)
What should I be doing differently
### EDIT
The reason for doing this is I have an application with a built in version of
python, I have written some python tools that should be run separately
alongside this application but there is no assurance that the user will have
python installed on their system outside the application with the builtin
version I'm using. Because of this I can get the python binary path from the
built in version programatically and I'd like to launch an external version of
the built in python. This eliminates the need for the user to install python
themselves. So in essence I need a simple way to call an external python
script using my current running version of python programatically.
I don't need to catch any output into the original program, in fact once
launched I'd like it to have nothing to do with the original program
### EDIT 2
So it seems that my original question was very unclear so here are more
details, I think I was trying to over simplify the question:
I'm running OSX but the code should also work on windows machines.
The main application that has a built in version of CPython is a compiled c++
application that ships with a python framework that it uses at runtime. You
can launch the embedded version of this version of python by doing this in a
Terminal window on OSX
/my_main_app/Contents/Frameworks/Python.framework/Versions/2.7/bin/python
From my main application I'd like to be able to run a command in the version
of python embedded in the main app that launches an external copy of a python
script using the above python version just like I would if I did the following
command in a Terminal window. The new launched orphan process should have its
own Terminal window so the user can interact with it.
/my_main_app/Contents/Frameworks/Python.framework/Versions/2.7/bin/python my_python_script
I would like the child python instance not to block the main application and
I'd like it to have its own terminal window so the user can interact with it.
The main application doesn't need to be aware of the child once its launched
in any way. The only reason I would do this is to automate launching an
external application using a Terminal for the user
Answer: If you're trying to launch a new terminal window to run a new Python in (which
isn't what your question asks for, but from a comment it sounds like it's what
you actually want):
You can't. At least not in a general-purpose, cross-platform way.
Python is just a command-line program that runs with whatever
stdin/stdout/stderr it's given. If those happen to be from a terminal, then
it's running in a terminal. It doesn't know anything about the terminal beyond
that.
If you need to do this for some specific platform and some specific terminal
program—e.g., Terminal.app on OS X, iTerm on OS X, the "DOS prompt" on
Windows, gnome-terminal on any X11 system, etc.—that's generally doable, but
the way to do it is by launching or scripting the terminal program and telling
it to open a new window and run Python in that window. And, needless to say,
they all have completely different ways of doing that.
And even then, it's not going to be possible in all cases. For example, if you
ssh in to a remote machine and run Python on that machine, there is no way it
can reach back to your machine and open a new terminal window.
On most platforms that have multiple possible terminals, you can write some
heuristic code that figures out which terminal you're currently running under
by just walking `os.getppid()` until you find something that looks like a
terminal you know how to deal with (and if you get to `init`/`launchd`/etc.
without finding one, then you weren't running in a terminal).
|
An efficient way to search similar words (with specified length) in two strings using python
Question: My input is two strings of the same length and a number which represents the
length of the common words I need to find in both strings. I wrote a very
straightforward code to do so, and it works, but it is super super slow,
considering the fact that each string is ~200K letters.
This is my code:
for i in range(len(X)):
for j in range(len(Y)):
if(X[i] == Y[j]):
for k in range (kmer):
if (X[i+k] == Y[j+k]):
count +=1
else:
count=0
if(count == int(kmer)):
loc=(i,j)
pos.append(loc)
count=0
if(Xcmp[i] == Y[j]):
for k in range (kmer):
if (Xcmp[i+k] == Y[j+k]):
count +=1
else:
count=0
if(count == int(kmer)):
loc=(i,j)
pos.append(loc)
count=0
return pos
Where the first sequence is X and the second is Y and kmer is the length of
the common words. (and when I say word, I just mean characters..)
I was able to create a X by kmer matrix (rather than the huge X by Y) but
that's still very slow.
I also thought about using a trie, but thought that maybe it will take too
long to populate it?
At the end I only need the positions of those common subsequences.
any ideas on how to improve my algorithm? Thanks!! :)
Answer: Create a set of words like this
words = {X[i:i+kmer] for i in range(len(X)-kmer+1)}
for i in range(len(Y)-kmer+1):
if Y[i:i+kmer] in words:
print Y[i:i+kmer]
This is fairly efficient as long as `kmer` isn't so large that you'd run out
of memory for the set. I assume it isn't since you were creating a matrix that
size already.
For the positions, create a dict instead of a set as Tim suggests
from collections import defaultdict
wordmap = defaultdict(list)
for i in range(len(X)-kmer+1):
wordmap[X[i:i+kmer]].append(i)
for i in range(len(Y)-kmer+1):
word = Y[i:i+kmer]
if word in wordmap:
print word, wordmap[word], i
|
How do I count only weekdays from timedelta in python
Question: I am getting the number of days until the next "billing cycle" (for example)
which starts on the `nth` day of the month:
from dateutil.relativedelta import relativedelta
dt = datetime.utcnow() + relativedelta(months=1,day=schedule.cycle_start)
days_till_next_cycle = dt - datetime.utcnow()
Where `schedule.cycle_start` is going to be something like `2` for the second
day of the month.
This works... But:
**How do I find the number of weekdays in that`timedelta`.**
I took a look at <https://pypi.python.org/pypi/BusinessHours/> and could not
find any documentation.
I also saw this: [Business days in
Python](http://stackoverflow.com/questions/2224742/business-days-in-python)
which linked me to the link above and rolling my own. It's also been 4 years
since that post and I was hoping there might be a simpler way?
Answer: With rrule I was able get the following using the dt definition from above:
from dateutil.rrule import *
number_weekdays = rrule(WEEKLY, byweekday=(MO,TU,WE,TH,FR), dtstart=datetime.utcnow(),until=dt).count()
|
No output in XML file using XMLITEMEXPORTER
Question: I am beginner to python and I am working with scrapy. I have used
xmlitemexporter to export my scraped data to xml file. But i get only
"<"/item"">" in the xml file. My items.py is like follow:
from scrapy.item import Item, Field
class WorkwithitemsItem(Item):
title = Field()
link = Field()
publish = Field()
description = Field()
And the spider is like:
from scrapy import log
from scrapy.spider import BaseSpider
from scrapy.selector import Selector
from workwithitems.items import WorkwithitemsItem
class MySpider(BaseSpider):
name = 'spidey'
allowed_domains = ['ekantipur.com']
start_urls = [
'http://www.ekantipur.com/en/rss',
]
def parse(self, response):
self.log('A response from %s just arrived!' % response.url)
sel = Selector(response)
title = sel.xpath('//title/text()').extract()
link = sel.xpath('//link/text()').extract()
publish = sel.xpath('//pubDate/text()').extract()
description = sel.xpath('//description/text()').extract()
WorkwithitemsItem(title = title[2:], link = link[2:],
publish = publish, description = description[1:])
And the pipelines.py is:
from scrapy import signals
from scrapy.contrib.exporter import XmlItemExporter
class XmlExportPipeline(object):
def __init__(self):
self.files = {}
@classmethod
def from_crawler(cls, crawler):
pipeline = cls()
crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
return pipeline
def spider_opened(self, spider):
file = open('%s_products.xml' % spider.name, 'w+b')
self.files[spider] = file
self.exporter = XmlItemExporter(file)
self.exporter.start_exporting()
def spider_closed(self, spider):
self.exporter.finish_exporting()
file = self.files.pop(spider)
file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
The settings.py is:
BOT_NAME = 'workwithitems'
SPIDER_MODULES = ['workwithitems.spiders']
NEWSPIDER_MODULE = 'workwithitems.spiders'
FEED_EXPORTERS_BASE = {
'xml': 'scrapy.contrib.exporter.XmlItemExporter',
}
ITEM_PIPELINES = {
'workwithitems.pipelines.XmlExportPipeline': 800,
}
I can't figure out where my problem is.
Answer: Ok! I found the problem. What i did is just put a 'return' at the last line in
spider.py
return WorkwithitemsItem(title = title[2:], link = link[2:],
publish = publish, description = description[1:]
)
|
Frequent "OperationalError: unable to open database file" with in memory sqlite3 database
Question: I'm using an in-memory database for a Python app, and am hitting pretty
frequent "unable to open database file" errors when attempting to access the
same in memory database from multiple threads.
Because it says that the in memory database is automatically cleaned up when
the last connection closes, I initialize and leave a connection open to the
database like this:
staging_cache = None
MEMORY_CACHE_PATH = "file::memory:?cache=shared"
def init_staging():
global staging_cache
staging_cache = sqlite3.connect(MEMORY_CACHE_PATH)
staging_cache.execute("""CREATE TABLE sigcache (path TEXT NOT NULL COLLATE NOCASE, sig BLOB,
updated_date REAL, sha512 TEXT DEFAULT "", item_type INT, depth INT, mtime REAL, size INT, revision_id INT)""")
staging_cache.execute("CREATE INDEX sigcache_rev_id_index on sigcache(path COLLATE NOCASE, revision_id)")
Then from some other threads:
with sqlite3.connect(MEMORY_CACHE_PATH, timeout=20) as db_conn:
db_conn.execute(query_string, param_tuple)
It seems like I keep hitting OperationalError: cannot open database file
I'm looking at the documentation at <http://www.sqlite.org/inmemorydb.html>
but I can't figure out if I'm doing something wrong or not.
EDIT: Apparently sqlite3 does not accept "file::memory:?cache=shared" as a
dbname, it only accepts :memory:. It was creating a file called
"file::memory:?cache=shared"
In any case, with sqlalchemy, there was a problem with persisting the data. I
solved the problem by just using sqlite3 with :memory:, creating a single
connection with check_same_thread=False, and wrapping all accesses in a single
threaded mutex.
Answer: SQLite and multiple threads don't mix well. I'd suggest using SQLAlchemy's
[connection
pooling](http://docs.sqlalchemy.org/en/rel_0_9/core/pooling.html#pooling-
plain-db-api-connections) (or even the whole package) to go around the
problem. Maybe something like this if you're not willing to rewrite
everything:
import sqlite3
import sqlalchemy.pool
sqlite = sqlalchemy.pool.manage(sqlite3, poolclass=sqlalchemy.pool.SingletonThreadPool)
connection = sqlite.connect(':memory:')
They also have some [notes about
multithreading](http://docs.sqlalchemy.org/en/rel_0_9/dialects/sqlite.html#threading-
pooling-behavior):
> So while even :memory: databases can be shared among threads in modern
> SQLite, Pysqlite doesn’t provide enough thread-safety to make this usage
> worth it.
|
While using Python's msilib- UPDATE statement fails with error 2259
Question: I have the following class method that is meant to run database statements:
class CDatabaseModifier(object):
def __init__(self, database):
""" Constructor gets database
"""
self._database = database
def RunStatement(self, statement):
""" Runs statement on database
"""
view = self._database.OpenView(statement)
view.Execute(None)
view.Close()
self._database.Commit()
This works with `INSERT INTO` and `DELETE` statements, but for some reason I
keep getting `MSIError 2259` exceptions when I try to run the `UPDATE`
statement with **string** as the parameter of `SET`. For example:
import msilib
db = msilib.OpenDatabase(r'C:\some\path\to\msi\bar.msi', msilib.MSIDBOPEN_DIRECT)
m = CDatabaseModifier(db)
m.RunStatement("UPDATE AppId SET ActivateAtStorage = 66 WHERE AppId = 'aaa'") # works OK
m.RunStatement("UPDATE AppId SET AppId = 'ccc' WHERE AppId = 'bbb'") # throws MSIError: 1: 2259 2
m.RunStatement("INSERT INTO AppId (AppId, RemoteServerName) VALUES ('foo', 'bar')") # works OK
More info: In the `AppId` table `ActivateAtStorage` column is `short` type,
`AppId` and `RemoteServerName` columns are `string` type.
It says [here](http://msdn.microsoft.com/en-
us/library/aa372835%28v=vs.85%29.aspx) that the 2259 error means that
> Database: [2] Table(s) Update failed. Queries must adhere to the restricted
> Windows Installer SQL syntax.
Because the syntax of the UPDATE statement seams right, I have no idea what
I'm doing wrong. Any help would be appreciated.
Answer: This site is magic: The minute you post a question you suddenly get the
answer.
Anyway, I missed the part from [here](http://msdn.microsoft.com/en-
us/library/aa372021%28v=vs.85%29.aspx) that clearly states that
> UPDATE queries **only work on nonprimary key columns**.
which was exactly what I was trying to do (`AppId` is a primary key column).
It had nothing to do with **string** types after all.
|
Python 3.x - Getting the state of caps-lock/num-lock/scroll-lock on Windows
Question: Just as the question asks, I know this is possible
[on](http://stackoverflow.com/questions/13129804/python-how-to-get-current-
keylock-status) [Linux](http://stackoverflow.com/questions/3207032/detect-
caps-lock-in-python-curses), but I couldn't find anything recent for Windows.
Is it even possible?
Answer: Install `pywin32` for Python 3.x
Here is the example for checking capslock state.
from win32api import GetKeyState
from win32con import VK_CAPITAL
GetKeyState(VK_CAPITAL)
|
Django Internationalization doesn't work (makemessages doesn't find .py file)
Question: I'm trying to internationalize my Django site with I18N. When I do the
makemessages. Bit that did not get the text of the view.py. I have done the
following things:
# my flow
PROJECT
- LOCALE
- MYSITE
- urls.py
- settings.py
- APP1
- views.py
- APP2
- APP3
manage.py
# settings.py
LANGUAGES = (
('it', 'Italiano'),
('en', 'English'),
)
LANGUAGE_CODE = 'it'
USE_I18N = True
LOCALE_PATHS = ('home/project/locale/',)
MIDDLEWARE_CLASSES = ( ...
'django.middleware.locale.LocaleMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (...,
'django.core.context_processors.i18n',
)
# views.py
from django.utils.translation import ugettext as tra
text = tra("this is a text")
...
# template.html
...
{% trans 'Dashboard' %}
....
from the root (where is manage.py) when I do "python manage.py makemessages.py
en-l" I get only a django.po with text from html file and not from views.py. I
also tried with "python manage.py makemessages.py en-l-e html,py" but it
doesn't work. Where am I doing wrong?
Answer: `makemessages` looks for very specific patterns in your code; `tra()` is _not_
one of those patterns.
From the [`makemessages` command
source](https://github.com/django/django/blob/master/django/core/management/commands/makemessages.py#L74)
you can see the `xgettext` command line tool is instead instructed to look
for: `gettext_noop`, `gettext_lazy`, `ngettext_lazy`, `ugettext_noop`,
`ugettext_lazy`, `ungettext_lazy`, `pgettext`, `npgettext`, `pgettext_lazy`
and `npgettext_lazy` (in addition to the `_()` callable).
Change your `views.py` code to:
from django.utils.translation import ugettext as _
text = _("this is a text")
to follow the widespread `gettext` conventions, or use:
from django.utils.translation import ugettext
text = ugettext("this is a text")
Best to stick to the original `translation.*` methods or `_()`, here.
|
interacting between modules / classes in wxPython
Question: I have a task of migrating a multi-userframe VBA project with a lot od
database interaction into something different - as this must be something that
cannot demand installing software (so JRE and .NET are out of the question) I
believe this can be done with Python - wxPython covers frames and different
controls (I'm using boa-constructor for it's frame designer), I also managed
to connect via adodbapi with the current database VBA is using. I just suck at
putting it all together properly. Consider this skeleton:
**myApp.py**
#!/usr/bin/env python
#Boa:App:BoaApp
import wx
import myFrame
modules ={u'myFrame': [1, 'Main frame of Application', u'myFrame.py']}
class BoaApp(wx.App):
def OnInit(self):
# here I think I'd see something like, say:
# self.main.cnnObject = adodbapi.connect ( some proper connection string )
self.main = myFrame.create(None)
self.main.Show()
self.SetTopWindow(self.main)
return True
def main():
application = BoaApp(0)
application.MainLoop()
if __name__ == '__main__':
main()
**myFrame.py**
#Boa:Frame:myFrame
import wx
def create(parent):
return myFrame(parent)
[wxID_MYFRAME, wxID_MYFRAMEBUTTON1,
] = [wx.NewId() for _init_ctrls in range(2)]
class myFrame(wx.Frame):
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_MYFRAME, name='myFrame', parent=prnt,
pos=wx.Point(710, 329), size=wx.Size(400, 250),
style=wx.DEFAULT_FRAME_STYLE, title='MainFrame')
self.SetClientSize(wx.Size(392, 223))
self.button1 = wx.Button(id=wxID_MYFRAMEBUTTON1,
label='FETCH cnnObject', name='button1', parent=self,
pos=wx.Point(0, 144), size=wx.Size(392, 79), style=0)
self.button1.Bind(wx.EVT_BUTTON, self.OnButton1,
id=wxID_MYFRAMEBUTTON1)
def __init__(self, parent):
self._init_ctrls(parent)
def OnButton1(self, event):
event.Skip()
# here and in other events in other frames I would like to retrieve
# that cnnObject to use for queries
Adding tons of controls, events, opening consecutive frames from this one and
next to come seems to work. However to not have to copy/paste the whole
database connection stuff over and over again I wanted to have it all in one
place and just access that code from frames. My general idea is that since
there's only one myApp object, it could contain the connection object,
especially since the connection string will be available as sys.argv[1] Is
this possible ? And if so, how would I reference the **application** object
from inside the OnButton1 method ? There's also a chance I have this figured
out all wrong, in which case I'd like to hear an outline of the 'right way'.
What I feel I may be missing is maybe a proper class wrapper for those
database operations, but even If I make one, I'd still like to have only one
instance of that class available in all my future frames, yet I can't even
manage to do that with the application instance - I import myApp inside
myFrame (which itself seems weird as myApp already imports myFrame, so both
ways ?) but no matter what type of assignment to a local variable I try, I
mostly get a " 'module' object has no attribute " ... (which makes me think I
probably don't get how scoping / modules work in Python)
Answer: I wrote a little about this, but I was using SQLAlchemy. This was my first
attempt:
* <http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/>
Then I received some comments and help from friend in the wxPython community
and SQLAlchemy's devs and updated the app a bit:
* <http://www.blog.pythonlibrary.org/2011/11/30/improving-medialocker-wxpython-sqlalchemy-and-mvc/>
This second article shows how to create a database session and pass it about.
I think that's the approach you are looking for. I would do the database
connection in your top level frame's init method:
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="Databases!")
self.data_connection = self.create_connection()
Then when you create your other frames, you can pass that connection to them:
def create_new_frame(self):
""""""
new_frame = MyOtherFrame(self.data_connection)
new_frame.Show()
Here's one way you could set up your frame class:
########################################################################
class MyOtherFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self, data_connection):
"""Constructor"""
wx.Frame.__init__(self, None, title="Other frame")
self.data_connection = data_connection
Just make sure you do not close the data connection in your other frame as
that will also close it in the original top level frame.
This solution also applies to your **OnButton1** call. Just change it so it's
like this:
def OnButton1(self, event):
cursor = self.data_connection.cursor()
You'll notice that you can access **self.data_connection** anywhere in your
main frame because it was defined as a class level variable.
You might also be interested in the Dabo project, which is a wrapper around
wxPython that is supposed to make it easier to work with databases:
<http://www.dabodev.com/>
|
Python - scipy fmin, giving the arguments to fmin
Question: I'm a bit of a newbie in Python. I'm writing a little piece of code in order
to find the minimum of a function:
import os,sys,matplotlib,pylab
import numpy as np
from scipy.optimize import fmin
par = [2., 0.5, 0.008]
x1 = 0.4
f2_2 = lambda x, param: param[0] * x**2 + param[1] * x + param[2]
xmin = fmin(f2_2,x1,args = (par))
print xmin
it should be very simple, however I am getting this error:
"Traceback (most recent call last):
File "prova.fmin.py", line 9, in <module>
xmin = fmin(f2_2,x1,args = (par))
File "/usr/lib/python2.7/dist-packages/scipy/optimize/optimize.py", line 257, in fmin
fsim[0] = func(x0)
File "/usr/lib/python2.7/dist-packages/scipy/optimize/optimize.py", line 176, in function_wrapper
return function(x, *args)
TypeError: <lambda>() takes exactly 2 arguments (4 given)"
Could someone help me in understanding this please?
Answer: I just tried this out. Looks like you need to say `(par,)` and not just
`(par)`. Note that `(par,)` is a tuple, with the variable `par` as a single
element, whereas `(par)` just evaluates to `par`: no tuple. The "`args`"
keyword of `fmin` expects to find a tuple, not `par`, which in this case is a
list.
Edit: Well, actually, it would seem that `args` doesn't mind receiving a list
either. But then, inside of `fmin`, when the function `f2_2` is called, `args`
is [unpacked](http://docs.python.org/2/tutorial/controlflow.html#arbitrary-
argument-lists), meaning its contents are now passed as arguments to `f2_2`.
This means that `f2_2` ends up getting four arguments, viz. `x`, `2`, `0.5`
and `0.008` in this case, as opposed to getting just the two arguments `x` and
`[2, 0.5, 0.008]`.
|
Editing PDF attributes using sed
Question: I'm trying to develop a python script for blender to output a rendered image
sequence to a PDF. I am using Imagemagick to convert to PDF, that part is
working fine, However, I want the thumbnail preview to also be included in the
PDF.
The PDF format is a bit confusing to me, but I have found the `/PageMode` and
`/UseThumbs` tags and how to insert them properly into the file. I can do this
manually and it works pretty well. But I have been trying to get a similar
result without the need to do it manually, I am writing a script after all.
Here is an example snippet of the header data in the PDF, with the added tags:
%PDF-1.3
1 0 obj
<<
/Pages 2 0 R
/PageMode
/UseThumbs
/Type /Catalog
>>
endobj
2 0 obj
<<
/Type /Pages
/Kids [ 3 0 R 17 0 R 31 0 R ]
/Count 3
>>
I am trying to use sed to insert the tags as needed on the 4th and 5th lines,
Which is also working, but when I open the PDF, the images are corrupted.
cryptically, when I compare the manually edited PDF (which isn't corrupted) to
the sed edited PDF(which is corrupted) in notepad++, there is no difference in
the files, that I can find. There is a different character count, but I cannot
find the location of the difference
I understand that PDFs have an offset cross reference table, but it seems
strange to me that doing it by hand doesn't corrupt anything, but doing it
with sed creates corruption
What am I doing wrong?
Answer: You really don't want to be doing this from sed. Some PDFs may look like line-
oriented text files, but they most assuredly are not.
Since you're already using Python, you can use a Python library for this task.
[pdfrw](https://github.com/pmaupin/pdfrw) will do this fine for you from pure
Python. It will slurp in a PDF file, and rebuild it with whatever changes you
want and set file offsets correctly. The following snippet of code should set
/PageMode to /UseThumbs in the /Root dictionary of the PDF:
from pdfrw import PdfReader, PdfWriter, PdfName
trailer = PdfReader('myfile.pdf')
trailer.Root.PageMode = PdfName.UseThumbs
PdfWriter().write('mynewfile.pdf', trailer)
Disclaimer: I am the pdfrw author.
|
Python convert WKT polygon to row wise points
Question:
"POLYGON ((12 13,22 23,16 17,22 24))",101,Something,100000
"POLYGON ((10 12,40 42,46 34,16 24,88 22,33 24,18 20 ))",102,another,200000
How can I get something like below in a csv file:
UID(like 101,102 etc) represents an unique identifier for each polygon.
UID#1,County,population,Point#1_Lat,Point#1_Long
UID#1,County,population,Point#2_Lat,Point#2_Long
UID#1,County,population,Point#3_Lat,Point#3_Long
UID#1,County,population,Point#n_Lat,Point#n_Long
UID#2,County,population,Point#1_Lat,Point#1_Long
UID#2,County,population,Point#2_Lat,Point#2_Long
UID#2,County,population,Point#3_Lat,Point#3_Long
UID#2,County,population,Point#n_Lat,Point#n_Long
Answer: Here is a solution using [`pyparsing`](http://pyparsing.wikispaces.com/). Let
me know if that doesn't work for you - it shouldn't be too difficult to come
up with something that only uses the standard library (e.g. `re`, etc.), but
it will definitely be uglier.
import csv
from pyparsing import Group, Literal, OneOrMore, Optional, Word
from pyparsing import delimitedList
from pyparsing import alphas, nums
data = """
"POLYGON ((12 13,22 23,16 17,22 24))",101,Something,100000
"POLYGON ((10 12,40 42,46 34,16 24,88 22,33 24,18 20 ))",102,another,200000
"""
def parse_line(line):
latitude = Word(nums)
longitude = Word(nums)
point = Group(latitude + longitude)
point_sequence = delimitedList(point, delim=',')
name = Word("POLYGON").suppress()
paren_left = Literal("((").suppress()
paren_right = Literal("))").suppress()
quote = Literal('"').suppress()
polygon = Group(quote + name + paren_left + point_sequence + paren_right + quote)
uid = Word(nums)
county = Word(alphas)
population = Word(nums)
sep = Literal(",").suppress()
parser = polygon + sep + uid + sep + county + sep + population
result = parser.parseString(line)
return result
def parse_lines(data, outfile):
with open(outfile, 'w') as f:
writer = csv.writer(f, lineterminator='\n')
lines = data.split('\n')
for line in lines:
if not line:
continue
points, uid, county, population = parse_line(line)
for lat, long in points:
writer.writerow([uid, county, population, lat, long])
writer.writerow('')
parse_lines(data, r'd:\out.txt') # change the path to wherever you want output
Result:
101,Something,100000,12,13
101,Something,100000,22,23
101,Something,100000,16,17
101,Something,100000,22,24
102,another,200000,10,12
102,another,200000,40,42
102,another,200000,46,34
102,another,200000,16,24
102,another,200000,88,22
102,another,200000,33,24
102,another,200000,18,20
|
Installing mysqldb with a new version of python on linux
Question: I have mysqldb installed and it works for python2.4. But I've recently
installed python2.6 and when I run it I can't import mysqldb. I get the
following:
import MySQLdb
ImportError: No module named MySQLdb
I've looked over how to install mysqldb (it's been a few years since I
installed it), but can't find anything on how to reinstall or make it work
with a new version of python. Any thoughts?
I made some progress by adding a path to my .bashrc file (the first one, whic
is where my MySQLdb installation is for python2.4):
export PYTHONPATH=/usr/lib64/python2.4/site-packages:/usr/lib/python2.4:/usr/lib/python2.4/site-packages:$PYTHONPATH
so now when I run python2.6 and try import MySQLdb I get
import MySQLdb
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.4/site-packages/MySQLdb/**init**.py", line 27, in
import _mysql
ImportError: /usr/lib64/python2.4/site-packages/_mysql.so: undefined symbol:
Py_InitModule4
I don't know what to do about this. Maybe install MySQLdb again with
python2.6? (I've actually tried this and it's hard to install MySQLdb with or
without setuptools. I did it once more than a year ago but forgot what I did.
My server behind a firewall, so setuptools doesn't work out of the box.) Any
ideas?
Answer: Which python version is on your path? You can determine this by typing
which python
It should return the location with py26 if it's referencing version 2.6
Then, try
sudo apt-get install python-mysqldb
This should install the correct version for 2.6
You can also download python-mysqldb directly
[here](http://sourceforge.net/projects/mysql-python/)
|
Problems running flask app on uwsgi / nginx
Question: I have created a flask app and up to this point have been using the default
flask server for creating/testing it. Now i want to deploy it to a server. I
am using uwsgi and nginx, though i am pretty new to both. i know there are a
lot of guides and questions about similar things, but i couldnt find the
solution after looking through as much as i could understand
The following is from my uwsgi log :
machine: x86_64
clock source: unix
detected number of CPU cores: 1
current working directory: /home/ben/flask/MLS-Flask
detected binary path: /home/ben/flask/MLS-Flask/mls-flask-ve/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 1024
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to UNIX address /home/ben/flask/MLS-Flask/mls_uwsgi.sock fd 3
Python version: 3.3.3 (default, Dec 30 2013, 16:29:41) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)]
Set PythonHome to /home/ben/flask/MLS-Flask/mls-flask-ve
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x11755d0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 72760 bytes (71 KB) for 1 cores
*** Operational MODE: single process ***
added /home/ben/flask/MLS-Flask/ to pythonpath.
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x11755d0 pid: 2926 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 2926, cores: 1)
I am assuming the uwsgi is at least running? I am fairly new to this so i am
not quite sure that the problem is.
my nginx config is :
server{
listen 8080;
charset utf-8;
location / {try_files $uri @app; }
location @app {
include uwsgi_params;
uwsgi_pass unix:/home/ben/flask/MLS-Flask/mls_uwsgi.sock;
}
}
my uwsgi ini is :
[uwsgi]
uid = nginx
gid = nginx
base = /home/ben/flask/MLS-Flask
home = %(base)/mls-flask-ve
pythonpath = %(base)
chdir = /home/ben/flask/MLS-Flask
module = runp
#socket file's location
socket = /home/ben/flask/MLS-Flask/mls_uwsgi.sock
#permissions for the socket file
chmod-socket = 666
#variable that holds a flask application inside the module imported
callable = app
#location of log file
logto = /var/log/uwsgi/%n.log
and the file the uwsgi ini is running is my flask app:
from app import app
if __name__ == "__main__":
app.run(debug = False, port = 8080)
I may have some extraneous stuff in my uwsgi ini or nginx config, but i am not
sure if those would necessarily be the problems. Can anyone see any reasons
why this might not be working? I am currently getting a 502 bad gateway error
on localhost:8080, so i am guessing it has something to do with my flask,
uwsgi ini/socket.
i appreciate any help.
Answer: It turned out my nginx user didnt have access to the socket because the / and
/home/ directory was owned by the root group and root user. I ended up giving
full access to the owner and group all the way from / directory to the socket
(this probably is not the safest solution security wise, but i can further
refine it after i get everything working.)
|
Python Shortest path between 2 points
Question: I have found many algorithms and approaches that talk about finding the
shortest path between 2 points , but i have this situation where the data is
modeled as :
[(A,B),(C,D),(B,C),(D,E)...] # list of possible paths
If we suppose i need the path from A to E , the result should be:
(A,B)=>(B,C)=>(C,D)=>(D,E)
but i can't find a pythonic way to do this search.
Answer: The Pythonic way is to to use a module if one exists. As in this case, we
know, [networkx](http://networkx.github.io/) is there , we can write
**Implementation**
import networkx as nx
G = nx.Graph([('A','B'),('C','D'),('B','C'),('D','E')])
path = nx.shortest_path(G, 'A', 'E')
**Output**
zip(path, path[1:])
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E')]
|
BeautifulSoup is not scraping ALL anchor tags in a page with .find_all('a'). Am I overlooking something?
Question: Okay, so in a terminal, after importing and making the necessary objects--I
typed:
for links in soup.find_all('a'):
print(links.get('href'))
which gave me all the links on a wikipedia page (roughly 250). No problems.
However, in a program I am coding, I only receive about 60 links (and this is
scraping the same wikipedia page) and the ones I DO get are mostly not worth
anything. I double checked that I initialized both exactly the same--the only
difference is the names of variables. For reference, here is the function
where I setup the BS4 object, and grab the desired page:
def get_site(hyperLink):
userSite = urllib3.PoolManager()
siteData = userSite.request("GET", hyperLink)
bsd = BeautifulSoup(siteData.data)
return bsd
Later, I grab the elements and append them to a list I will then manipulate:
def find_urls(bsd, urls, currentNetloc):
for links in bsd.find_all('a'):
urls.append(links.get('href'))
return urls
Other relevant info:
* I am using Python 3.3
* I am using urllib3, BeautifulSoup 4, and urlparse (from urllib)
* I am working in PyCharm (for the actual program)
* Using Lubuntu, if it matters.
After running a command line instance of python3 and importing "sys" I typed
and received:
$ sys.executable
'/usr/bin/python3'
$ sys.path
['', '/usr/local/lib/python3.3/dist-packages/setuptools-1.1.5-py3.3.egg', '/usr/local/lib/python3.3/dist-packages/pip-1.4.1-py3.3.egg', '/usr/local/lib/python3.3/dist-packages/beautifulsoup4-4.3.2-py3.3.egg', '/usr/lib/python3.3', '/usr/lib/python3.3/plat-i386-linux-gnu', '/usr/lib/python3.3/lib-dynload', '/usr/local/lib/python3.3/dist-packages', '/usr/lib/python3/dist-packages']
After running these commands in a Pycharm project, I received exactly the same
results, with the exception that the directories containing my pycharm
projects were included in the list.
Answer: This is not my answer. I got it from
[here](http://fryandata.wordpress.com/2014/06/17/24/), which has helped me
before.
from bs4 import BeautifulSoup
import csv
# Create .csv file with headers
f=csv.writer(open("nyccMeetings.csv","w"))
f.writerow(["Name", "Date", "Time", "Location", "Topic"])
# Use python html parser to avoid truncation
htmlContent = open("nyccMeetings.html")
soup = BeautifulSoup(htmlContent,"html.parser")
# Find each row
rows = soup.find_all('tr')
for tr in rows:
cols = tr.find_all('td') # Find each column
try:
names = cols[0].get_text().encode('utf-8')
date = cols[1].get_text().encode('utf-8')
time = cols[2].get_text().encode('utf-8')
location = cols[3].get_text().encode('utf-8')
topic = cols[4].get_text().encode('utf-8')
except:
continue
# Write to .csv file
f.writerow([names, date, time, location, topic])
I think it would be useful to note some of the troubles I ran into while
writing this script:
Specify your parser. It is very important to specify the type of html parser
that BeautifulSoup will use to parse through the html tree form. The html file
that I read into Python was not formatted correctly so BeautifulSoup truncated
the html and I was only able to access about a quarter of the records. By
telling BeautifulSoup to explicitly use the built-in Python html parser, I was
able to avoid this issue and retrieve all records.
Encode to UTF-8. get_text() had some issues with encoding the text inside the
html tags. As such, I was unable to write data to the comma-delimited file. By
explicitly telling the program to encode to UTF-8, we avoid this issue
altogether.
|
selenium python not working with phantomjs
Question: I have installed phantomjs with npm and selenium-python via python.
Everything works properly with Headless Firefox, but not with phantomjs.
Here is the code.
In [1]: from selenium import webdriver
In [2]: browser = webdriver.PhantomJS()
In [3]: browser.get('http://www.google.com/')
---------------------------------------------------------------------------
CannotSendRequest Traceback (most recent call last)
<ipython-input-5-a95426e05380> in <module>()
----> 1 browser.get('http://www.google.com/')
/home/asit/pyrepo/env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.pyc in get(self, url)
174 Loads a web page in the current browser session.
175 """
--> 176 self.execute(Command.GET, {'url': url})
177
178 @property
/home/asit/pyrepo/env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.pyc in execute(self, driver_command, params)
160
161 params = self._wrap_value(params)
--> 162 response = self.command_executor.execute(driver_command, params)
163 if response:
164 self.error_handler.check_response(response)
/home/asit/pyrepo/env/local/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.pyc in execute(self, command, params)
353 path = string.Template(command_info[1]).substitute(params)
354 url = '%s%s' % (self._url, path)
--> 355 return self._request(url, method=command_info[0], data=data)
356
357 def _request(self, url, data=None, method=None):
/home/asit/pyrepo/env/local/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.pyc in _request(self, url, data, method)
381 headers["Authorization"] = "Basic %s" % auth
382
--> 383 self._conn.request(method, parsed_url.path, data, headers)
384 resp = self._conn.getresponse()
385 statuscode = resp.status
/usr/lib/python2.7/httplib.pyc in request(self, method, url, body, headers)
956 def request(self, method, url, body=None, headers={}):
957 """Send a complete request to the server."""
--> 958 self._send_request(method, url, body, headers)
959
960 def _set_content_length(self, body):
/usr/lib/python2.7/httplib.pyc in _send_request(self, method, url, body, headers)
984 skips['skip_accept_encoding'] = 1
985
--> 986 self.putrequest(method, url, **skips)
987
988 if body and ('content-length' not in header_names):
/usr/lib/python2.7/httplib.pyc in putrequest(self, method, url, skip_host, skip_accept_encoding)
854 self.__state = _CS_REQ_STARTED
855 else:
--> 856 raise CannotSendRequest()
857
858 # Save the method we use, we need it later in the response phase
CannotSendRequest:
Any solution to this ?
Answer: Make sure you're at least at PhantomJS 1.8 They didn't support webdriver
connections until that version. I know my package manager had a much older
version when I was going through this yesterday.
<http://phantomjs.org/release-1.8.html>
|
How to save all instances in a single transaction in the peewee (python)?
Question: How to save all instances in a single transaction in the
[peewee](http://peewee.readthedocs.org/en/latest/) (python orm library)? For
example:
from peewee import SqliteDatabase, Model, TextField
DB_NAME = 'users.db'
db = SqliteDatabase(os.path.join(os.path.dirname(__file__), DB_NAME))
class Users(Model):
user_id = IntegerField(index = True)
name = TextField(null = True, index = True)
password = TextField(null = True)
description = TextField(null = True)
class Meta:
database = db
if not Drugs.table_exists():
Drugs.create_table()
data_to_save = [('user1', 'pass1'), ('user2', 'pass2'), ('user3', 'pass3')]
for user_name, user_password in data_to_save:
user_data = Users.get_or_create(name=user_name, password=user_password)
user_data.save()
how to rewrite in a single transaction?
Answer: You can wrap your query with "with" context manager
<http://peewee.readthedocs.org/en/latest/peewee/cookbook.html#working-with-
transactions>, so:
with db.transaction():
for user_name, user_password in data_to_save:
user_data = Users.get_or_create(name=user_name, password=user_password)
user_data.save()
|
Getting the start time of a new process which I triggered
Question: I am using Multiprocessing module in python and triggering many processes. Is
there a way where I can find out the START TIME of each process that I
triggered?
Since the processes are triggered quickly, I am looking to get the time in
milliseconds or even in nanoseconds to differentiate each process. This is the
piece of code that I have,
import multiprocessing
import time
def myProcess(processName):
print "This is a method that will run in parallel: processName"
time.sleep(120)
num = 100
for n in range(1,num):
processName = "Process %s" % n
proc = multiprocessing.Process(target=myProcess,args=(processName))
proc.start()
proc.join()
print "process startTime: %s " ?????
Answer: Don't do that. `multiprocessing.Process` objects have a `pid` attribute -- the
process ID, which is the process's unique identifier _at the OS level_. Use
that instead.
|
Customizing Regex for Validator in Python
Question: Just came across a line of code that enforces an user's text input into the
dialog's field. Regardless of the input only IP format will be allowed at the
end such as :
**123.456.789.100**
regexIP=QtCore.QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
I would like to write a regex for lineedit validator that would automatically
replace all the white spaces, commas, periods, dashes, minuses, dollar signs
(everything except letters and number) with underscores. I also would like to
capitalize the first three letters and then insert an underscore right after
them regardless of what the user types.
For instance, if an user types:
this is a beautiful day 77
the regex validator would automatically change it to:
THI_Sis_a_beatiful_day_77
Her is how PyQt portion of the code looks like:
my_regex = QtCore.QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
my_QLineEdit = QtGui.QLineEdit()
my_validator = QtGui.QRegExpValidator(my_regex, my_QLineEdit)
my_QLineEdit.setValidator( my_validator )
Once again, the code above is just an example. What I want is to write a regex
expression to put it inside the brackets:
my_regex = QtCore.QRegExp(**my_regex_expression_goes_here**)
This my_regex expression would enforce that user never enters a white_space,
period, comma, dollar sign into the text field (lineedit). Ideally I would
like to capitalize first three letters and then put an underscore. But that is
not a big deal any longer. Let's focus on how to achieve some basic regex
expression so the user is not able to put white spaces, minus, dollar signs
and etc. Only letters and numbers are allowed....
Answer: The `QRegExpValidator` class isn't really suitable for your use-case.
Instead, you should subclass `QValidator` and re-implement its
[validate](https://qt-project.org/doc/qt-4.8/qvalidator.html#validate) method
to get the behaviour you want.
The script below provides a basic demo. It automatically uppercases the first
three letters and inserts an underscore (if necessary). Also, all non-
alphanumeric characters are automatically replaced with an underscore. If you
want runs of non-alphanumeric characters replaced with a single underscore,
add a "+" to the end of the regexp. Pasted text will also be automatically
converted.
import sip, re
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui
class Validator(QtGui.QValidator):
def __init__(self, parent=None):
super(Validator, self).__init__(parent)
self._replace = re.compile(r'[^A-Za-z0-9]').sub
def validate(self, string, pos):
string = self._replace('_', string)
prefix = string[:3].upper()
if len(string) > 3 and not string[3] == '_':
prefix += '_'
pos += 1
string = prefix + string[3:]
return QtGui.QValidator.Acceptable, string, pos
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.edit = QtGui.QLineEdit(self)
self.validator = Validator(self)
self.edit.setValidator(self.validator)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.edit)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 300, 500, 100)
window.show()
sys.exit(app.exec_())
|
Same but without loops
Question: So I've got this module called risar. And what it does, it draws. But that's
not really of importance. I wrote this code which sets 20 flowers on the
background. The code works but it looks horribly awkward to me. I'd like it to
look more "fancy" or maybe that less loops would be used. I'm relatively new
to python.
import risar
import random
def makeFlowers():
flowers = []
for i in range(5):
colors = ["black_flower.svg","blue_flower.svg", "brown_flower.svg", "green_flower.svg","purple_flower.svg"]
for j in range(4):
x = random.randint(20, (risar.maxX-20))
y = random.randint(20, 300)
flower = risar.picture(x, y, colors[i])
flowers.append(flower)
return flowers
flowers = makeFlowers()
Answer: Well for starters, you're setting the `color` variable to the same list, five
times, so you can remove that from the loop:
# Just set `colors` once
colors = ["black_flower.svg","blue_flower.svg", "brown_flower.svg","green_flower.svg","purple_flower.svg"]
for i in range(5):
# Do stuff
Second, you're using two loops for no reason at all. Hint: if you're not using
`j` for anything, it might not deserve its own loop.
Instead, pull the code that you want to repeat together, and then repeat it
that many times. In this case, you want to repeat your block of code twenty
times, but you're using nested loops just to make sure you rotate through the
colors. Instead, notice that the number of flowers you're drawing is divisible
by the length of your color list, and refactor the whole thing into a single
loop:
for i in range(20):
x = random.randint(20, (risar.maxX-20))
y = random.randint(20, 300)
flower = risar.picture(x, y, colors[i//4]) # 0, 0, 0, 0, 1, 1, 1, 1, etc...
flowers.append(flower)
|
What happened in the Django 1.6 branch that affected how Manager metaclasses work?
Question: I have a little utility module, [django-
delegate](https://github.com/fish2000/django-delegate), that lets you define
methods on a QuerySet subclass and then “delegate” those method definitions to
a corresponding Manager subclass, by dint of a `@delegate` decoration.
It looks like this, if I can quote from my own
[README](https://github.com/fish2000/django-delegate/blob/master/README.rst):
from delegate import DelegateManager, delegate
class CustomQuerySet(models.query.QuerySet):
@delegate
def qs_method(self, some_value):
return self.filter(some_param__icontains=some_value)
def dont_delegate_me(self):
return self.filter(some_other_param="something else")
class CustomManager(DelegateManager):
__queryset__ = CustomQuerySet
class SomeModel(models.Model):
objects = CustomManager()
… which that setup allows for method-chaining on the model’s manager
reference, without any runtime dispatch vaguery, like so†:
>>> SomeModel.objects.custom_query().another_custom_query()
Behind-the-scenes, the module works by using a metaclass on the Manager
subclass, DelegateManager – and that worked without issue until Django turned
1.6. Now, when importing an app with models that use a DelegateManager, I get
one of these maddeningly esoteric metaclass-related showstopper TypeErrors:
>>> from tika import models as tika
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/fish/Praxa/TESSAR/instance/tika/models.py", line 4, in <module>
from delegate import DelegateManager, delegate
File "/Users/fish/Praxa/TESSAR/local/lib/python2.7/site-packages/delegate/__init__.py", line 108, in <module>
class DelegateManager(models.Manager):
File "/Users/fish/Praxa/TESSAR/local/lib/python2.7/site-packages/delegate/__init__.py", line 105, in __new__
cls, name, bases, attrs)
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
>>>
**TL,DR:** what happened between versions 1.5 and 1.6 in Django’s Manager-
related plumbing that could cause this?
* * *
**†** – _N.B., I do understand I could solve this myself by either a) reading
through endless kLOCs of Django source diffs or b) accomplishing roughly the
same thing in one of the bajillion other ways that one could possibly approach
the notional idea django-delegate addresses; mainly I am interested in
whatever is causing this Manager metaclass situation, tho. Thank you, my
fellow Djangonauts_
Answer: In order to deprecate `get_query_set` in favor of `get_queryset`
([#15363](https://code.djangoproject.com/ticket/15363)) the
`django.db.models.manager.Manager` is now an instance of
`django.db.models.manager.RenameManagerMethods`, a subclass of
`django.utils.deprecation.RenameMethodsBase`.
Since `delegate.DelegateSupervisor` is not a (non-strict) subclass of
`django.db.models.manager.RenameManagerMethods` Python can't resolve the
correct `delegate.DelegateManager` metaclass.
To solve this issue you should make sure `delegate.DelegateSupervisor` is a
subclass of `type(django.db.models.manager.Manager)` and not `type`. This
should work for Django 1.5 and 1.6. I created a PR on your repository to fix
this issue.
By the way, you might want to take a look at the [Django 1.7 release
note](https://docs.djangoproject.com/en/dev/releases/1.7/#calling-custom-
queryset-methods-from-the-manager). A delegate alternative has been built-in
into Django.
|
Is subprocess.Popen not thread safe?
Question: The following simple script hangs on the subprocess.Popen call intermittently
(roughly 30% of the time).
Unless use_lock = True, and then it never hangs, leading me to believe
subprocess is not thread safe! The expected behavior is script finishes within
5-6 seconds.
To demonstrate the bug, just run "python bugProof.py" a few times until it
hangs. Ctrl-C exits. You'll see the 'post-Popen' appear only once or twice but
not the third time.
import subprocess, threading, fcntl, os, time
end_time = time.time()+5
lock = threading.Lock()
use_lock = False
path_to_factorial = os.path.join(os.path.dirname(os.path.realpath(__file__)),'factorial.sh')
def testFunction():
print threading.current_thread().name, '| pre-Popen'
if use_lock: lock.acquire()
p = subprocess.Popen([path_to_factorial], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if use_lock: lock.release()
print threading.current_thread().name, '| post-Popen'
fcntl.fcntl(p.stdout, fcntl.F_SETFL, os.O_NONBLOCK)
fcntl.fcntl(p.stderr, fcntl.F_SETFL, os.O_NONBLOCK)
while time.time()<end_time:
try: p.stdout.read()
except: pass
try: p.stderr.read()
except: pass
print threading.current_thread().name, '| DONE'
for i in range(3):
threading.Thread(target=testFunction).start()
The shell script referenced above (factorial.sh):
#!/bin/sh
echo "Calculating factorial (anything that's somewhat compute intensive, this script takes 3 sec on my machine"
ans=1
counter=0
fact=999
while [ $fact -ne $counter ]
do
counter=`expr $counter + 1`
ans=`expr $ans \* $counter`
done
echo "Factorial calculation done"
read -p "Test input (this part is critical for bug to occur): " buf
echo "$buf"
System info: Linux 2.6.32-358.123.2.openstack.el6.x86_64 #1 SMP Thu Sep 26
17:14:58 EDT 2013 x86_64 x86_64 x86_64 GNU/Linux
Python 2.7.3 (default, Jan 22 2013, 11:34:30)
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Answer: On Python 2.x, there are various race conditions affecting subprocess.Popen.
(e.g. on 2.7 it disables & restores garbage collection to prevent various
timing issues, but this is not thread-safe in itself). See e.g.
<http://bugs.python.org/issue2320>, <http://bugs.python.org/issue1336> and
<http://bugs.python.org/issue14548> for a few of the issues in this area.
A substantial revision to subprocess was made in Python 3.2 which addresses
these (amongst other things, the fork & exec code is in a C module, rather
than doing some reasonably involved Python code in the critical part between
fork and exec), and is available backported to recent Python 2.x releases in
the [subprocess32](http://pypi.python.org/pypi/subprocess32/) module. Note the
following from the PyPI page: "On POSIX systems it is guaranteed to be
reliable when used in threaded applications."
I can reproduce the occasional (about 25% for me) crashes of the code above,
but after using `import subprocess32 as subprocess` I've not seen any failures
in 100+ runs.
Note that subprocess32 (and Python 3.2+) default to close_fds=True, but with
subprocess32 in place, I saw no failures even with close_fds=False (not that
you should generally need that).
|
Dictionary that counts occurrences of its items
Question: I'd like to create a
[`dictionary`](http://docs.python.org/2/tutorial/datastructures.html#dictionaries)
in python that automatically counts the repetitions of its elements:
when an element that is not contained is added it should insert it with
corresponding value `1`, if the same element is inserted again it will
increment its counter.
Is there a more elegant / compact way to implement this dictionary rather than
the following?
if var in myList:
myDictionary[var] += 1
else:
myDictionary[var] = 1
Answer:
from collections import defaultdict
d = defaultdict(int)
d[var] += 1
|
Gedit problems with python
Question: I'm just learning Python in school and we were suppose to draw something (code
it in gedit for python) on canvas (Tkinter). Instead of getting something
drawn up I only get an empty canvas. [It looks like this on my
computer](https://db.tt/X2vvLfQ9). The code is correct as I copied it from
another web page.
from Tkinter import *
master=Tk()
w=Canvas(master, width=200, height=100)
w.pack
w.create_line(0,0,200,100)
w.create_line(0,100,200,0, fill="red", dash=(4,4))
w.create_rectangle(50,25,150,75, fill="blue")
mainloop()
Answer: Actually, the code is _not_ correct. The person who wrote it forgot to
actually call the [`pack`](http://effbot.org/tkinterbook/pack.htm) method. You
need to add `()` after it to do this:
from Tkinter import *
master=Tk()
w=Canvas(master, width=200, height=100)
########
w.pack()
########
w.create_line(0,0,200,100)
w.create_line(0,100,200,0, fill="red", dash=(4,4))
w.create_rectangle(50,25,150,75, fill="blue")
mainloop()
Otherwise, the canvas will never be placed on the window.
P.S. You should note that not everything you find on the Web is guaranteed to
be correct. :)
|
How to limit by column repetitions in Python Pandas
Question: I want to select only rows that contain fewer than 3 total repetitions of an
element in a column. To be specific, I have a large directory of phone
numbers, names, and cities. I want to export a list of only "small cities,"
such that any line with a city that has fewer than three entries across the
document is kept. So, for example
Name, City, State
Foo, L.A., CA
Bar, L.A., CA
Sam, L.A., CA
Tricia, Kent, WA
Bob, Kent, WA
Ida, Boo, PA
Monster Mash, Whack, PA
Zoomacroom, L.A., CA
Otter Pop, Boo, PA
Snake, HP, WA
Ronnie the Bear, Boo, PA
Should become:
Name, City, State
Tricia, Kent, WA
Bob, Kent, WA
Snake, HP, WA
Monster Mash, Whack, PA
I also don't have to use pandas - I can use csv just as easily; I just happen
to already have it imported in my cleaning script.
Answer: How about something like:
>>> small_cities = df.groupby(["City", "State"]).filter(lambda x: x.count() < 3)
>>> small_cities
Name City State
3 Tricia Kent WA
4 Bob Kent WA
6 Monster Mash Whack PA
9 Snake HP WA
[4 rows x 3 columns]
|
Python 3.3.3 Running Files with Command Line
Question: I just started learning Python 3.3.3 with the book "Learning Python" from
O'Reilly by Mark Lutz, 4th Ed.
I was able to run code interactively, but when I tried to run the code from
files through the command line, I just kept getting syntax errors.
FYI, I am using Windows 7.
The book asks that one create a file using a text editor with the following:
import sys
print(sys.platform)
print(2 ** 100)
x = 'Spam!'
print(x * 8)
I did this using notepad and saved the file with the suffix "py" and the file
type "all.files" so there would not be a "txt" file saved. When I try to run
the script in the python command I get an error message. I've tried entering
the PATH but that as not worked either. It is located in C:\Python33\
Any guidance you are able to provide is very welcomed. I've tried numerous
ways for the past 1 hour.
Answer: So, I have the following in my `Path` variable,
C:\Python27;C:\Python27\Scripts;
Is that what you have? Maybe close your command line and open it again, or
shut your machine off and turn it on again--the system variables do not update
instantly.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.