text
stringlengths 226
34.5k
|
---|
Repeating an algorithm as many times as the user requires (PYTHON 3.3.2 GUI)
Question: I'm trying to repeat this algorithm and use the values in my code, please
help!!!
import random
def dice_roll(number):
if number == 12:
number = random.randint(1,12)
print(number)
return(number)
elif number == 6:
number = random.randint(1,12)
print(number)
return(number)
else:
number == 4
number = random.randint(1,12)
print(number)
return(number)
dice_roll(int(input("Which dice would you like to roll? --> ")))
Answer: The typical way to do this is a `while True` loop, which you `break` when the
user quits, e.g.:
while True:
user_input = int(input("Which die would you like to roll (0 to quit)? "))
if user_input in (4, 6, 12):
dice_roll(user_input)
elif user_input:
print("Not an acceptable die.")
else:
break
Note that your `dice_roll` function currently always rolls a 12-sided die, and
could be simplified:
def dice_roll(sides):
number = random.randint(1, sides)
print(number)
return number
(this also removes the limit to 4, 6 and 12 only, so you may want to revise
the input loop accordingly).
|
PIL: AttributeError: 'NoneType' object has no attribute 'show'
Question: I'm trying to use PIL to show an image loaded from a list of numbers.
My entire code looks like this:
from PIL import Image
import os, sys
L = 4 #resolution increase
LR_DIM = (2592, 1944)
HR_DIM = (LR_DIM[0]*L, LR_DIM[1]*L)
HR = [0] * (HR_DIM[0] * HR_DIM[1])
#include low-res files
LR = []
LR.append([[250 for x in range(LR_DIM[0])] for y in range(LR_DIM[1])])
img = Image.new("L", LR_DIM)
img = img.putdata(LR[0])
img.show()
and I got to the last line and get the error in the title.
What's wrong?
I'm on Windows, and using Python32 and a fresh install of both Python and PIL.
Answer: `img.putdata()` returns `None`; it alters the image in place.
Just use:
img = Image.new("L", LR_DIM)
img.putdata(LR[0])
img.show()
|
Google App Engine deferred.defer() error 404
Question: I'm trying to get running a task in the Task Queue using deferred.defer(). The
task is added to the default task queue, but the task fail with a 404 error.
This is the handler:
import webapp2
import models
import defer_ajust_utils
from google.appengine.ext import ndb
from google.appengine.ext import deferred
class ajust_utils(webapp2.RequestHandler):
def get(self):
deferred.defer(defer_ajust_utils.DoTheJob)
application = webapp2.WSGIApplication([('/ajust_utils', ajust_utils)], debug=True)
This is the module **defer_ajust_utils** :
import logging
import models
from google.appengine.ext import ndb
def DoTheJob():
logging.info("Debut de la mise a jour des utilisateurs")
utilisateurs = models.Utilisateur.query()
utilisateurs = utilisateurs.fetch()
for utilisateur in utilisateurs:
utilisateur.produire_factures_i = False
utilisateur.put()
logging.info("Fin de la mise a jour des utilisateurs")
And my **app.yaml** file :
application: xxxx
version: dev
runtime: python27
api_version: 1
threadsafe: yes
builtins:
- deferred: on
handlers:
- url: /ajust_utils
script : tempo_ajuster_utils.application
login: admin
Here's the log :
0.1.0.2 - - [10/Mar/2014:17:50:45 -0700] "POST /_ah/queue/deferred HTTP/1.1" 404 113
"http://xxxx.appspot.com/ajust_utils" "AppEngine-Google;
(+http://code.google.com/appengine)" "xxxx.appspot.com" ms=6 cpu_ms=0
cpm_usd=0.000013 queue_name=default task_name=17914595085560382799
app_engine_release=1.9.0 instance=00c61b117c0b3648693af0563b92051423b3cb
Thank you for help!!
Answer: If you are using push-to-deploy with git, when you add in a 'builtin' part to
the app.yaml, such as in
` builtins: - deferred: on`
you need to do a 'normal' gcloud deploy before you run the app. Otherwise it
will not update the running app, which causes 404 errors for
/_ah/queue/deferred
There is an open bug for this, so vote for it and it may get fixed.
<https://code.google.com/p/googleappengine/issues/detail?id=10139>
|
Haskell: Appending to a list from multiple locations in a program
Question: I would like to have a list that may be updated (appended to) from more than
one location in the code. Since in haskell, [`calling a function once is the
same as calling it twice and discarding the result of the first
call`](https://www.fpcomplete.com/school/starting-with-haskell/basics-of-
haskell/3-pure-functions-laziness-io), what is the best way for me to manage
this list if side effects are not allowed? I've thought of passing the list
through each time each time I need to append to it, but I don't know if that
would be sufficient for what I want to accomplish. The [algorithm that I'm
implementing](http://video.mit.edu/watch/introduction-to-algorithms-
lecture-20-dynamic-programming-ii-text-justification-blackjack-14035/) uses
memoization [edit not dynamic programming] and stores a possible list of
optimal winnings in a helper list. Would it be a good idea to simulate a
global variable using monads and states or is there a better way to go about
this?
Edit: This is how I implemented it in python:
def BJ(i):
if i in BJList:
return BJList[i]
else:
options = [0] # if you walk away
if n-i < 4: # not enough cards to play
return 0
for p in range(2,(n - i)): # number of cards taken
player = c[i] + c[i+2] + sum(c[i+4:i+p+2])
# when p is 2
if player > 21:
options.append(-1 + BJ(i + p + 2))
break # breaks out of for(p)
dealer = 0
d1 = 0
for d in range(2,n-i-p+1): # python ranges are not inclusive
d1 = d
dealer = c[i+1] + c[i+3] + sum(c[i+p+2:i+p+d])
if dealer >= 17:
break # breaks out of for(d)
if dealer < 17 and i + p + d >= n: # doesn't change results, maybe
dealer = 21 # make it be more like haskell version
if dealer > 21:
dealer = 0
dealer += .5 # dealer always wins in a tie
options.append(cmp(player, dealer) + BJ(i + p + d1))
BJList[i] = (max(options))
return max(options)
c = [10,3,5,7,5,2,8,9,3,4,7,5,2,1,5,8,7,6,2,4,3,8,6,2,3,3,3,4,9,10,2,3,4,5]
BJList = {}
n = len(c)
print "array:" + str(c)
print BJ(0)
My question refers to the `options` list. Is there a way to implement the
`options` list that would allow me to manipulate it in both `options.append`
locations?
Edit: This is my final implementation in Haskell (both programs concur):
import qualified Data.MemoCombinators as Memo
deck = [10,3,5,7,5,2,8,9,3,4,7,5,2,1,5,8,7,6,2,4,3,8,6,2,3,3,3,4,9,10,2,3,4,5]
dsize = length deck
getPlayerScore :: Int -> Int -> Int
getPlayerScore i p
| i + 2 + p <= dsize =
deck !! i + deck !! (i + 2) + (sum $ take (p-2) $ drop (i + 4) deck)
| otherwise = 0
getDealerScoreAndHitCount :: Int -> Int -> (Int, Int)
getDealerScoreAndHitCount i p -- gets first two cards
| i + 2 + p <=
dsize = getDSAHC' (deck !! (i + 1) + deck !! (i + 3)) (i+2+p)
| otherwise = (0,0)
getDSAHC' :: Int -> Int -> (Int, Int) -- gets the remaining cards dealer hits
getDSAHC' baseScore cardIndex
| baseScore >= 17 = (baseScore,0)
| cardIndex < dsize = (fst result, snd result + 1)
| otherwise = (0,0)
where
result = getDSAHC' (baseScore + deck !! cardIndex) (cardIndex + 1)
takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' p (x:xs) =
if p x
then x:takeWhile' p xs
else [x]
takeWhile' p [] = []
getHandOutcome :: Int -> Int -> Int
getHandOutcome pValue dValue
| pValue > 21 = -1
| dValue == 0 = 0
| pValue > dValue = 1 -- player beats dealer
| dValue > 21 = 1 -- dealer busts
| otherwise = -1 -- dealer wins ties
blackjack :: Int -> Int
blackjack i
| dsize - i < 4 = 0
| otherwise = maximum options
where
options =
[0] ++ map score (takeWhile' (\(p,_,_) -> p <= 21) (map result [2 ..dsize-i-1]))
score (pValue,dValue,mCards) = -- mcards is total cards taken in current hand
(getHandOutcome pValue dValue) + bjMemo (i + mCards)
result p = -- 'p' represents the num of cards player is going to receive
(getPlayerScore i p, fst (getDealerScoreAndHitCount i p),
2 + p + snd (getDealerScoreAndHitCount i p))
bjMemo :: Int -> Int
bjMemo = Memo.integral blackjack
main :: IO()
main =
do
print $ blackjack 0
Answer: In general I see 3 solutions, with decreasing 'appealing' to Haskellers:
1. Write the algorithm in a purely functional way
* Pros: No side effects, beautiful
* Cons: You might have to rewrite the algorithm if it is given in imperative style (which is the case here)
2. Use the `State` monad to _emulate_ state, because it essentially just 'hides' additional arguments to your function.
* Pro: Imperative feeling
* Cons: Monadic code, which is in general harder to reason about and not as easy reusable
* Example:
workerState :: State [Int] ()
workerState = do
modify (++ [21])
{- lots of stuff happening -}
modify (++ [21])
-- E.g. in repl
> runState workerState []
3. Use side effects. This means use either the `ST` monad or some sort of mutable references like `IORef`.
* Pro: Real mutability, minimal changes to original algorithm due to monadic style
* Cons: All from `State` \+ the ultimate evil: _side effects_
* Example:
workerST :: STRef s [Int] -> ST s ()
workerST ref = do
modifySTRef ref (++ [21])
{- lots of stuff happening -}
modifySTRef ref (++ [21])
-- E.g. in repl:
> runST $ do
r <- newSTRef []
workerST r
Note that in general _appending_ to a list in haskell is slow because the
standard list type is a single linked list, where only prepend is O(1).
Having said that, if you use variant 1 (purely functional), you also have the
benefit of using libraries like [memo-
combinators](http://hackage.haskell.org/package/data-memocombinators/), giving
you memoization almost for free: Given a function `bj` that calculates the
best score, we can memoize it like that:
bj :: Int -> Score
bj i =
undefined -- purely functional algorithm, replace recursive calls with bjMemo
bjMemo :: Int -> Score
bjMemo = Memo.integral bj
|
Python 2 raw_input() : EOFError when reading a line in WINDOWS 7 command prompt
Question: NOTE: Many of the same questions have been asked about python raw_input() in
**sublime text**. This question is **NOT** about sublime. The python code is
called in Windows command prompt which unlike the sublime terminal does
support interactive inputs.
* * *
I have a python program that takes user input with the built-in function
raw_input(). See below.
def password_score():
pwd = raw_input('Enter a password: ')
gname = raw_input('Enter your first name: ')
...
I call the program in cmd by
echo password_score()|python -i a06q1.py
where a06q1.py is the file name. The path of the python directory has been
added to system variable `%PATH%` temporarily. I am in the directory of the
file. My operating system is Windows 7. I am using python 2.6. The same
command has worked until now.
Then cmd returns
File "<stdin>", line 1, in <module>
File "a06q1.py", line 27, in password_score
pwd = raw_input(p_prompt)
EOFError: EOF when reading a line
Is there a way to get around it **within cmd**?
EDIT: I just tried in on an iOS terminal too. With the same command as in cmd
(with quotes), it returns the same error. Is there anything wrong about the
command line I used? Thank you!
* * *
EDIT: Sebastian's answer solves the problem. The command should adapt to
windows as follows.
printf "a06q1.password_score()\n'arg1\n'arg2"|python -i -c "import a06q1"
The single quotes succeeding `\n` can be replaced by spaces. They separate
multiple inputs.
Answer: What you're trying to do is not the way to call a specific function from the
command line. You need an `if __name__ == "__main__"`-block in your code.
At the end of your file:
`if __name__ == "__main__"`:
password_score()
And now run the program by:
python a06q1.py
If you run a python file from the command file, the `__name__`-variable will
be `"__main__"`. Notice that if you import `a06q1` to some other python file,
the name will equal the module name and thus the `if __name__` block evaluates
to `False`.
From [python docs](http://docs.python.org/2/library/__main__.html):
> This module represents the (otherwise anonymous) scope in which the
> interpreter’s main program executes — commands read either from standard
> input, from a script file, or from an interactive prompt. It is this
> environment in which the idiomatic “conditional script” stanza is run
* * *
As J.F Sebastian writes in the comments, you can also execute a specific
python command by providing the `-c` switch. The following will import the
`a06q1` and run `function_name`:
python -c "from a06q1 import function_name; function_name()"
|
`Query.count()` woes with Flask-SQLAlchemy and multiple binds
Question: # Abstract
I am having trouble using multiple binds with Flask-SQLAlchemy. In particular,
the `count()` method on query objects doesn’t seem to work.
# Particulars
My Flask application works on a PostgreSQL database. Additionally, it also
retrieves data from a legacy [Simple Machines
Forum](http://simplemachines.org) installation that runs on MySQL.
To facilitate usage, I use a second Flask-SQLAlchemy bind for the MySQL
database and setup the classes via reflection. Querying works fine in general,
but using `count()` raises a `sqlalchemy.exc.ProgrammingError` that the
corresponding table would not exist.
# Code
`myapp/app.py`:
from flask import Flask
class Config(object):
SQLALCHEMY_DATABASE_URI = 'postgres://localhost/igor'
SQLALCHEMY_BINDS = {
'smf': 'mysql://myuser:mypass@localhost/my_db',
}
app = Flask('myapp')
app.config.from_object(Config)
`myapp/model.py`:
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from .app import app
__all__ = []
def _add_global(key, value):
globals()[key] = value
__all__.append(key)
bind_key = 'smf'
table_prefix = 'smf_'
table_prefix_len = len(table_prefix)
db = SQLAlchemy(app)
engine = db.get_engine(app, bind=bind_key)
meta = MetaData(bind=engine)
# Reflect SMF database
meta.reflect()
for tablename, table in meta.tables.items():
# Skip non-SMF tables
if not tablename.startswith(table_prefix):
continue
# Strip table name prefix
tablename = tablename[table_prefix_len:]
# Do not create a class for tables without primary key
if not table.primary_key:
_add_global(tablename, table)
continue
# Derive class name from table name by camel-casing,
# e.g. `smf_personal_messages` -> `PersonalMessages`
classname = ''.join(x.capitalize() for x in str(tablename).split('_'))
# Create class
class_ = type(classname, (db.Model,), {
'__table__': table,
'__bind_key__': bind_key,
})
_add_global(classname, class_)
Example (file paths in the error stack trace shortened for legibility):
% python
Python 2.7.6 (default, Dec 2 2013, 11:07:48)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from myapp.model import Topics
>>> len(Topics.query.all())
10162
>>> Topics.query.count()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "…/sqlalchemy/orm/query.py", line 2573, in count
return self.from_self(col).scalar()
File "…/sqlalchemy/orm/query.py", line 2379, in scalar
ret = self.one()
File "…/sqlalchemy/orm/query.py", line 2348, in one
ret = list(self)
File "…/sqlalchemy/orm/query.py", line 2391, in __iter__
return self._execute_and_instances(context)
File "…/sqlalchemy/orm/query.py", line 2406, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "…/sqlalchemy/engine/base.py", line 717, in execute
return meth(self, multiparams, params)
File "…/sqlalchemy/sql/elements.py", line 317, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "…/sqlalchemy/engine/base.py", line 814, in _execute_clauseelement
compiled_sql, distilled_params
File "…/sqlalchemy/engine/base.py", line 927, in _execute_context
context)
File "…/sqlalchemy/engine/base.py", line 1076, in _handle_dbapi_exception
exc_info
File "…/sqlalchemy/util/compat.py", line 185, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "…/sqlalchemy/engine/base.py", line 920, in _execute_context
context)
File "…/sqlalchemy/engine/default.py", line 425, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) relation "smf_topics" does not exist
LINE 3: FROM smf_topics) AS anon_1
^
'SELECT count(*) AS count_1 \nFROM (SELECT smf_topics.id_topic AS smf_topics_id_topic, […] \nFROM smf_topics) AS anon_1' {}
In the latter case, the statement is obviously run against the primary
PostgreSQL bind instead of the MySQL bind. (This can easily be proven by
creating a `smf_topics` table in the connected PostgreSQL database.)
I also tried providing the `__tablename__` attribute in addition to (and also
in place of) `__table__` when creating the classes, but to no avail.
I guess I am missing something crucial here. Unfortunately, time constraints
prohibit migrating the forum to PostgreSQL. Any help is appreciated.
# Update (Feb 23, 2015)
Here is a minimal example to reproduce the error. Using `count()` with a
conventional model class on the other bind—see `class Topic(db.Model)`—works,
though.
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
# Application setup
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost/igor'
app.config['SQLALCHEMY_BINDS'] = {
'smf': 'mysql://myuser:mypass@localhost/my_db',
}
db = SQLAlchemy(app)
# Database reflection
smf_meta = MetaData(bind=db.get_engine(app, bind='smf'))
smf_meta.reflect()
topic_class = type(db.Model)('Topic', (db.Model,), {
'__bind_key__': 'smf',
'__tablename__': 'smf_topics',
'__table__': smf_meta.tables['smf_topics'],
})
# Conventional model class
class Topic(db.Model):
__bind_key__ = 'smf'
__tablename__ = 'smf_topics'
id_topic = db.Column(db.Integer, primary_key=True)
num_replies = db.Column(db.Integer, nullable=False, default=0)
# Run it
if __name__ == '__main__':
print('1. {}'.format(Topic.query.count()))
print('2. {}'.format(len(topic_class.query.all())))
print('3. {}'.format(topic_class.query.count()))
And the output when running the script:
1. 10400
2. 10400
Traceback (most recent call last):
File "./test.py", line 35, in <module>
print('3. {}'.format(topic_class.query.count()))
File "…/sqlalchemy/orm/query.py", line 2640, in count
return self.from_self(col).scalar()
File "…/sqlalchemy/orm/query.py", line 2426, in scalar
ret = self.one()
File "…/sqlalchemy/orm/query.py", line 2395, in one
ret = list(self)
File "…/sqlalchemy/orm/query.py", line 2438, in __iter__
return self._execute_and_instances(context)
File "…/sqlalchemy/orm/query.py", line 2453, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "…/sqlalchemy/engine/base.py", line 729, in execute
return meth(self, multiparams, params)
File "…/sqlalchemy/sql/elements.py", line 322, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "…/sqlalchemy/engine/base.py", line 826, in _execute_clauseelement
compiled_sql, distilled_params
File "…/sqlalchemy/engine/base.py", line 958, in _execute_context
context)
File "…/sqlalchemy/engine/base.py", line 1159, in _handle_dbapi_exception
exc_info
File "…/sqlalchemy/util/compat.py", line 199, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "…/sqlalchemy/engine/base.py", line 951, in _execute_context
context)
File "…/sqlalchemy/engine/default.py", line 436, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) relation "smf_topics" does not exist
LINE 3: FROM smf_topics) AS anon_1
^
'SELECT count(*) AS count_1 \nFROM (SELECT smf_topics.id_topic AS smf_topics_id_topic, […] \nFROM smf_topics) AS anon_1' {}
Answer: And here’s how it works. ^^ The key is to use `db.reflect()` and then provide
`db.Model.metadata` as the newly created class’ metadata:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost/igor'
app.config['SQLALCHEMY_BINDS'] = {
'smf': 'mysql://myuser:mypass@localhost/my_db',
}
db = SQLAlchemy(app)
db.reflect(bind='smf', app=app)
topic_class = type(db.Model)('Topic', (db.Model,), {
'__bind_key__': 'smf',
'__table__': db.Model.metadata.tables['smf_topics'],
'__tablename__': 'smf_topics',
'__module__': __name__,
'metadata': db.Model.metadata,
})
if __name__ == '__main__':
print('1. {}'.format(len(topic_class.query.all())))
print('2. {}'.format(topic_class.query.count()))
|
Calling isinstance in main Python module
Question: There is a strange behavior of isinstance if used in `__main__` space.
Consider the following code
a.py:
class A(object):
pass
if __name__ == "__main__":
from b import B
b = B()
print(isinstance(b, A))
b.py
from a import A
class B(A):
pass
main.py
from a import A
from b import B
b = B()
print(isinstance(b, A))
When I run `main.py`, I get `True`, as expected, but when I run `a.py`, I am
getting `False`. It looks like the name of `A` is getting the prefix
`__main__` there.
How can I get a consistent behavior? I need this trick with import of `B` in
`a.py` to run `doctest` on file `a.py`.
Answer: WSo what happens when you run `a.py` is that Python reads `a.py` and executes
it. While doing so, it imports module `b`, which imports module `a`, but it
does not reuse the definitions from parsing it earlier. So now you have two
copies of the definitions inside `a.py`, known as modules `__main__` and `a`
and thus different `__main__.A` and `a.A`.
In general you should avoid importing modules that you are executing as well.
Rather you can create a new file for running doctests and use something like
import a
import doctest
doctest.testmod(a)
and remove the `__main__` part from module `a`.
|
Python pyserial slow and crashes after given period of time
Question: When I use Python’s pyserial to obtain voltage and time information from an
Arduino, the Python with Pyserial appears to be slow. When I look in the
Arduino serial monitor, everything is fine, the time and voltage values are as
expected and can go on for as long as is possible of the Arduino. However on
Python, the first thousand or so values (samples) are fine, after a period of
15 - 20 seconds,the plot crashes and data values are corrupted.
The following text file containing the results from the plot illustrate what I
describe:
7180.0 2.9521
7187.0 4.1349
7193.0 4.51124
7200.0 3.68035
7206.0 2.58065
7214.0 1.86217
7221.0 1.51026
7227.0 1.44184
7234.0 1.39296
7240.0 1.35386
7247.0 1.4174
7255.0 1.43695
7261.0 1.43695
7268.0 1.52004
7274.0 1.53959
7281.0 1.55425
7288.0 1.63734
7294.0 1.65689
7302.0 1.67155
7308.0 1.75464
7315.0 1.76442
7322.0 1.78397
7328.0 1.86706
7335.0 1.87683
7342.0 1.91593
7349.0 2.0088
7356.0 1.99902
7362.0 2.02346
7369.0 2.09677
7375.0 2.087
7383.0 2.10166
7390.0 2.15054
7396.0 2.10655
7403.0 2.09677
7409.0 2.10655
7416.0 2.02346
7424.0 1.97947
7430.0 1.95015
7437.0 1.83773
7443.0 1.77908
7450.0 1.77908
7457.0 1.6911
7463.0 1.64223
7471.0 1.65689
7477.0 1.59335
7484.0 1.60802
7491.0 1.63734
7497.0 1.60313
7504.0 1.64712
7511.0 1.68622
7518.0 1.65689
7525.0 1.69599
7531.0 1.73509
7538.0 1.70577
7544.0 1.74976
7552.0 1.80352
7559.0 1.74487
7565.0 1.82796
7572.0 1.81329
7578.0 1.77908
7585.0 1.82796
7592.0 1.83773
7599.0 1.80352
7606.0 1.84751
7612.0 1.85239
7619.0 1.81329
7626.0 1.85239
7632.0 1.84751
7640.0 1.80841
7646.0 1.85728
7653.0 1.86706
7660.0 1.83773
7666.0 1.86706
7673.0 1.85728
7680.0 1.83284
7687.0 1.8915
7694.0 1.88661
7700.0 1.87683
7707.0 1.95015
7713.0 1.92571
7720.0 1.92571
7728.0 2.01857
7734.0 2.03324
7741.0 2.01857
7747.0 2.03324
7754.0 1.9306
7761.0 1.86706
7768.0 1.85728
7775.0 1.79863
7781.0 1.78397
7788.0 1.82307
7795.0 1.78397
7801.0 1.77908
7809.0 1.82796
7815.0 1.78886
7822.0 1.77419
7829.0 1.76442
7835.0 1.74487
7842.0 2.10166
7848.0 3.04497
7856.0 4.174
7863.0 4.50635
7869.0 3.65591
7876.0 2.48778
7882.0 1.80352
7889.0 1.52981
7897.0 1.39785
7903.0 1.38807
7910.0 1.40762
7916.0 1.36364
7923.0 1.42717
7930.0 1.48583
7937.0 1.47605
7944.0 1.53959
7950.0 1.59335
7957.0 1.57869
7964.0 1.64712
7970.0 1.69599
7977.0 1.68622
7984.0 1.76442
7991.0 1.80841
7998.0 1.80841
8004.0 1.88172
8011.0 1.92571
8018.0 1.92082
8025.0 1.99902
8032.0 2.03812
8038.0 2.03324
8045.0 2.10166
8052.0 2.11632
8058.0 2.087
8066.0 2.11632
8072.0 2.09677
8079.0 2.03812
8086.0 2.05279
8092.0 1.98925
8099.0 1.89638
8105.0 1.88172
8113.0 1.79863
8120.0 1.71554
8126.0 1.71554
8133.0 1.66178
8139.0 1.61779
8146.0 1.66178
8154.0 1.62268
8160.0 1.6129
8167.0 1.67155
8173.0 1.65689
8180.0 1.65689
8187.0 1.71554
8194.0 1.70088
8201.0 1.70577
8207.0 1.76442
8214.0 1.73998
8221.0 1.75464
8227.0 1.80841
8235.0 1.78397
8241.0 1.79863
8248.0 1.83773
8255.0 1.81818
8261.0 1.80352
8268.0 1.84751
8274.0 1.80352
8282.0 1.81818
8289.0 1.85239
8295.0 1.80841
8302.0 1.82796
8308.0 1.85728
8315.0 1.81329
8323.0 1.83773
8329.0 1.86706
8336.0 1.82307
8342.0 1.84751
8349.0 1.88172
8356.0 1.82307
8363.0 1.85728
8370.0 1.88661
8376.0 1.85239
8383.0 1.90127
8390.0 1.9306
8396.0 1.89638
8403.0 1.9306
8410.0 1.96481
8417.0 1.96481
8424.0 2.04301
8430.0 2.04301
8437.0 1.96481
8443.0 1.95015
8451.0 1.89638
8458.0 1.0
8667.0 1.75953
8674.0 1.75464
8680.0 1.78886
8687.0 1.86706
8694.0 1.85728
8700.0 16892.0
8640.0 1.58358
8646.0 1.652
8653.0 1.65689
8660.0 1.68622
8667.0 1.75953
8674.0 1.75464
8680.0 1.78886
8687.0 1.86706
8694.0 1.85728
8700.0 1.90616
8708.0 1.98436
8714.0 1.98925
8721.0 2.03324
8728.0 299066.0
9072.0 1.86706
9079.0 1.88172
9086.0 1.94037
25.0 1.87683
9032.0 855.0
9438.0 2.10166
9444.0 2.15054
9451.0 2.10655
9458.0 2.07722
9464.0 2.09677
9472.0 2.01369
9478.0 1.95503
9485.0 13812.0
9424.0 2.11632
9431.0 2.10655
9438.0 2.10166
9444.0 2.15054
9451.0 2.10655
9458.0 2.07722
9464.0 2.09677
9472.0 2.01369
9478.0 1.95503
9485.0 1.912
9424.0 2.11632
9431.0 2.10655
9438.0 2.10166
9444.0 2.15054
9451.0 2.10655
9458.0 2.07722
9464.0 2.09677
9472.0 2.01369
9478.0 1.95503
9485.0 1.92082
9492.0 1.81329
9498.0 1.75464
9505.0 1.74487
9850.0 1.79374
9857.0 1.78397
9864.0 1.83284
9870.0 1.78886
9877.0 1.735
10632.0 1.41251
10639.0 1.48094
10646.0 1.5347
10653.0 1.53959
10660.0 1.62268
10668.0 1.64712
10675.0 1.67155
10683.0 1.75464
10690.0 1.75953
10697.0 1.80352
10704.0 1.876861
11046.0 1.87683
11054.0 1.85239
11061.0 1.92571
11068.0 1.91105
11075.0 1.93548
11083.0 1.98436
11090.0 1.94037
11098.0 2.0039262
11039.0 1.88661
11046.0 1.87683
11054.0 1.85239
11061.0 1.92571
11068.0 1.91105
11075.0 1.93548
11083.0 1.98436
11090.0 1.94037
11098.0 2.003912
11440.0 2.1652
11447.0 2.11632
11454.0 2.06256
11461.0 2.05279
11468.0 1.94037
11475.0 1.8768256
11418.0 2.13099
11425.0 2.15543
11432.0 2.1261
11440.0 2.1652
11447.0 2.11632
11454.0 2.06256
11461.0 2.05279
11468.0 1.94037
11475.0 1.87683
11484.0 1.82307
11491.0 1.71065
168.0 2.06745
12175.0 2.0479
12182.0 2.00391
12189.0 1.87683
12196.0 1.8279329
12873.0 1.87195
12881.0 1.94037
12889.0 1.9306
12896.0 2.01369
12903.0 2.04301
12910.0 2.06256
12917.0 2.14565
12924.0 2.1261
1293866.0 1.81329
12873.0 1.87195
12881.0 1.94037
12889.0 1.9306
12896.0 2.01369
12903.0 2.04301
12910.0 2.06256
12917.0 2.14565
12924.0 2.1261
12932.0 6.0
12873.0 1.87195
12881.0 1.94037
12889.0 1.9306
12896.0 2.01369
12903.0 2.04301
12910.0 2.06256
12917.0 2.14565
12924.0 2.1261
12932.0 2.1261
12939.0 2.16031
123282.0 1.85728
13289.0 1.8284751
13231.0 1.83284
13238.0 1.87195
13245.0 1.82796
13252.0 1.83284
13259.0 1.87195
13266.0 1.81818
13274.0 1.85728
13282.0 1.85728
13289.0 1.8230334
13631.0 1.67644
13638.0 1.74976
13645.0 1.73998
13652.0 7.0
1329.0 1.36364
14337.0 1.43695
14345.0 1.43695
14352.0 1.51026
14359.0 1.56892
14366.0 1.56892
14373.0 1.65689
14381.0 1.68622
14388.0 1.70088
1439329.0 1.36364
14337.0 1.43695
14345.0 1.43695
14352.0 1.51026
14359.0 1.56892
14366.0 1.56892
14373.0 1.65689
14381.0 1.68622
14388.0 1.70088
14395.0 1.79374
14402.0 1.78886
144145.0 1.82796
14752.0 1.86706
14759.0 1.86706
14708.0 1.84751
14715.0 1.90616
14723.0 1.84262
14730.0 1.85728
14737.0 1.87195
14745.0 1.82796
14752.0 1.86706
14759.0 1.86706
14767.0 1.832392
15109.0 1.3392
15116.0 1.39785
15123.0 1.3783
15130.0 1.45161
473.0 1.86217
15480.0 1.83284
15488.0 1.83773
15495.0 1.87683
15502.0 1.82307
15509.0 1.84751
15516.0 1.86706
15523.0 1.82307
1553165.0 1.79863
15473.0 1.86217
15480.0 1.83284
15488.0 1.83773
15495.0 1.87683
15502.0 1.82307
15509.0 1.84751
15516.0 1.86706
15523.0 1.82307
15531.0 1.0
15473.0 1.86217
15480.0 1.83284
15488.0 1.83773
15495.0 1.87683
15502.0 1.82307
15509.0 1.84751
15516.0 1.86706
15523.0 1.82307
15531.0 1.81304
15874.0 3.15738
15881.0 2.07722
15888.0 1.56892
15895.0 1.43695
15902.0 1.34897
15909.0 1.37341
1591751.0 3.43597
15858.0 4.45748
15865.0 4.3304
15874.0 3.15738
15881.0 2.07722
15888.0 1.56892
15895.0 1.43695
15902.0 1.34897
15909.0 1.37341
15917.0 16.80352
16259.0 1.77908
16266.0 1.78886
16274.0 1.83773
16281.0 1.79863
1616223.0 1.68133
16230.0 1.74487
16237.0 1.75464
16244.0 1.74487
16251.0 1.80352
16259.0 1.77908
16266.0 1.78886
16274.0 1.83773
16281.0 1.79863
116623.0 1.74487
16630.0 1.89638
16637.0 2.42424
16645.0 3.60215
16652.0 4.5063417394
17401.0 4.32063
17410.0 4.58455
17417.0 3.47019
17424.0 2.25806
17431.0 1.6422352
17373.0 1.79374
17380.0 1.74487
17387.0 2.13587
17394.0 3.13294
17401.0 4.32063
17410.0 4.58455
17417.0 3.47019
17424.0 2.25806
17431.0 1.64223
17373.0 1.79374
17380.0 1.74487
17387.0 2.13587
17394.0 3.13294
17401.0 4.32063
17410.0 4.58455
17417.0 3.47019
17424.0 2.25806
17431.0 1.64223
18181.0 4.5259
18188.0 4.4086
18195.0 3.10362
18203.0 2.05279
18210.0 1.5738
18217.0 1.36852
1822159.0 1.82796
18166.0 2.37537
18173.0 3.55816
18181.0 4.5259
18188.0 4.4086
18195.0 3.10362
18203.0 2.05279
18210.0 1.5738
18217.0 1.36852
18967.0 1.85728
18974.0 1.81818
18981.0 1.83284
18989.0 1.83284
18996.0 1.75464
19004.0 1.98925
19011.0 2.7664751
18953.0 1.82796
18960.0 1.81329
18967.0 1.85728
18974.0 1.81818
18981.0 1.83284
18989.0 1.83284
18996.0 1.75464
19004.0 1.98925
19011.0 2.7667
4.0 1.54936
20161.0 1.58358
20168.0 1.6129
20175.0 1.58358
20183.0 1.65689
20190.0 1.66178
20197.0 1.64223
20205.0 1.70577
20212.0 1.7057747
20154.0 1.54936
20161.0 1.58358
20168.0 1.6129
20175.0 1.58358
20183.0 1.65689
20190.0 1.66178
20197.0 1.64223
20205.0 1.70577
20212.0 1.70577
20219.0 81.79374
20561.0 1.82796
20569.0 1.78886
20576.0 1.73998
20583.0 1.98925
20999.0 1.76931
21006.0 1.81818
21013.0 1.78397
21020.0 1.82796
21027.0 1.84751
21035.0 1.0
20976.0 1.69599
20983.0 1.76442
20990.0 1.73509
20999.0 1.76931
21006.0 1.81818
21013.0 1.78397
21020.0 1.82796
21027.0 1.84751
21377.0 4.56989
21384.0 3.47507
21391.0 2.24829
21399.0 1.62268
21406.0 1.4174
21413.0 1.31476
21421.0 1.33431
21428.0 1.33431
21435.0 9.0
21377.0 4.56989
21384.0 3.47507
21391.0 2.24829
21399.0 1.62268
21406.0 1.4174
21413.0 1.31476
21421.0 1.33431
21428.0 1.33431
After about 8500 you can see some corrupted data. This ruins the plot
completely, I see my options as either changing the way I do things in Python
or using an exception handler to ignore such values, but it would be nice to
know why they happen and therefore to eliminate such issues.
For reference here is the implementation of pyserial on Python:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure
import PyQt4.QtGui as gui, PyQt4.QtCore as core
import collections
import time
import random
import numpy as np
import serial
ser = serial.Serial('/dev/tty.usbmodem1411', 19200)
time.sleep(2)
ser.write('S')
# def get_line():
# x = time.time()%10000
# y = random.random() * 5
# return "%d %.3f\n" % (x,y)
refreshMillis = 5
N = 1000
xs = collections.deque(maxlen=N)
ys = collections.deque(maxlen=N)
xsLong = []
ysLong = []
app = gui.QApplication([])
fig = Figure() # container for Axes
canvas = FigureCanvas(fig) # holds Figure instance
ax = fig.add_subplot(111) # creates and adds Axes instance to Figure instance 'fig'
ax.set_ylim([0,5])
# ax.set_xlim([0,12000])
ax.set_title('Arduino Electrocardiogram')
ax.set_xlabel("Time (ms)")
ax.set_ylabel("Voltage (V)")
ax.grid(True)
line2D, = ax.plot(xs,ys) # adds plot by calling required function 'plot' on axes instance 'ax'
canvas.show()
waiting = ser.inWaiting()
print waiting
def process_line():
line = ser.readline()
data = map(float,line.split(" "))
xs.append(data[0])
ys.append(data[1])
xsLong.append(data[0])
ysLong.append(data[1])
line2D.set_data(xs,ys)
print data
xmin, xmax = min(xs),max(xs)
if xmin == xmax:
ax.set_xlim([xmin,xmin+1])
else:
ax.set_xlim([xmin,xmax])
canvas.draw()
zipString = zip(xsLong,ysLong)
f = open("plot_store.txt","w")
for line in zipString:
f.write(" ".join(str(x) for x in line) + "\n")
f.close()
timer = core.QTimer()
timer.timeout.connect(process_line)
timer.start(refreshMillis)
app.exec_()
ser.flush()
ser.close()
Answer: In process_line() you append data to xsLong as well as ysLong. Thus these
become longer with each pass. Both are then zippend and fed into
plot_store.txt That is instead of appending a line to plot_store.txt you
rewrite it with each pass. Since the data gets longer and longer this will
take more and more time. At one point in time it will make your handler slow
enough to start missing data.
Solution: do not rewrite the file each time but only append the new data.
|
Install python, pygtk in user's space
Question: I am trying to install python with pygtk in my ubuntu system.
I don't have root access so I need to install all the packages locally say
/home/user/local/lib
I am able to install python, but I am not able to link other
packages(pygobject, pygtk, etc) to the locally installed python. And if I try
to install pygtk locally using the command
./configure --prefix=/home/shrihari/local/lib/pygtk2.24/
It gives the following error
checking for GLIB - version >= 2.8.0... yes (version 2.28.6)
checking for PYGOBJECT... yes
checking for gio-types.defs... no
checking for ATK... yes
checking for PANGO... yes
checking for codegen... configure: error: unable to find PyGObject codegen
My default python version is python2.4. If I try to import pygtk in python2.4
it works fine but i need pygtk in python2.7. So how can I achieve this? If
there is any good documentation available for installing python, pygtk,
pygobject locally in user space please share.
Thanks in advance
Answer: In general, to be able to link a build to something already installed, you
need to have set up the LD_LIBRARY_PATH and (for Python modules) PYTHONPATH to
the directories where you have installed that "something". So in this example,
if you install Python 2.7 with prefix /home/shrinari/local/python27, you need
afterwards set the system variables like this (for bash):
export LD_LIBRARY_PATH=/home/shrinari/local/python27/lib:$LD_LIBRARY_PATH
export PYTHONPATH=/home/shrinari/local/python27/lib/python2.7/site-packages:$PYTHONPATH
export PKG_CONFIG_PATH=/home/shrinari/local/python27/lib/pkgconfig:$PKG_CONFIG_PATH
And after that you can try to compile something dependent on your new Python
installation. But, according to the configuration error provided, I don't
think this helps in your situation. It seems that you have something missing
from PyGObject, maybe just header files, maybe some module (I don't know
PyGObject specifics). Anyway, why the configure script can not find something
is usually better visible from config.log file which can be found in the build
directory after running the configure script.
|
python string to date ISO 8601
Question: I am converting many obscure date formats from an old system. The dates are
unpacked/processed as strings and converted into ISO 8601 format.
This particular function attempts to convert YYMMDD0F to YYYYMMDD -- function
name says it all. Dates from the year 2000 make this messy and clearly this is
not the most pythonic way of handling them. How can I make this better using
the `dateutil.parser`?
def YYMMDD0FtoYYYYMMDD(date):
YY = date[0:2]
MM = date[2:4]
DD = date[4:6]
if int(YY) >= 78:
YYYY = '19%s' % YY
elif 0 <= int(YY) <= 77 and MM!='' and MM!='00':
YYYY = '20%s' % YY
else:
YYYY = '00%s' % YY
return "%s-%s-%s" % (YYYY, MM, DD)
Answer: You don't need to use `dateutil`, you can do this with
[`datetime.strptime`/`.strftime`](http://docs.python.org/2/library/datetime.html#strftime-
and-strptime-behavior):
from datetime import datetime
def YYMMDD0FtoYYYYMMDD(date):
return datetime.strptime(date[:6], "%y%m%d").strftime("%Y-%m-%d")
Example usage:
>>> YYMMDD0FtoYYYYMMDD('1403110F')
'2014-03-11'
|
how to install packages o python?
Question: Mac OSX 10.6.8 Python 2.7
Hi guys,
I just recently started programming with Python using the "Think Python" by
Allen Downey. In Chapter 4, the first case study, he recommends to install a
package called swampy...so basically I´m stuck here. For trouble shooting
Downey recommends:
* import swampy.TurtleWorld -> doesnt work
* pip install swampy -> command not found(Could`t also install pip)
After typing
* sudo python setup.py install
I get
/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'setup.py': [Errno 2] No such file or directory
Then I unzip the package swampy and thought to drag&drop it into the
appropriate directory, however my directory ends with
`System/Library/Frameworks/Python.framework/Versions/2.7/Resources` here I
have 3 objects "`English.Iproj`" "`inof.plist`" and "`Python`"
Does anybody have some suggestions how to install that package?
THX a lot
Answer: you shall do:
sudo easy_install pip
sudo pip install swampy
|
global name logger is not defined thru classes?
Question: I cant get logger as a global name... I tried it inside a normal script, and
later trying to debug inside the python cli, but its out of my reach
apparently...
(as you will notice, I tried to define logger global everywhere, but also
without that, no success)
Inside the python cli-program:
import time
import datetime
import subprocess
import re
import glob
import logging
from daemon import runner
from lockfile import LockTimeout
import RPIO
import picamera
import atexit
#From here, it should be global right?
global logger
logger = logging.getLogger("DoorcamLog")
import DoorcamExample
doorcam=DoorcamExample.Doorcam()
Error returned:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "DoorcamExample.py", line 28, in __init__
logger.info('Doorcam started capturing')
NameError: global name 'logger' is not defined
DoorcamExample.py:
#!/usr/bin/python
import sys
import os
if os.geteuid() != 0:
# This works perfect on a Raspbian system because there's no rootpassword required
os.execvp("sudo", ["sudo"] + sys.argv)
print('to far!') #This should NEVER be reached, there is something wrong...
sys.exit(1)
import time
import datetime
import subprocess
import re
import glob
import logging
from daemon import runner
from lockfile import LockTimeout
import RPIO
import picamera
import atexit
class Doorcam:
global logger
def __init__(self):
logger.info('Doorcam started capturing')
self.pollLightFile='/var/tmp/picam-pollLight'
atexit.register(self.stopListening)
def socket_callback(self, socket, val):
vals=val.split()
if len(vals) == 0 or len(vals) > 4:
number=1
notify=True
trigger='Socket'
triggernotify='Socket (value %s)'%val
elif len(vals) == 1:
number=int(vals[0])
notify=True
trigger='Socket'
triggernotify='Socket (value %s)'%val
elif len(vals) == 2:
number=int(vals[1])
notify=True
trigger=vals[0]
triggernotify=vals[0]
elif len(vals) == 3:
number=int(vals[1])
trigger=vals[0]
triggernotify=vals[0]
notify=self.boolval(vals[2])
elif len(vals) == 4:
number=int(vals[2])
trigger=vals[0]
triggernotify=vals[0], [1]
notify=self.boolval(vals[3])
socket.send('self.upload(self.shot(filename=self.filename, number=number, trigger=trigger), notify=notify,trigger=triggernotify)')
RPIO.close_tcp_client(socket.fileno())
def startListening(self,channel,port=8080, threaded=True):
#RPIO.add_interrupt_callback(channel, self.gpio_callback, pull_up_down=RPIO.PUD_DOWN, debounce_timeout_ms=1000)
RPIO.add_tcp_callback(port, self.socket_callback)
RPIO.wait_for_interrupts(threaded=threaded)
def stopListening(self):
logger.info('Stop listening')
RPIO.stop_waiting_for_interrupts()
global logger
Answer: "Global" variables are only global within a single module, so your
DoorcamExample.py doesn't have access to logger that you defined in some other
module.
In this case, you don't need a global variable, because the logging module
already maintains a truly global (i.e., visible from all modules) registry of
loggers. So if you do `logging.getLogger("DoorcamLog")` in any of your
modules, you'll get a reference to the same logger.
|
IronPython Remote Debugging with PTVS
Question: i've implemented IronPython in my C#-Application successful. I store all my
scripts in a database and load them when they are needed. Now i want to debug
my Python-Code with the PTVS. But always when i try to connect with the remote
debugger to my application the visual studio say that i should use
`ptvsd.enable_attach()`.
1. i thought if i enable the Debug-Mode for my Python-Engine it would be enought
2. If i need to import ptvsd, how i can import the scripts(**ini** , **main** , ...) should i put them also in my database?
I can't figure this points out and have tried a lot, but nothing realy work.
**EDIT** : I could figure out how to use ptvsd, i have to "include" the ptvsd-
module:
//copied from: C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.0
string dir = Path.GetDirectoryName("C:\\Support\\Modules\\ptvsd");
ICollection<string> paths = myScriptEngine.GetSearchPaths();
if (dir != null && dir != "")
{
paths.Add(dir);
}
else
{
paths.Add(Environment.CurrentDirectory);
}
But now i get an error in os.py:
> global name 'statvfs_result' is not defined
in the lines:
_copy_reg.pickle(statvfs_result, _pickle_statvfs_result,
_make_statvfs_result)
**EDIT 2** : It seems that i can ignore the error message with the global
name. But now i get the following message:
> IronPython must be started with -X:Tracing and -X:Frames options to support
> PTVS remote debugging.
**EDIT 3** : I solved the error with Tracing and Frames by using the following
code:
Dictionary<string, object> options = new Dictionary<string, object>();
options["Debug"] = true;
options["Tracing"] = true;
options["Frames"] = true;
myScriptEngine = Python.CreateEngine(options);
But now i have the next problem, i can't attach visual studio to my
application, i get always the following error-message:
> Could not connect to remote Python process at 'localhost:5678'. Make sure
> that the process is running, and has called ptvsd.enable_attach()-
**EDIT 4:** My python code:
# -----------------------------------------------
# Framework-Root-Script
# This script is the main-framework script
# Autor: BE
# Date: 07.10.2013
# -----------------------------------------------
# --------------------------------------------
import sys
#import atexit
import ptvsd
ptvsd.enable_attach(None)
#ptvsd.wait_for_attach()
#
from System import *
from System.Windows import MessageBox
from System.Windows.Controls import Grid, MenuItem
from ESS.MS.Base import GlobalSettings
from ESS.MS.Framework.Core.TaskbarNotification import TaskbarNotificationManager
from ESS.MS.Framework.UIG.Mask import DynamicMaskManager
# --------------------------------------------
# --------------------------------------------
#<summary>
#Eine Instanz dieser Klasse wird automatisch mit
#dem Start des DocCenter Studios erstellt.
#</summary>
class StudioInstance:
# --------------------------------------------
# Declarations
# --------------------------------------------
# --------------------------------------------
# Constructor
def __init__(self):
pass
# --------------------------------------------
# --------------------------------------------
# Will be called before the Login-Window open
def BeforeUserLogin(self):
try:
pass
except:
pass
# --------------------------------------------
# --------------------------------------------
#<summary>
#Wird ausgeführt, wenn der Login für einen Benutzer
# Fehlschlägt
#</summary>
#<param Name="InputUserName">Eingegeber Benutzername</param>
#<param Name="InputDomain">Eingegebene Domain<param>
def LoginFailed(self, InputUserName, InputDomain):
try:
pass
except:
pass
# --------------------------------------------
# --------------------------------------------
# Will be called if the Login-Process is complete
def LoginComplete(self, UserName, Domain):
try:
# -------------------------------------------------------------------
# Control auf das Tray-Icon setzten (Linksklick)
# Mask = DynamicMaskManager.Singleton.GetMaskInstance("Win_DCC_Bediener", False)
# grid = Grid()
# grid.Children.Add(Mask.VisualElement)
# TaskbarNotificationManager.Singleton.AddTrayPopupControl(grid)
# -------------------------------------------------------------------
# -------------------------------------------------------------------
# Context-Menu einttrag auf das Tray-Icon setzten
# test = MenuItem()
# test.Header = "Hallo Welt"
# TaskbarNotificationManager.Singleton.AddContextMenuItem(test)
# -------------------------------------------------------------------
pass
except Exception, e:
MessageBox.Show(e.ToString())
# --------------------------------------------
# --------------------------------------------
# Will be called synchron with the UI (same thread)
def SyncUpdate(self):
try:
pass
except Exception, e:
MessageBox.Show(e.ToString())
# --------------------------------------------
# --------------------------------------------
# Will be called in a custom thread
def AsyncUpdate(self):
try:
pass
except:
pass
# --------------------------------------------
# --------------------------------------------
**EDIT 5** I think i can attach now to the process. But when i click on the
refresh-button in the visual studio debugger window, visual studio hang up and
the program doesn't react anymore.
Refresh-Button: 
Maybe some one can halp me, thank you!
Answer: Assuming that the process is running on `localhost` and you've called
`ptvsd.enable_attach()`, it's probably a firewall issue. You might have to
tweak the Windows firewall to allow connections to that port (I _thought_ that
localhost connections were always allowed but I'm not sure).
|
Apache hangs with Django / Matplotlib app
Question: new StackOverflow user here. I need help with an Apache freezing problem. I
have a WAMPServer setup on Win 7 64-bit and am working with python / django /
mysql / mod_wsgi / matplotlib, experimenting with dynamically rendered images.
I am using Apache to serve static files.
I am trying to plot data from a MySQL database. My views.py file is below.
When I invoke the function "view_Stats" by visiting the appropriate web page,
this calls the "CreateFig" function to create and save .png files to a
directory that are subsequently served by Apache. It works fine initially, but
it seems as if a maximum of 8 calls can be made to the "CreateFig" function
before Apache just hangs. I have to restart Apache at that point, but it takes
a while (minutes) for it to restart.
Looking at the Apache error logs (see below) shows an error related to Apache
child processes that requires Apache to force it to terminate. I suspect some
sort of memory leak / error, but I'm pretty new at this and can't troubleshoot
well; I've Googled this and looked around on StackOverflow, no joy.
Any help would be appreciated!
[Tue Mar 11 17:01:07.550093 2014] [core:notice] [pid 2820:tid 404] AH00094: Command line: 'c:\\wamp\\bin\\apache\\apache2.4.4\\bin\\httpd.exe -d C:/wamp/bin/apache/Apache2.4.4'
[Tue Mar 11 17:01:07.551093 2014] [mpm_winnt:notice] [pid 2820:tid 404] AH00418: Parent: Created child process 3528
[Tue Mar 11 17:01:07.856093 2014] [mpm_winnt:notice] [pid 3528:tid 324] AH00354: Child: Starting 150 worker threads.
[Tue Mar 11 17:04:53.233893 2014] [mpm_winnt:notice] [pid 2820:tid 404] AH00422: Parent: Received shutdown signal -- Shutting down the server.
[Tue Mar 11 17:05:23.248293 2014] [mpm_winnt:notice] [pid 2820:tid 404] AH00431: Parent: Forcing termination of child process 3528
The Code from views.py is below:
from django.contrib import auth
from django.contrib.auth.models import User, Group
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponseRedirect
from rwjcnlab import settings
from clientele.models import UserProfile
from reports.models import EEG, LTM, EMU, AEEG
import os, datetime
import numpy
from pylab import *
import matplotlib.pyplot as plt; plt.rcdefaults()
import matplotlib.pyplot as plt
import gc
# CREATE VIEWS HERE
def view_Stats(request):
UID = UserProfile.objects.get(user_id = request.user.id)
StatsEEG, StatsLTM, StatsAEEG, StatsEMU, start_date = ReportNumbers(UID.id)
# Create figures
CreateFig(StatsEEG, 300, 50, 'EEG', 'b')
CreateFig(StatsLTM, 100, 10, 'LTM', 'r')
CreateFig(StatsAEEG, 15, 3, 'AEEG', 'y')
CreateFig(StatsEMU, 25, 5, 'EMU', 'c')
return render_to_response('view_Stats.html', {
'StatsEEG': StatsEEG,
'StatsLTM': StatsLTM,
'StatsAEEG': StatsAEEG,
'StatsEMU': StatsEMU,
'start_date': start_date,
'user': request.user,
})
def CreateFig(Stats, ymax, yinc, figname, c):
nAll = tuple(x[1] for x in Stats)
nUser = tuple(x[2] for x in Stats)
xlabels = tuple(x[0].strftime("%b%y") for x in Stats)
ind = numpy.arange(len(xlabels)-1.4,-0.4,-1) # the x locations for the groups
width = 0.8 # the width of the bars: can also be len(x) sequence
plt.ioff()
fig = plt.figure(figsize=(10, 5), dpi=72, facecolor='w', edgecolor='k')
p1 = plt.bar(ind, nAll[1:], width, color=c)
p2 = plt.bar(ind, nUser[1:], width, color='g')
plt.title(figname+' Volumes at RWJUH')
plt.xticks(ind+width/2., xlabels[1:])
plt.yticks(numpy.arange(0,ymax,yinc))
plt.legend( (p1[0], p2[0]), ('Total', 'User') )
plt.savefig(os.path.join(settings.BASE_DIR, 'static/'+figname+'.png'))
fig.clf()
plt.close(fig)
gc.collect()
return
Answer: This is likely because you're trying to connect to a (presumably non-existent)
X-server when you use matplotlib. If you do have X running on your webserver,
you probably still want to avoid using an interactive backend for matplotlib
(_Edit_ : Just saw that you're on windows. Obviously, it's not that
mattplotlib is trying to connect to an X-server when run on Windows, but I'd
be willing to bet that your problem is still related to using an interactive
backend and matplotlib trying to connect to the graphical display.)
If you want to use matplotlib without interactive plots (i.e. without needing
an X-server), then you need to explicitly use a non-interactive backend. (e.g.
`Agg`, `pdf`, etc)
First off, remove `from pylab import *`. That's a really bad idea for a huge
number of reasons (hint, `min` and `max` aren't what you think they are, among
other things). Also, you don't seem to be using it. You're already accessing
matplotlib functionality through the pyplot interface and `numpy` though the
numpy namespace.
Next, _before_ you do `import matplotlib.pyplot as plt` (or before you do
`from pylab import *` if you decide not to remove it), do:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot # etc...
Now matplotlib won't try to connect to the X display everytime you make a new
figure.
|
Python PyQt: How Run While Loop Without Locking Main Dialog Window
Question: Pressing Ok button will run while_loop() method which prints some message on a
screen.
While **while_loop()** method is running the main dialog becomes
irresponsible. It's interesting that even after a dialog window is closed the
function itself will be still running. Apparently that is not desired. When
the dialog box is closed **while_loop()** method should be stopped as well. It
would be great if running a while_loop() method wouldn't lock (make
irresponsible) the main dialog window as well...
import sys, time
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.main_layout = QtGui.QVBoxLayout()
ok_button = QtGui.QPushButton("Run")
ok_button.clicked.connect(self.OK)
self.main_layout.addWidget(ok_button)
cancel_button = QtGui.QPushButton("Cancel")
cancel_button.clicked.connect(self.cancel)
self.main_layout.addWidget(cancel_button)
central_widget = QtGui.QWidget()
central_widget.setLayout(self.main_layout)
self.setCentralWidget(central_widget)
def myEvenListener(self):
state=True
while state:
for i in range(10,100):
time.sleep(i*0.01)
print '.'*i
def OK(self):
self.myEvenListener()
def cancel(self):
sys.exit()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.resize(480, 320)
window.show()
sys.exit(app.exec_())
Answer: You might want to use thread to solve this problem. and so that your thread
closes
import threading
import sys, time
from PyQt4 import QtCore, QtGui
import psutil
import os
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.main_layout = QtGui.QVBoxLayout()
ok_button = QtGui.QPushButton("Run")
ok_button.clicked.connect(self.OK)
self.main_layout.addWidget(ok_button)
cancel_button = QtGui.QPushButton("Cancel")
cancel_button.clicked.connect(self.cancel)
self.main_layout.addWidget(cancel_button)
central_widget = QtGui.QWidget()
central_widget.setLayout(self.main_layout)
self.setCentralWidget(central_widget)
def myEvenListener(self,stop_event):
state=True
while state and not stop_event.isSet():
for i in range(10,100):
time.sleep(i*0.01)
print '.'*i
def OK(self):
self.stop_event=threading.Event()
self.c_thread=threading.Thread(target=self.myEvenListener, args=(self.stop_event,))
self.c_thread.start()
def cancel(self):
self.stop_event.set()
self.close()
def main():
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.resize(480, 320)
window.show()
app.exec_()
main()
def kill_proc_tree(pid, including_parent=True):
parent = psutil.Process(pid)
if including_parent:
parent.kill()
me = os.getpid()
kill_proc_tree(me)
|
Categorize and calculate something in python
Question: I have following input file
O 2.05151 39.51234 0.00000
O 32.69451 1.48634 8.31300
O 10.53351 21.63634 7.95400
O 30.37451 20.74134 0.99700
Si 8.06451 19.19434 10.21700
Si 32.03251 42.98634 21.23900
O 9.69051 19.06934 16.27200
Si 2.18351 39.67034 11.36500
Si 31.78351 2.38334 1.42300
......
First, I hope to categorize these data based on 4th column, such as [0~1, 1~2,
2~3, ...., max-1 ~ max] and then count the number of 'Si' and 'O' in each of
sections. After that, do some calculation based on those numbers then print
out. Printing format was setted to
section1 number_of_Si_in_section1 number_of_O_in_section1 add_two_numbers
...
with three space devided I tried to use nested for loops, but failed.
for i1 in range (total number of lines)
for j1 in range (each sections)
if (at_name[j1] = 'Si'):
num_Si = num_Si + 1
if (at_name[j1] = 'O'):
num_O = num_O + 1
Something like this but I stucked in the middle. I heard that numpy, csvanal
or other function can do this easily, but I have no idea about them.
Answer: You should test small bits of this code line by line in your Python
interpreter. You will see the small mistakes (like you used single equals
instead of double equals to check equality).
Nothing inside the loop depends on `i1`, so it looks like this loop will just
do the same thing again and again. Also, you should use a dictionary (or
better yet, collections.Counter):
import collections
import csv
f = open('myfile.csv','rb')
reader = csv.reader(f, delimiter='\t')
si_counter = collections.Counter()
o_counter = collections.Counter()
for line in reader:
number = int(line[3])
si_or_o = line[0]
if si_or_o == 'Si':
si_counter[number] += 1
elif si_or_o == 'O':
o_counter[number] += 1
The code is untested and you can improve it.
|
ArgumentParser object has no attribute 'add_option' on passing flags
Question: Day three of learning python.
I'm attempting to understand how to pass flags from the command line and call
a function with that flag. However, I'm getting the following error:
Traceback (most recent call last):
File "main.py", line 18, in <module>
parser.add_option("-l", action="callback", callback=printLogs)
AttributeError: 'ArgumentParser' object has no attribute 'add_option'
The code is here:
import argparse
def printLogs():
print("logs!")
parser = argparse.ArgumentParser()
parser.add_argument('-e','--entry', type=str, help='New entry',required=False)
parser.add_option("-l", action="callback", callback=printLogs)
args = parser.parse_args()
I can understand that parser.add_option doesn't exist for parser. This much is
clear. I can also see that the OptionParser has been deprecated as per [this
link](http://stackoverflow.com/questions/4960880/understanding-optionparser).
So, OptionParser is out.
The question being: How do I parse the -l argument such that the printLogs
function is called when its passed?
Answer: The way I would implement this is:
import argparse
def printLogs():
print("logs!")
parser = argparse.ArgumentParser()
parser.add_argument('-e','--entry', type=str, help='New entry')
parser.add_argument("-l", action="store_true", help='print logs')
args = parser.parse_args()
if args.l:
printLogs()
The primary purpose of `argparse` is to parse the input (`sys.argv`), and give
you a set of argument values (`args` is a simple `namespace` object).
`callbacks` is a `optparse` concept that have not been included in `argparse`.
The `FooAction` example in the docs,
<http://docs.python.org/3.4/library/argparse.html#action>, does something like
this `optparse` callback. It prints some information when called, and then
does the important thing - set a value in the namespace.
|
Kill a process and all its threads from the same process
Question: I am spawning a python process using MultiProcess library and within it I am
spawning around 100 threads( of 3 types each performing a separate function
and using a Queue).
I want my process to neatly terminate when a db flag is raised killing all the
threads and the process itself and also set a db level terminated flag once
everything's ended.
Here's my approach: As soon as a flag is set in the database( I can poll the
db at the end of the process code after spawning the threads), I can exit the
poll loop which exits my process. To kill all the threads, I'd have to keep an
array of thread-id's spawned and send a kill to all of them. I need that all
the threads will get killed along with their connections(threads are connected
to mysql,mongo and there's a websocket connection thread to another server).
If someone has a better approach or if there's any drawback in my approach,
please suggest.
Answer: This is something you can try, but no guarantee's . This function kill the
whole process tree.
import psutil , os
def kill_proc_tree(pid, including_parent=True):
parent = psutil.Process(pid)
for child in parent.get_children(recursive=True):
child.kill()
if including_parent:
# Set the db terminate flag.
# the next step will kill the whole process
parent.kill()
# when Db flag iss set run this function
def terminate():
me = os.getpid()
kill_proc_tree(me)
|
Good approach for updating the GUI continuously in wxPython using threads?
Question: I am working on a GUI app using python v2.7 and wxPython v3.0 on windows 7 OS.
I have to update my GUI continuously which contains lots of panels. Each
panels contains a `wx.StaticText`. I have to update these `wx.StaticTexts`
continuously. I thought of using `threads`. Also I am using `pubsub` module
for communicating with the GUI to update these `wx.StaticTexts`. Every thing
works as intended. I have created a short demo below of my real problem.
**Problem** : In my code below, two threads are created. Both the threads are
able to update the GUI using `wx.CallAfter()`. What if I have 100 panels to
update? Do I need to create 100 classes for each of the thread which updates a
particular panel? I want the threads to work independently of the other
threads. What will possibly be the better approach than this one?
**Code** : Please find the sample code below to play around:
import wx
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub
import time
from threading import Thread
import threading
class GUI(wx.Frame):
def __init__(self, parent, id, title):
screenWidth = 500
screenHeight = 400
screenSize = (screenWidth,screenHeight)
wx.Frame.__init__(self, None, id, title, size=screenSize)
self.locationFont = locationFont = wx.Font(12, wx.MODERN, wx.NORMAL, wx.BOLD)
mainSizer = wx.BoxSizer(wx.VERTICAL)
myPanelA = wx.Panel(self, style=wx.SIMPLE_BORDER)
myPanelA.SetBackgroundColour('#C0FAE0')
self.myTextA = wx.StaticText(myPanelA, -1, "I have a problem :( ")
myPanelB = wx.Panel(self, style=wx.SIMPLE_BORDER)
myPanelB.SetBackgroundColour('#C0FAFF')
self.myTextB = wx.StaticText(myPanelB, -1, "Me too :( ")
mainSizer.Add(myPanelA, 1, wx.EXPAND, 5)
mainSizer.Add(myPanelB, 1, wx.EXPAND, 5)
self.SetSizer(mainSizer)
pub.subscribe(self.updatePanelA, 'Update-panelA')
pub.subscribe(self.updatePanelB, 'Update-panelB')
def updatePanelA(self, message):
self.myTextA.SetLabel(message)
def updatePanelB(self, message):
self.myTextB.SetLabel(message)
class threadA(Thread):
def __init__(self):
Thread.__init__(self)
self.start()
def run(self):
ObjA = updateGUI()
ObjA.methodA()
class threadB(Thread):
def __init__(self):
Thread.__init__(self)
self.start()
def run(self):
ObjB = updateGUI()
ObjB.methodB()
class updateGUI():
def methodA(self):
while True:
time.sleep(3)
wx.CallAfter(pub.sendMessage, 'Update-panelA', message='Problem solved')
def methodB(self):
while True:
time.sleep(5)
wx.CallAfter(pub.sendMessage, 'Update-panelB', message='Mine too')
if __name__=='__main__':
app = wx.App()
frame = GUI(parent=None, id=-1, title="Problem Demo")
frame.Show()
threadA()
threadB()
app.MainLoop()
Thank you for your time!
Answer: You can define your private "selfUpdatePanel" to launch its own thread to
update its own text field. The code would be easy maintain in this way.
Check following code modified based on your code:
import wx
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub
import time
from threading import Thread
import threading
class selfUpdatePanel(wx.Panel):
def __init__(self, parent, mystyle, interval, topic, message):
wx.Panel.__init__(self, parent, style = mystyle)
pub.subscribe(self.updatePanel, topic)
self.updateMsg = message
self.textCtrl = None
self.interval = interval
self.topic = topic
pub.subscribe(self.updatePanel, self.topic)
def setTextCtrl(self,text):
self.textCtrl = text
def updatePanel(self):
self.textCtrl.SetLabel(self.updateMsg)
def threadMethod(self):
while True:
print "threadMethod"
time.sleep(self.interval)
wx.CallAfter(pub.sendMessage, self.topic)
def startThread(self):
self.thread = Thread(target=self.threadMethod)
self.thread.start()
class GUI(wx.Frame):
def __init__(self, parent, id, title):
screenWidth = 500
screenHeight = 400
screenSize = (screenWidth,screenHeight)
wx.Frame.__init__(self, None, id, title, size=screenSize)
self.locationFont = locationFont = wx.Font(12, wx.MODERN, wx.NORMAL, wx.BOLD)
mainSizer = wx.BoxSizer(wx.VERTICAL)
#myPanelA = wx.Panel(self, style=wx.SIMPLE_BORDER)
myPanelA = selfUpdatePanel(self, wx.SIMPLE_BORDER, 3, 'Update-panelA', 'Problem solved')
myPanelA.SetBackgroundColour('#C0FAE0')
self.myTextA = wx.StaticText(myPanelA, -1, "I have a problem :( ")
myPanelA.setTextCtrl(self.myTextA)
#myPanelB = wx.Panel(self, style=wx.SIMPLE_BORDER)
myPanelB = selfUpdatePanel(self, wx.SIMPLE_BORDER, 5, 'Update-panelB', 'Mine too')
myPanelB.SetBackgroundColour('#C0FAFF')
self.myTextB = wx.StaticText(myPanelB, -1, "Me too :( ")
myPanelB.setTextCtrl(self.myTextB)
mainSizer.Add(myPanelA, 1, wx.EXPAND, 5)
mainSizer.Add(myPanelB, 1, wx.EXPAND, 5)
self.SetSizer(mainSizer)
myPanelB.startThread()
myPanelA.startThread()
if __name__=='__main__':
app = wx.App()
frame = GUI(parent=None, id=-1, title="Problem Demo")
frame.Show()
app.MainLoop()
|
Passing values from bash to python
Question: I am trying to implement bash with python can anybody help me or teach me on
what should be done.Thanks my code is
import io
val=os.system("echo 'sdfsfs'") #for example
print(val)
Answer:
>>> import subprocess
>>> subprocess.chec
subprocess.check_call subprocess.check_output
>>> val = subprocess.check_output(['echo', "'sdfsfs'"])
>>> print(val)
'sdfsfs'
If you have ipython, you can also do this with a shell escape:
In [1]: val = !echo 'sdfsf'
In [2]: val
Out[2]: ['sdfsf']
|
Drawing a 2D function in matplotlib
Question: Dear fellow coders and science guys :)
I am using python with numpy and matplotlib to simulate a perceptron, proud to
say it works pretty well.
I used python even tough I've never seen it before, cause I heard matplotlib
offered amazing graph visualisation capabilities.
Using functions below I get a 2d array that looks like this: [[aplha_1, 900],
[alpha_2], 600, .., [alpha_99, 900]
So I get this 2D array and would love to write a function that would enable me
to analyze the convergence.
I am looking for something that will easily and intuitively (don't have time
to study a whole new library for 5 hours now) draw a function like this
sketch:

def get_convergence_for_alpha(self, _alpha):
epochs = []
for i in range(0, 5):
epochs.append(self.perceptron_algorithm())
self.weights = self.generate_weights()
avg = sum(epochs, 0) / len(epochs)
res = [_alpha, avg]
return res
And this is the whole generation function.
def alpha_convergence_function(self):
res = []
for i in range(1, 100):
res.append(self.get_convergence_for_alpha(i / 100))
return res
Is this easily doable?
Answer: You can convert your nested list to a 2d numpy array and then use slicing to
get the alphas and epoch counts (just like in matlab).
import numpy as np
import matplotlib.pyplot as plt
# code to simulate the perceptron goes here...
res = your_object.alpha_convergence_function()
res = np.asarray(res)
print('array size:', res.shape)
plt.xkcd() # so you get the sketchy look :)
# first column -> x-axis, second column -> y-axis
plt.plot(res[:,0], res[:,1])
plt.show()
Remove the plt.xkcd() line if you don't actually want the plot to look like a
sketch...
|
Pip is already installed: but I am getting no module named lxml
Question: I have installed lxml with pip. But when I run a script that uses lxml, I get
"no module named lxml." Why might this be? How do I fix it?
(venv)prompt$ sudo pip install lxml
Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/local/lib/python2.7/dist-packages
Cleaning up...
(venv)prompt$ python scripts/pyftp.py
Traceback (most recent call last):
File "scripts/pyftp.py", line 5, in <module>
from lxml import etree
ImportError: No module named lxml
Answer: It looks like you are in a virtualenv. You probably do not want to be root
when installing new packages.
|
What is wrong with my linked list?
Question: I am trying to create a class for nodes (it's suppsoed to be a system for a
queue) to `import` in another program. I know that the other program is
working fine since it works when `import`ing another type of queue that uses
the same function names(that is based on Pythons regular `list`). With this
queue-type however, I never seem to be able to get it to work. I'm sure that
there are MANY problems with my code(Since I've been getting a big variety of
error messages) and I would like some input on what i should change.
Here is the code for the class:
class Node():
def __init__(self, v=None, n=None):
self.item=v
self.next=n
lastnode=__init__
def put(self, v):
Node.lastnode.next=self
self.item=v
self.next=None
Node.lastnode=Node.lastnode.next
def get(self):
if Node.isempty(self):
return None
out=Node.__init__.next
Node.__init__.next=out.next
out.next=None
return ut.item
def isempty(self):
if Node.lastnode==Node.__init__:
return True
else:
return False
The `put` functions role is to put a new item/node last in the queue.
The `get` functions role is to remove the first node from the queue and
`return` its item.
The `isempty` function is there to check if the queue is empty.
Please give me some criticism on this.
Answer: Your primary problem is that you're trying to use a single class to solve a
problem that really requires two classes. Linked lists involve two kinds of
items: The nodes and the list structure itself. A node only "knows" two
things: the data it contains and the identity of the next node it links to.
The list object is what manages access to a group of linked nodes. By trying
to combine the two roles in a single class you're making it impossible to
realize a list. Think about, e.g., how your class could manage multiple nodes.
You're trying to get around such difficulties, it seems, by using class
attributes for list-level data (such as the identity of the head node), but
even if that could be made to work you'd only be able to work with one list
instance at a time.
In addition to this, your code has some basic syntactical issues. E.g., the
line `lastnode=__init__` does not call `__init__`; call syntax would be
`lastnode=__init__()`, but you can't do that in the body of the class
definition.
Here's a trivial implementation you could study:
class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class List(object):
def __init__(self):
self.head = None
def put(self, value):
new = Node(value)
new.next = self.head
self.head = new
def get(self):
if self.is_empty():
return None
old = self.head
self.head = old.next
return old.value
def is_empty(self):
return self.head is None
|
Selenium doesn't return after starting Chrome but returns after starting Firefox?
Question: I am trying to execute the following code in Python with Selenium:
def create_browser(first_page=None):
print "Starting"
browser = webdriver.Chrome()
if first_page:
browser.get(first_page);
print "Done."
return browser
browser = create_browser()
When I execute this code, Chromium starts but the "Done" statement doesn't get
printed. However, if I replace `Chrome()` by `Firefox()` the browser starts
and "Done" gets printed. I tried to verfiy this in terminal too. If I execute
following series of statements:
from selenium import webdriver
driver = webdriver.Chrome()
When I replace `Chrome()` by `Firefox()` the terminal returns normally and
displays `>>` (in the python shell but that doesn't happen with Chromium. Can
anyone tell what's going wrong here. I really appreciate your help. Thanks!
Update:
I am not sure if this helps but when I execute using `webdriver` a file called
`chromedriver.log` gets generated in the directory containing my code. It has
the following contents:
[0.000][INFO]: ChromeDriver 20.0.1133.0 /home/therookie/bin/chromedriver
[1.000][FINE]: Initializing session with capabilities {
"browserName": "chrome",
"chromeOptions": {
"args": [ ],
"extensions": [ ]
},
"javascriptEnabled": true,
"platform": "ANY",
"version": ""
}
[1.001][INFO]: Launching chrome: /usr/bin/google-chrome --disable-hang-monitor --disable-prompt-on-repost --dom-automation --full-memory-crash-report --no-default-browser-check --no-first-run --ignore-certificate-errors --homepage=about:blank
[11.796][SEVERE]: Failed to initialize connection
Answer: Chrome requires a special file called chromedriver to run. Look
[here](https://code.google.com/p/selenium/wiki/ChromeDriver) to see what
chromedriver is
` from selenium import webdriver import os chromedriver =
"PATH_TO_CHROMEDRIVER" os.environ["webdriver.chrome.driver"] = chromedriver
browser = webdriver.Chrome(executable_path=chromedriver) ` This should launch
Chrome and print done.
|
Why does pytz correctly adjust time & offset when crossing TZ & DST boundaries but not the TZ name?
Question: I have reviewed several `pytz`-related questions here, but none seems to
address the exact problem I'm seeing.
Following the [pytz documentation](http://pytz.sourceforge.net/), here's a
loop to print the current time in multiple time zones, including time zone
offset, time zone name, and whether the `datetime` object thinks it's DST.
nowDT = datetime.datetime.now()
chicagoTz = pytz.timezone('America/Chicago')
chicagoDT = chicagoTz.normalize(chicagoTz.localize(nowDT))
sys.stdout.write( "%-10s %-35s %s\n" % ('Chicago',
chicagoDT.strftime("%Y/%m/%d %H:%M:%S %Z %z"),
chicagoDT.dst()) )
tzTups = [('New York', 'America/New_York'),
('London', 'Europe/London'),
('Sydney', 'Australia/Sydney')]
for tzTup in tzTups:
tz = pytz.timezone(tzTup[1])
locDT = tz.normalize(chicagoDT.astimezone(tz))
sys.stdout.write( "%-10s %-35s %s\n" % (tzTup[0],
locDT.strftime("%Y/%m/%d %H:%M:%S %Z %z"),
locDT.dst()) )
Here's the output:
Chicago 2014/03/12 14:34:53 CDT -0500 1:00:00
New York 2014/03/12 15:34:53 EDT -0400 1:00:00
London 2014/03/12 19:34:53 GMT +0000 0:00:00
Sydney 2014/03/13 06:34:53 EST +1100 1:00:00
Checking with, say,
[timeanddate.com](http://www.timeanddate.com/worldclock/city.html?n=240), we
see that all of this information is correct, including the Sydney time,
offset, and the `1:00:00` indicating that the `datetime` object believes that
DST is currently in effect in Sydney.
The only problem is that the Sydney time is labeled `EST` instead of `EDT`. In
fact, I can't get Python to ever declare Sydney in `EDT` even though it knows
about the DST offset:
tz = pytz.timezone('Australia/Sydney')
for i in range(1,13):
locDT = tz.normalize(tz.localize(datetime.datetime(2013, i, 15)))
sys.stdout.write("%02d %s %s\n" % (i, locDT.dst(), locDT.tzname()))
Output:
01 1:00:00 EST
02 1:00:00 EST
03 1:00:00 EST
04 0:00:00 EST
05 0:00:00 EST
06 0:00:00 EST
07 0:00:00 EST
08 0:00:00 EST
09 0:00:00 EST
10 1:00:00 EST
11 1:00:00 EST
12 1:00:00 EST
Am I doing something wrong? Is `/usr/share/zoneinfo` out of date on my system?
Is this a known issue corrected in recent versions of `pytz` or the Olson DB
that I might not have? (Mine says it's using `OLSON_VERSION = '2010b'`.)
Answer: The [IANA](https://www.iana.org/) maintains the Olson database. The question
of what timezone abbreviation(s) should be used for Australia was discussed in
the IANA's tz [mailing list
here](http://mm.icann.org/pipermail/tz/2013-March/018815.html) (the discussion
spanned two months: [March
2013](http://mm.icann.org/pipermail/tz/2013-March/thread.html#18815), [April
2013](http://mm.icann.org/pipermail/tz/2013-April/thread.html#18891)).
There seems to be strong opinion on all sides as to what the abbreviations
should be and those strong opinions have resulted in gridlock.
[Some say the abbreviations are a relic of the
past](http://mm.icann.org/pipermail/tz/2013-March/018827.html) and should not
be used and the ambiguity should not be fixed to help discourage its use.
Apparently there is no recognized authority in Australia defining the
abbreviations. [Some say conflicting organizations use different timezone
abbreviations](http://mm.icann.org/pipermail/tz/2013-April/018858.html), and
so as not to pick political sides, the IANA chose EST for both standard and
daylight savings times.
For now, the Olson DB uses EST for all timezones for all dates in
Australia/Sydney:
In [60]: import pytz
In [61]: sydney = pytz.timezone('Australia/Sydney')
In [68]: [(date, tzabbrev) for date, (utcoffset, dstoffset, tzabbrev) in zip(sydney._utc_transition_times, sydney._transition_info)]
Out[68]:
[(datetime.datetime(1, 1, 1, 0, 0), 'EST'),
(datetime.datetime(1916, 12, 31, 14, 1), 'EST'),
(datetime.datetime(1917, 3, 24, 15, 0), 'EST'),
(datetime.datetime(1941, 12, 31, 16, 0), 'EST'),
(datetime.datetime(1942, 3, 28, 15, 0), 'EST'),
(datetime.datetime(1942, 9, 26, 16, 0), 'EST'),
(datetime.datetime(1943, 3, 27, 15, 0), 'EST'),
...]
In [69]: set([tzabbrev for utcoffset, dstoffset, tzabbrev in sydney._transition_info])
Out[69]: {'EST'}
This shows that in the Australia/Sydney timezone, EST is used across every
transition boundary.
|
Searching a List of Objects for those Objects with a Particular Member Variable set to a Value?
Question:
import string
import random
class Foo(object):
def __init__(self, bar):
self.bar = bar
foos = []
for i in range(1,101):
f = foo(random.choice(string.letters))
foos.append(f)
fs == find_object_in_list_by_attribute(bar='b')
Is there a method like `find_object_in_list_by_attribute` in python to
accomplish this?
Answer: Just use the `[, if <filter>]` grammar of list comprehensions to give you the
foos with `bar == 'b'`:
fs = [foo for foo in foos if foo.bar == 'b']
sidenotes: classes should start with capital letters (like ruby, but just
_strongly recommended_ instead of compulsory) and range objects are written as
`for i in range(100):`.
In the event that you just want the _first_ foo (which may or may not be the
only foo), you can do:
fs = next(foo for foo in foos if foo.bar == 'b')
This will notably raise a `StopIteration` exception if `'b'` is not found
anywhere in your `foos` collection, so you can give `next` a "fallback" value
to avoid that:
fs = next((foo for foo in foos if foo.bar == 'b'), None)
|
Inspect code of next line in Python
Question:
# script.py
greeting = "hi"
import inspect; import traceback; print traceback.format_stack(inspect.currentframe())[-1]
print greeting
The code on the fourth line of the script prints out the file name, line
number and the current line:
$ python script.py
File "script.py", line 4, in <module>
import inspect; import traceback; print traceback.format_stack(inspect.currentframe())[-1]
hi
But how can I print out the line number and the content for the next
line(`print greeting`) instead of the current one?
This would be convenient for debugging, a oneliner to show the code of the
line beneath it.
## Edit
Via Ben's answer I got to this hideous creature:
import inspect; import sys; _lne = inspect.currentframe().f_lineno; print "{0}, line {1}:".format(__file__, _lne+1); print open(sys.argv[0]).readlines()[_lne].strip()
It's 166 chars long, very verbose. Beware that it raises an `IndexError` when
the there is no next line.
Running `python script.py` would print out the following
script.py, line 5:
print greeting
hi
I'm hoping some minor change in the original line I posted could lead to the
desired behavior, because that included the file name and number without the
need of explicitly printing these. And the indentation it provided wasn't
unwelcome either.
Answer: Add a little helper function to lookup and print the relevant filename and
line:
import inspect, linecache
def show_next(cf):
'Show the line following the active line in a stackframe'
filename = cf.f_code.co_filename
line = cf.f_lineno
print linecache.getline(filename, line+1)
greeting = "hi"
show_next(inspect.currentframe())
print greeting
Of course, if need, it can go into one-line:
greeting = "hi"
import inspect, linecache; _f=inspect.currentframe(); print linecache.getline(_f.f_code.co_filename, _f.f_lineno+1)
print greeting
|
How do you share a variable between two processes in Python?
Question: I have two processes, one adds jobs to a queue and the other takes them off
the same queue and runs them. This should work as expected and I'm not sure
why the `worker` never gets any jobs. Here's my code:
from multiprocessing import Process
from Queue import Queue
import time
q = Queue()
def queuer():
while True:
q.put("JOB")
print "Adding JOB"
time.sleep(1)
def worker():
while True:
if not q.empty():
item = q.get()
print "Running", item
else:
print "No jobs"
time.sleep(1)
a = Process(target=queuer)
a.start()
b = Process(target=worker)
b.start()
Answer: Two things:
1. You need to pass the Queue as an argument to both processes.
2. You should use multiprocessing.Queue, not Queue.Queue (which are for Threads)
This code works for me:
from multiprocessing import Process, Queue
import time
def queuer(q):
while True:
q.put("JOB")
print "Adding JOB"
time.sleep(1)
def worker(q):
while True:
if not q.empty():
item = q.get()
print "Running", item
else:
print "No jobs"
time.sleep(1)
if __name__ == '__main__':
q = Queue()
a = Process(target=queuer, args=(q,))
b = Process(target=worker, args=(q,))
a.start()
b.start()
|
How can I convert a XLSB file to csv using python?
Question: I have been provided with a xlsb file full of data. I want to process the data
using python. I can convert it to csv using excel or open office, but I would
like the whole process to be more automated. Any ideas?
**Update:** I took a look at this
[question](https://stackoverflow.com/questions/1858195/convert-xls-to-csv-on-
command-line "question") and used the first answer:
import subprocess
subprocess.call("cscript XlsToCsv.vbs data.xlsb data.csv", shell=False)
The issue is the file contains greek letters so the encoding is not preserved.
Opening the csv with Notepad++ it looks as it should, but when I try to insert
into a database comes like this ���. Opening the file as csv, just to read
text is displayed like this: \xc2\xc5\xcb instead of ΒΕΛ.
I realize it's an issue in encoding, but it's possible to retain the original
encoding converting the xlsb file to csv ?
Answer: Most popular Excel python packages
[openpyxl](https://bitbucket.org/ericgazoni/openpyxl) and
[xlrd](https://github.com/python-excel/xlrd/) have no support for `xlsb`
format (bug tracker entries: [openpyxl](https://github.com/python-
excel/xlrd/issues/83), [xlrd](https://github.com/python-
excel/xlrd/issues/83)).
So I'm afraid there is no native python way =/. However, since you are using
windows, it should be easy to script the task with external tools.
I would suggest taking look at [Convert XLS to XLSB
Programatically?](http://stackoverflow.com/questions/6442698/convert-xls-to-
xlsb-programatically). You mention python in title but the matter of the
question does not imply you are strongly coupled to it, so you could go pure
c# way.
If you feel really comfortable only with python one of the answers there
suggests a command line tool under a fancy name of [Convert-
XLSB](http://www.softinterface.com/Convert-XLS/Features/Convert-XLSB.htm). You
could script it as an external tool from python with
[`subprocess`](https://docs.python.org/2/library/subprocess.html).
I know this is not a good answer, but I don't think there is better/easier way
as of now.
|
Running Selenium Webdriver headlessly using Cron
Question: I am trying to execute my Selenium Scripts through cron headlessly using Xvfb.
The code of shell script looks something like this
export PATH=$PATH
Xvfb :10 -ac &
gnome-terminal -e export DISPLAY=:10 &
gnome-terminal -e firefox &
gnome-terminal -e export DISPLAY=:10 &
gnome-terminal -e firefox &
cd wait/test/
sh deploy.sh
But I am getting an eror something like this :
Failed to parse arguments: Cannot open display:
Failed to parse arguments: Cannot open display:
Failed to parse arguments: Cannot open display:
Failed to parse arguments: Cannot open display:
[dix] Could not init font path element /usr/share/fonts/X11/cyrillic, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/100dpi/:unscaled, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/75dpi/:unscaled, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/100dpi, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/75dpi, removing from list!
[dix] Could not init font path element /var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType, removing from list!
Traceback (most recent call last):
File "runner.py", line 7, in <module>
from test import root
File "/home/user/Tests/redirect/wait/test/ScrapyCrawl/test.py", line 47, in <module>
class root (unittest.TestCase):
File "/home/user/Tests/redirect/wait/test/ScrapyCrawl/test.py", line 49, in root
driver = webdriver.Firefox ()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 59, in __init__
self.binary, timeout),
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 47, in __init__
self.binary.launch_browser(self.profile)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 61, in launch_browser
self._wait_until_connectable()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 100, in _wait_until_connectable
self._get_firefox_output())
selenium.common.exceptions.WebDriverException: Message: 'The browser appears to have exited before we could connect. The output was: Error: no display specified\n'
Any help would be appreciated. Thanks.
Answer: I used `pyvirtualdisplay` to solve this problem. It is a a Python wrapper for
Xvfb and Xephyr. More info can be found here :
[pyvirtualdisplay](http://coreygoldberg.blogspot.in/2011/06/python-headless-
selenium-webdriver.html)
|
How do I improve my code for Think Python, Exercise 7.4 eval and loop
Question: The task:
> Write a function called `eval_loop` that iteratively prompts the user, takes
> the resulting input and evaluates it using `eval()`, and prints the result.
>
> It should continue until the user enters `'done'`, and then return the value
> of the last expression it evaluated.
My code:
import math
def eval_loop(m,n,i):
n = raw_input('I am the calculator and please type: ')
m = raw_input('enter done if you would like to quit! ')
i = 0
while (m!='done' and i>=0):
print eval(n)
eval_loop(m,n,i)
i += 1
break;
eval_loop('','1+2',0)
My code cannot return the value of the last expression it evaluated!
Answer: Three comments:
1. Using recursion for this means that you will eventually hit the system recursion limit, iteration is probably a better approach (and the one you were asked to take!);
2. If you want to `return` the result of `eval`, you will need to assign it; and
3. I have no idea what `i` is for in your code, but it doesn't seem to be helping anything.
With those in mind, a brief outline:
def eval_loop():
result = None
while True:
ui = raw_input("Enter a command (or 'done' to quit): ")
if ui.lower() == "done":
break
result = eval(ui)
print result
return result
For a more robust function, consider wrapping `eval` in a `try` and dealing
with any errors stemming from it sensibly.
|
Create pixel square and present later
Question: I’ve started working with Python and SDL2 a short time ago to program my
psychological experiments. My question, therefore, is probably very basic. I
would like to create a square filled with random pixels of two different
colors and show it in the middle of the screen. I’ve managed to create this
pixel square and show it but it takes up to one second to create it. Thus, I
would like to create the pixel square earlier, that is in a moment in which
the participant is occupied with something else, and later show it. I thought
about using SDL_CreateRenderer(window, -1, 0) twice but I was not able to do
it. Is there a very easy way to solve my problem? Maybe it’s possible to save
the created pixel square to a file and then load it later on? That’s how I
create my pixel square:
def put_pixel(x,y, color):
pixel = SDL_Rect(x, y,1,1)
if color == "orange":
SDL_SetRenderDrawColor(sdlRenderer,255,100,0,255)
elif color == "blue":
SDL_SetRenderDrawColor(sdlRenderer,0,100,255,255)
SDL_RenderFillRect(sdlRenderer,pixel)
return sdlRenderer
def pixel_square(n_pixel_x,n_pixel_y, n_pixel_blue):
seq = range(n_pixel_x*n_pixel_y)
random.shuffle(seq)
lst = range(n_pixel_x*n_pixel_y)
pos=0
for i in range(n_pixel_x):
for j in range(n_pixel_y):
lst[seq[pos]] = [i,j]
pos = pos+1
#create orange square
square_orange=SDL_Rect(MAXX/2-n_pixel_x/2,MAXY/2-n_pixel_y/2,n_pixel_x,n_pixel_y)
SDL_SetRenderDrawColor(sdlRenderer,255,100,0,255) #orange
SDL_RenderFillRect(sdlRenderer,square_orange)
#add blue pixels
for i in range(n_pixel_blue):
put_pixel(x=MAXX/2-n_pixel_x/2+lst[i][0], y=MAXY/2-n_pixel_y/2+lst[i][1], color="blue")
return sdlRenderer
Later on I use
SDL_RenderPresent(sdlRenderer)
to show the pixel square.
I’d be very happy if you could help me with that problem!! Thank you! Vero
Answer: Your procedure to create images is slow due to the overhead of calculations
and loops to process. Aside from optimizing them here and there and
precomputing, storing and loading images from elsewhere, I'd recommend to use
[Numpy](http://www.numpy.org/%20%22Numpy) to generate the image on the fly, if
applicable. It features random distribution arrays out of the box and is
heavily optimized for speed.
A fully working example could look like:
import sys
import sdl2
import sdl2.ext
import numpy
SIZE_X = 400
SIZE_Y = 300
# RGB values
RED = 0xFF0000
GREEN = 0x00FF00
def pixelate():
choices = [RED, GREEN]
pixelarray = numpy.random.choice(choices,(SIZE_X, SIZE_Y))
buf = pixelarray.tostring()
# Create a software surface from the array. The depth and pitch are really
# important here, since we use a continuous byte buffer access.
image = sdl2.SDL_CreateRGBSurfaceFrom(buf,
SIZE_X, SIZE_Y,
32, # Bit depth, we use 32-bit RGB
SIZE_X, # pitch (byte size of a single scanline) - for 32 bit it is SIZE_X
0xFF0000,
0x00FF00,
0x0000FF,
0x0)
# required to avoid loosing buf. SDL_CreateRGBSurfaceFrom() will
# reference the byte buffer, not copy it
image._buffer = buf
return image
def main():
sdl2.ext.init()
window = sdl2.ext.Window("Pixel example", size=(800, 600))
imgoffset = sdl2.SDL_Rect(200, 150, 0, 0)
window.show()
# Software rendering, we also could use hardware rending and use streaming
# textures, but the example would become more complicated then.
windowsurface = window.get_surface()
running = True
while running:
events = sdl2.ext.get_events()
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
break
if event.type == sdl2.SDL_MOUSEBUTTONDOWN:
image = pixelate()
sdl2.SDL_BlitSurface(image, None, windowsurface, imgoffset)
window.refresh()
sdl2.SDL_Delay(10)
sdl2.ext.quit()
return 0
if __name__ == "__main__":
sys.exit(main())
The most important part is the _pixelate()_ function, which creates a 2D array
of specified size filled with a random distribution of the passed values (your
colors). SDL2 allows you to create surfaces (images) from a byte buffer, so
the next step is to create a buffer from the 2D numpy array and create a
surface using that specific buffer. Once done with that it is a simple matter
of showing the image on the screen.
If [Numpy](http://www.numpy.org/%20%22Numpy) can't be used in your
environment, I would avoid to draw each pixel individually using your
_put_pixel()_ method, since this will cause at least one context switch on
each color change in the SDL2 renderer (worst case). Instead, precompute a 2D
array, fill it with the necessary values and create a software surface buffer
(or again, a streaming texture) based on it, which you then blit on the screen
in a single operation.
|
extracting tuples based on values in python
Question: I have a list of tuples with following format ("key","value"), I need to
extract keys with highest & second highest values & store them, how do I
achieve this in python ?
Answer: Use
[`heaq.nlargest`](http://docs.python.org/2/library/heapq.html#heapq.nlargest):
import heapq
heapq.nlargest(2, list_of_t, key=lambda x:x[1])
**Demo:**
>>> import heapq
>>> list_of_t = [('a', 100), ('b', 5), ('c', 50)]
>>> heapq.nlargest(2, list_of_t, key=lambda x:x[1])
[('a', 100), ('c', 50)]
|
/etc/aliases using pipe to run script return error (mailer=prog, dsn=5.3.0, stat=unknown mailer error 2)
Question: I would like to get any advice for my issue to run script on /etc/aliases. At
first, here are my envirements/script.
* OS : centos 6
* script : python 2.6.6
* mail : sendmail-8.14 / dovecot-2x
* python script (it's very simple for testing)
> import sys
>
> f = open("aa.txt", 'w')
>
> for i in range(1, 5): data = "%d \n" % i f.write(data)
>
> f.close() sys.exit()
and then I did some congiguration to use smrsh like, make link on /etc/smrsh/,
move script on /etc/smrsh/...
and then modified the /etc/aliases as below:
testuser: "|/etc/smrsh/python /etc/smrsh/aa.py"
and then run `newaliases`.
When I send email to testuser user, maillog shows error as below: (sorry for
changing some info like IP, domain)
Mar 13 11:14:38 localhost sendmail[8153]: s2DBEcX7008153: from=<ttt@test.com>, size=4448, class=0, nrcpts=1, msgid=<B75C8C1216C9824DBF46410575577E294559AC17@test.com>, proto=ESMTP, daemon=MTA, relay=relay.test.com [xx.xxx.000.xx]
Mar 13 11:14:39 localhost sendmail[8154]: s2DBEcX7008153: to="|/etc/smrsh/python /etc/smrsh/aa.py", ctladdr=<testuser@[xx.xx.xx.xx]> (8/0), delay=00:00:01, xdelay=00:00:01, mailer=prog, pri=34652, dsn=5.3.0, stat=unknown mailer error 1
Mar 13 11:14:39 localhost sendmail[8154]: s2DBEcX7008153: s2DBEdX7008154: DSN: unknown mailer error 1
but, just forwarding email via /etc/aliases works very well like, testuser :
test@zzz.com
I tried to run with smrsh on the shell :
> > smrsh -c "|/etc/smrsh/python /etc/smrsh/aa.py"
it also works very well.
here are my sendmail.cf for Mprog,
Mlocal, P=/usr/bin/procmail, F=lsDFMAw5:/|@qSPfhn9, S=EnvFromL/HdrFromL, R=EnvToL/HdrToL,
T=DNS/RFC822/X-Unix,
A=procmail -t -Y -a $h -d $u
Mprog, P=/usr/sbin/smrsh, F=lsDFMoqeu9, S=EnvFromL/HdrFromL, R=EnvToL/HdrToL, D=$z:/,
T=X-Unix/X-Unix/X-Unix,
A=smrsh -c $u
and, /etc/smrsh/
lrwxrwxrwx. 1 root root 17 Mar 13 09:01 procmail -> /usr/bin/procmail
lrwxrwxrwx. 1 root root 15 Mar 13 09:08 python -> /usr/bin/python
lrwxrwxrwx. 1 root root 15 Mar 13 09:42 smrsh -> /usr/sbin/smrsh
lrwxrwxrwx. 1 root root 17 Feb 13 09:17 vacation -> /usr/bin/vacation
-rwxr-xr-x. 1 root root 125 Mar 13 11:27 aa.py
-rw-r--r--. 1 root root 12 Mar 13 11:27 aa.txt
Could someone help to slove this problem? Many Thanks!
Answer: # [Sendmail FAQ 4.13 : What does "unknown mailer error 1"
mean?](http://www.sendmail.com/sm/open_source/support/support_faq/general_issues_faq/#4.13)
Sendmail expects exit code zero (0) to signal all "OK" **OR** exit codes from
64 to 78 to signal specific problems. In your case is not on the list of exit
codes sendmail can interpret.
Valid exit codes to signal errors/problems are listed in
[`sysexits.h`](https://www.freebsd.org/cgi/man.cgi?query=sysexits&apropos=0&sektion=0&manpath=FreeBSD%204.3-RELEASE&format=html)
#define EX_USAGE 64 /* command line usage error */
#define EX_DATAERR 65 /* data format error */
#define EX_NOINPUT 66 /* cannot open input */
#define EX_NOUSER 67 /* addressee unknown */
#define EX_NOHOST 68 /* host name unknown */
#define EX_UNAVAILABLE 69 /* service unavailable */
#define EX_SOFTWARE 70 /* internal software error */
#define EX_OSERR 71 /* system error (e.g., can't fork) */
#define EX_OSFILE 72 /* critical OS file missing */
#define EX_CANTCREAT 73 /* can't create (user) output file */
#define EX_IOERR 74 /* input/output error */
#define EX_TEMPFAIL 75 /* temp failure; user is invited to retry */
#define EX_PROTOCOL 76 /* remote error in protocol */
#define EX_NOPERM 77 /* permission denied */
#define EX_CONFIG 78 /* configuration error */
|
python getting syntax error in except
Question: I am new to python and just been playing with the database API. I am getting
an invalid syntax error in the exception except block comma. I can't figure
out any syntax mistakes. Below is the code I am using
import time
import MySQLdb
import sys
import urllib2
#f = open("../", 'r')
try:
db = MySQLdb.connect(host="localhost", user="test", passwd="test",db="test")
cur = db.cursor()
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
finally:
cur.close()
db.close()
#f.write('amal')
#f.close()
Answer: Your syntax is correct _for Python 2_ , which would be the correct version
given the fact that you tried to import `urllib2` here.
For recent Python versions the `except` syntax was updated, and the old syntax
no longer works in Python 3. The correct syntax would be:
except MySQLdb.Error as e:
but you'll need to fix what Python version you are running this with _or_ use
the correct libraries for Python 3. That means using `urllib.request` and
installing `MySQLdb` for your Python 3 installation first.
|
Python's support for hexadecimal escapes in the replacement text
Question: Could not found a corresponding PEP or a bug for one problem in Python's `re`
module.
Does anyone know if the following is planned to be fixed?
From [regular-expressions.info](http://www.regular-
expressions.info/replacenonprint.html):
> Python does not support hexadecimal escapes in the replacement text syntax,
> even though it supports \xFF and \uFFFF in string constants.
But it actually supports standard escapes like `\n`, `\r`, etc.
So, for example one cannot replace `'<'` character with `'>'` character using
hexadecimal escapes:
>>> import re
>>> re.sub(r'\x3c', r'\x3e', '\x3c')
'\\x3e'
Instead of `'\\x3e'` it should be `'>'`.
Using escaped `\n` works fine:
>>> re.sub(r'a', r'\n', 'a')
'\n'
Thanks in advance!
**UPD:** Not using the raw string is not an option. For example if pattern and
replacement strings are stored in a config file, so if I write \x3e in it, it
will become `'\\x3e'` when read, instead of `'>'`.
Answer: The only workaround I know if is to not use a raw string for the replacement
text and instead allow normal string evaluation to make `\x3e` into `>`. This
works because, as you noted, python strings do support such sequences.
>>> import re
>>> re.sub(r'\x3c', '\x3e', '\x3c')
'>'
This means that in more complex replacement text you need more escapes, which
could make it less readable, but at least it works.
I don't know if there is any plan to improve on this. I took a look at the
existing documentation for the [python 3.4 re
module](http://docs.python.org/3.4/library/re.html#re.sub) (under dev) and
found no mention of including this kind of support.
However, if you have a need for more complex logic on the replacement, you can
pass a function instead of replacement text for the `repl` argument of
`re.sub`.
|
python - using Selenium logging in
Question: I followed the accepted answer's solution at: [How to use Selenium with
Python?](http://stackoverflow.com/questions/17540971/how-to-use-selenium-with-
python)
I am trying to log into coinbase <https://coinbase.com/signin>
Here is my code
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
site = "https://coinbase.com/signin"
email = "myemail@mymail.com"
password = "mypassword"
xpaths = {
'emailTxtBox' : '/html/body/div[2]/div[2]/div[2]/div/div/form/div[2]/div/input',
'passwordTxtBox' : '/html/body/div[2]/div[2]/div[2]/div/div/form/div[3]/div/input',
'submitButton' : '/html/body/div[2]/div[2]/div[2]/div/div/form/div[4]/div/input'
}
browser = webdriver.Firefox()
browser.get(site)
#Write Username in Username TextBox
mydriver.find_element_by_xpath(xpaths['emailTxtBox']).send_keys(email)
#Write Password in password TextBox
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)
#Click Login button
mydriver.find_element_by_xpath(xpaths['submitButton']).click()
I run this, and selenium opens coinbase, then refreshes after a couple
seconds, then nothing happens.
Answer: You are specifying:
xpaths['usernameTxtBox']
but it doesn't exist according to your array:
xpaths = {
'usernameTxtBox' # needs to be in the array
'emailTxtBox' : '/html/body/div[2]/div[2]/div[2]/div/div/form/div[2]/div/input',
'passwordTxtBox' : '/html/body/div[2]/div[2]/div[2]/div/div/form/div[3]/div/input',
'submitButton' : '/html/body/div[2]/div[2]/div[2]/div/div/form/div[4]/div/input'
}
**Edit after comment:** I'd consider either revising your xpath, or Keeping It
Simple, (Stupid).
//input[@id='email']
//input[@id='password']
//input[@id='signin_button']
|
Parsing Tex using python re library
Question: I want to parse the following part of a .tex file
\section{a}
some random lines with lot
of special characters
\subsection{aa}
somehthing here too
\section{b}
I want the content within `\section{a}` and `\section{b}` inclusive so i tried
the following code in python
import re
a="my tex string mentioned above"
b=re.findall(r'\\section{a}.*\\section{b}',a)
print(b)
but i got `b=[]`. Where I am wrong?
Answer: You need to use the re.DOTALL flag to make the . match newlines, like this:
b=re.findall(r'\\section{a}.*\\section{b}',a,re.DOTALL)
|
TypeError: open() takes 0 positional arguments but 2 were given
Question: Here is the code:
def save():
f = open('table.html', 'w')
f.write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>\n")
f.write("<html xmlns='http://www.w3.org/1999/xhtml'>\n")
f.write("<head profile='http://gmpg.org/xfn/11'>\n")
f.write('<title>Table</title>')
f.write("<style type='text/css'>")
f.write('body {margin-left:0;margin-right:0;font:normal normal 800 18px Arial;}')
f.write('a{ text-decoration: }')
f.write(':link { color: rgb(0, 0, 255) }')
f.write(':visited {color :rgb(100, 0,100) }')
f.write(':hover { }')
f.write(':active { }')
f.write('table{position: relative; empty-cells: show;border: 1px solid black; border-collapse: collapse}')
f.write('td{position: relative; border: 1px solid black; text-align: left; padding: 0px 5px 0px 1px}')
f.write('.tr1{background: #EEFFF9}')
f.write('.tr2{background: #FFFEEE}')
f.write('</style>')
f.write('</head>')
f.write('<body>')
f.write('<center>2012 La Jolla Half Marathon</center><br />')
f.write('<table>')
f.close()
I get this exception:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Python33\GUICreator1.py", line 11, in save
f = open('table.html', 'w')
TypeError: open() takes 0 positional arguments but 2 were given
I know open takes 2 arguments. Also, if I run the same code not within the
function it runs properly with no error.
Answer: You have, elsewhere in your module, a function named `open()` (defined or
imported) that masks the built-in. Rename it.
As for your `save()` function, you should really use multi-line string, using
triple-quoting, to save yourself so many `f.write()` calls:
def save():
with open('table.html', 'w') as f:
f.write("""\
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>\n
<html xmlns='http://www.w3.org/1999/xhtml'>\n
<head profile='http://gmpg.org/xfn/11'>\n
<title>Table</title>
<style type='text/css'>
body {margin-left:0;margin-right:0;font:normal normal 800 18px Arial;}
a{ text-decoration: }
:link { color: rgb(0, 0, 255) }
:visited {color :rgb(100, 0,100) }
:hover { }
:active { }
table{position: relative; empty-cells: show;border: 1px solid black; border-collapse: collapse}
td{position: relative; border: 1px solid black; text-align: left; padding: 0px 5px 0px 1px}
.tr1{background: #EEFFF9}
.tr2{background: #FFFEEE}
</style>
</head>
<body>
<center>2012 La Jolla Half Marathon</center><br />
<table>""")
This also uses the open file object as a context manager, which means Python
will close it for you automacally.
|
Python Files, adding values to/from a list
Question: I am trying to add a value to a list from a file, and then be able to add the
values from the file to the list. This is what I have:
L = []
def readFile(L):
ui = input("Please enter your file name:")
r = open(ui, 'r')
files = r.readlines()
for line in files:
return float(line)
L.append(line)
r.close()
def fileAddValue(L):
ui = input("Please enter your file name:")
val = float(input("Enter the value you would like to add to the list: "))
r = open(ui, 'a')
file = r.write(str(val) + '\n')
for ix in r:
x = float(ix)
L.append(x)
L.sort()
r.close()
Answer: Do you need something like that?
L = []
def readFile():
ui = input("Please enter your file name:")
r = open(ui, 'r')
files = r.readlines()
for line in files:
value = float(line)
L.append(value)
r.close()
def fileAddValue():
ui = input("Please enter your file name:")
val = float(input("Enter the value you would like to add to the list: "))
r = open(ui, 'a+')
r.write(str(val) + '\n')
for ix in r:
x = float(ix)
L.append(x)
L.append(val)
L.sort()
r.close()
if __name__ == '__main__':
readFile()
fileAddValue()
print(L)
While it's non-pytonic (tried to not touch your code unless necessary), it
works if I got your question right. Indenting code is important in Python and
returning from a function guarantees that code after return will never run. If
you want a function that "returns" several values so you can iterate over that
"function" with `for`, use `yield` instead of `return`.
|
Python 3.x dynamically group elements in 2d list by common elements in list
Question:
[('20bgx6', 'HQ', 'Head Quarters'),
('2040bl', 'NVA', 'North Vietnamese Army '),
('2040bl', 'HEAT', 'High Explosive Anti Tank '),
('2040bl', 'HEAT', 'High Explosive Anti Tank '),
('202kon', 'HEAT', 'High Explosive Anti Tank '),
('202kon', 'EFP', 'Explosively Formed Penetrator/Projectile'),
('202kon', 'NCO', 'Non-commissioned officer'),
('202kon', 'MRAP', 'Mine Resistant Ambush Protected'),
('202kon', 'UXO', 'Unexploded Ordnance'),
('202kon', 'MP', 'Military Police'),
('202kon', 'CQ', 'Charge of Quarters'),
('202kon', 'HQ', 'Head Quarters'),
('202kon', 'NCO', 'Non-commissioned officer'),
('1zz081', 'BC', 'Battalion Commander'),
('1zz081', 'HMMWV', 'High Mobility Multi Wheeled Vehicle'),
('1zz081', 'SALUTE', 'Size Activity Location Uniform Time Equipment '),
('1zxpbs', 'NCO', 'Non-commissioned officer'),
('1ztrv6', 'SALUTE', 'Size Activity Location Uniform Time Equipment '),
('1ztrv6', 'HEAT', 'High Explosive Anti Tank '),
('1ztrv6', 'BDU', 'Battle Dress Uniform, predecessor to the ACU'),
('1zs9gz', 'AG', 'Adjutant General'),
('1zs9gz', 'HEAT', 'High Explosive Anti Tank ')]
I will have a list that is equal to that, and I need to group then such that
there is groups of elements who all start with the same ID tag (2040bl,
202kon, etc) will be in their own sublist.
So the sub lists starting with '2040bl' will end up in their own group, all
within the same list. The resulting list will have a resulting length of 7, as
there is 7 unique ID tags (first element in each sublist)
I'm on python 3
Answer: You can use
[`itertools.groupby`](http://docs.python.org/3/library/itertools.html?highlight=groupby#itertools.groupby)
method. With your data it seems it will work out of the box. For example:
from itertools import groupby
for k, v in groupby(l, key=lambda t: t[0]) # assuming your list is stored in l
print('%s\n\t%s' % (k, list(v)))
Will output:
20bgx6
[('20bgx6', 'HQ', 'Head Quarters')]
2040bl
[('2040bl', 'NVA', 'North Vietnamese Army '), ('2040bl', 'HEAT', 'High Explosive Anti Tank '), ('2040bl', 'HEAT', 'High Explosive Anti Tank ')]
202kon
[('202kon', 'HEAT', 'High Explosive Anti Tank '), ('202kon', 'EFP', 'Explosively Formed Penetrator/Projectile'), ('202kon', 'NCO', 'Non-commissioned officer'), ('202kon', '
MRAP', 'Mine Resistant Ambush Protected'), ('202kon', 'UXO', 'Unexploded Ordnance'), ('202kon', 'MP', 'Military Police'), ('202kon', 'CQ', 'Charge of Quarters'), ('202kon', 'HQ', '
Head Quarters'), ('202kon', 'NCO', 'Non-commissioned officer')]
1zz081
[('1zz081', 'BC', 'Battalion Commander'), ('1zz081', 'HMMWV', 'High Mobility Multi Wheeled Vehicle'), ('1zz081', 'SALUTE', 'Size Activity Location Uniform Time Equipment ')
]
1zxpbs
[('1zxpbs', 'NCO', 'Non-commissioned officer')]
1ztrv6
[('1ztrv6', 'SALUTE', 'Size Activity Location Uniform Time Equipment '), ('1ztrv6', 'HEAT', 'High Explosive Anti Tank '), ('1ztrv6', 'BDU', 'Battle Dress Uniform, predecess
or to the ACU')]
1zs9gz
[('1zs9gz', 'AG', 'Adjutant General'), ('1zs9gz', 'HEAT', 'High Explosive Anti Tank ')]
Important: When using `groupby` the data needs to be sorted by the group key,
which in your example they are. Otherwise you can add a `sorted(l, key=lambda
t:t[0])` before grouping.
|
Python Terminal GUI - like functionalities
Question: How can I make a console GUI of sorts?
It's important to note that I will be changing the text in some of the spots,
and this is why I can't have it just print to the screen. It would be fine to
use other modules, but I'd prefer not to have to. Here's an ASCII mockup of
what it would look like:
********************************************
* *
* *
* *
* There are 8 seconds left. *
* *
* *
* *
* The script has run 8 times *
* *
* *
* *
* *
********************************************
I would need to be able to update the timer and the number of iterations
dynamically.
I know how to write over the last printed line using the carriage return. But
I can't use that on both lined.
How can I achieve this?
Thanks!
evamvid
Answer: Try using the [curses](http://docs.python.org/2/library/curses.html) module.
Here's [an introduction](http://docs.python.org/2/howto/curses.html).
|
Python: Remove elements from the list which are prefix of other
Question: Fastest (& python) way to get list of elements which do not contain any other
elements as their prefix.
(Elements can be in any order, for the sake of clarity in explanation elements
are kept kind of sequential here, so if needed sorting has to be done
explicitly)
Input is
['AB', 'ABC', 'ABCDEF', 'ABCDEFG', 'BCD', 'DEF', 'DEFGHI', 'EF', 'GKL', 'JKLM']
Elements eliminated:
'AB' prefix of 'ABC'
'ABC' prefix of 'ABCDEF'
'ABCDEF' prefix OF 'ABCDEFG'
'DEF' prefix of 'DEFGHI'
Expected Output
['ABCDEFG', 'BCD', 'DEFGHI', 'EF', 'GKL', 'JKLM']
**Edited** :
Adding a bit more complexity(or clarity). The average length of the list
varies from 500 - 900.
Answer: List comprehension (`ls` is the name of your input list):
[x for x in ls if x not in [y[:len(x)] for y in ls if y != x]]
I doubt it is the quickest in terms of performance, but the idea is very
straightforward. You are going through the list element by element and
checking if it is the prefix of any element in a list of all the rest of
elements.
timeit result: 11.9 us per loop (though the scaling is more important if you
are going to use it for large lists)
|
Python Bottle - Inline IF statements in Template
Question:
Make = <SELECT name="where_make">
% for make in makes:
<OPTION value="{{make}}"
% if make == defaults['make']:
selected="selected"
% end
>{{make}}</option>
%end
How can I do this if statement on a single line?
Answer: Bottle's built-in template engine supports [inline if
statements](http://bottlepy.org/docs/dev/stpl.html#inline-expressions):
<option value="{{make}}" {{!'selected="selected"' if make == defaults['make'] else ""}}>{{make}}</option>
Note the exclamation mark before the `selected="selected"` \- it tells the
template engine not to escape quotes.
Demo:
from bottle import SimpleTemplate
tpl = SimpleTemplate("""Make = <SELECT name="where_make">
% for make in makes:
<option value="{{make}}" {{!'selected="selected"' if make == defaults['make'] else ""}}>{{make}}</option>
%end""")
print tpl.render(make='test', defaults={'make': 'test'}, makes=['test'])
prints:
Make = <SELECT name="where_make">
<option value="test" selected="selected">test</option>
Hope that helps.
|
Supporting the "with open" syntax without using contextlib.closing()
Question: I really like the syntax "with open('in_file'') as f". I want to use that
syntax for my own resources which must be opened and closed.
However, I do not understand how to change my open() method to enable the
'with' syntax. I can (and do) use the contextlib.closing() approach but it
becomes a bit bulky after repeated use.
So, I will ask my question below in relation to shelve.open(). I am not
proposing a change to the shelve module but instead am using it because the
source code is readily available to all of you.
There is nothing special about shelve.open() vs. other standard library
resources that require closing: socket.socket(), sqlite3.connect(),
urllib2.urlopen(), etc.
import contextlib, inspect, shelve, sys
#print(inspect.getsource(open)) # can not see how it was done here :-(
print('-' * 40)
# Given that we can view the source for the shelve module:
print(inspect.getsource(shelve))
print('-' * 40)
# Given that we can view the docs for the shelve module:
print(shelve.__doc__)
#print('-' * 40)
# Given that the desired syntax is Pythonic but is not supported:
#with shelve.open('test_shelve') as my_shelve:
# my_shelve['fact_number_1'] = "There's a dead fish on the landing."
# Given that the required syntax is convoluted and
# takes programmer attention away from the task at hand:
with contextlib.closing(shelve.open('test_shelve')) as my_shelve:
my_shelve['fact_number_2'] = "There's another dead fish on the landing."
# Q: What changes would need to made to shelve.open() to allow the
# 'with shelve.open(x) as y' syntax?
I am not really interested in an extra wrapper with a different name. Using
contextlib.closing() is easier, safer, and more intuitive than that. What I am
really interested in is creating a single open() method that can be called
either with or without 'with'.
So, to successfully answer this question, you need to take the source code for
the shelve module and show what changes would need to be made to shelve.open()
to have a single method that can be used either with or without 'with' (like
the builtin open() or the Python3 urllib.urlopen()).
Answer: The biggest problem here is that if you do
shelf = the_function_you_want()
the function you want has to return the shelf, but if you do
with the_function_you_want() as shelf:
the function you want has to return a context manager. That means you need to
return a shelf that is also a context manager, which in turn means you either
need to make a shelf subclass or monkey-patch `Shelf`. It's probably better to
make a subclass:
class ContextManagerShelf(shelve.DbfilenameShelf):
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.close()
Then you can use `ContextManagerShelf` as a context manager or not. The
signature is the same as `shelve.open`. If you want, you can also make an
`open` function to go with it.
|
Python circular import, `from lib import module` vs `import lib.module`
Question: I have two python modules, `a.py` and `b.py`, both of which are in `lib/`
relative to the current directory. Suppose each module needs the functionality
of the other.
**a.py:**
import lib.b
...
**b.py:**
import lib.a
...
The above example works with
PYTHONPATH=./lib python -c 'from lib import a, b'
However, if I switch the imports in `a.py` and `b.py` to `from lib import b`
and `from lib import a`, respectively, the above Python command terminates
with `ImportError`.
Could someone please explain why this breaks? I'm not trying to import any
member from either `a` or `b`. (In that case I would be importing from an
uninitialized module, as the question referenced below points out.)
### Reference:
1. [python circular imports once again (aka what's wrong with this design)](http://stackoverflow.com/questions/3955790/python-circular-imports-once-again-aka-whats-wrong-with-this-design)
Answer: in your lib folder there is a __init__.py file? If yes you have 2 possibility:
1) __init__.py is empty and you can use from lib import a,b
a.foo b.bar
2) in your __init__.py there are istructions import a,b in this case you can
write
import lib.a as a import lib.b as b
hope this help you
|
Facing an error in program of image capturing and processing using opencv(cv2) and python
Question: In the following program, it captures and processes image runtime. But I am
facing a lot problems in the code. The first problem is, when camera is
initialized for the first time and if it is unable to detect red colour in
captured frame then it gives following error.
Traceback (most recent call last):
File "/home/mukund/Desktop/Checknewcod/attempone.py", line 23, in <module>
M=cv2.moments(best_cnt)
NameError: name 'best_cnt' is not defined
Sometimes it gives following error.
Traceback (most recent call last):
File "/home/mukund/Desktop/New logic/GridTestcal1.py", line 287, in <module>
fun2()
File "/home/mukund/Desktop/New logic/GridTestcal1.py", line 230, in fun2
M=cv2.moments(best_cnt)
UnboundLocalError: local variable 'best_cnt' referenced before assignment
The code is as follows.
import cv2
import numpy as np
capture = cv2.VideoCapture(1)
num = 0
while True:
flag, img2 = capture.read()
flag=capture.set(3,640)
flag=capture.set(4,480)
cv2.imwrite('pic'+str(num)+'.jpg', img2)
img1=cv2.imread('pic'+str(num)+'.jpg')
img=cv2.blur(img1,(3,3))
ORANGE_MIN=np.array([170,160,60],np.uint8)
ORANGE_MAX=np.array([180,255,255],np.uint8)
hsv_img=cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)
frame_thresh=cv2.inRange(hsv_img,ORANGE_MIN,ORANGE_MAX)
contours,hierarchy=cv2.findContours(frame_thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
x_area=0
for cnt in contours:
area=cv2.contourArea(cnt)
if area>x_area:
x_area=area
best_cnt=cnt
M=cv2.moments(best_cnt)
cx,cy=int(M['m10']/M['m00']),int(M['m01']/M['m00'])
cv2.circle(frame_thresh,(cx,cy),5,255,-1)
cv2.imwrite('pic1'+str(num)+'.jpg',frame_thresh)
print cx,cy
if num == 30:
capture.release()
break
num += 1
Is there any efficient way to implement above code such as using video
processing?
Answer: For the error, you should check that the number of returned contours is > 0.
In some cases no coutours are detected so best_cnt is not set so the error is
telling you that you are referencing it before defining that variable.
for cnt in contours:
area=cv2.contourArea(cnt)
if area>x_area: # I believe your code is indented wrongly here
x_area=area
best_cnt=cnt
if len(cnt) > 0: # In some cases no coutours are detected so best_cnt is not set.
M=cv2.moments(best_cnt)
cx,cy=int(M['m10']/M['m00']),int(M['m01']/M['m00'])
cv2.circle(frame_thresh,(cx,cy),5,255,-1)
cv2.imwrite('pic1'+str(num)+'.jpg',frame_thresh)
print cx,cy
if num == 30:
capture.release()
break
num += 1
The bulk of the processing time for your code, I believe, should be in reading
and writing the image. If you are getting the frames from a video camera, then
things might be slightly better, especially if its frame rate is high. If you
can choose to write the frames every say `k` images then it might help avoid
dropping frames. Also, it would help if you can narrow down the region of
interest (ROI) and only perform the image processing algorithms such as
cvtColor, inRange, and findContours on it.
Some minor tweaks would be to move the declaration of `ORANGE_MIN/MAX` outside
of the while loop.
|
How can I use monkey patching in Python to replace a specific argument?
Question: I want to use monkey patching to change all statements such as `time.sleep(5)`
to `myServer.sleep(5)`. How can I realize it? Thank you very much!
import test
import subprocess
import ast
import os
import time
import sys
if __name__ == "__main__":
def insomniac(duration):
pass # don't sleep
_original_sleep = time.sleep
time.sleep = insomniac
def dont_write(stuff):
pass # don't write
_original_write = sys.stdout.write
sys.stdout.write = dont_write
execfile("test.py")
exit(0)
Answer: If your focus is on testing, i.e. you want to ensure that a callable in some
external library out of your control is called in a specific way, there are
testing libraries that can help you with this, such as
[`mock`](https://pypi.python.org/pypi/mock). It can be pretty involving to set
all those things up correctly so when I do coding I typically try to structure
my code in a way that minimizes the usage of mocks.
Take a look at the [documentation for
`mock`](http://www.voidspace.org.uk/python/mock/) if you really want to get
your toes wet towards this direction. While at this, you probably should
formalize your testing techniques to make use of
[`unitttest`](http://docs.python.org/library/unittest.html). If you are lost,
[Writing unit tests in Python: How do I
start?](http://stackoverflow.com/questions/3371255/writing-unit-tests-in-
python-how-do-i-start).
|
I don't see why this code is not working! can someone please tell me what i am doing wrong?
Question: I keep getting an error, but i dont see it.. I am new to programing and if you
explane me the code, please dont assume I know too much.
#!/usr/bin/env python
# Name:
# Student number:
'''
This script crawls the IMDB top 250 movies.
'''
# Python standard library imports
import os
import sys
import csv
import codecs
import cStringIO
import errno
# Third party library imports:
import pattern
from pattern.web import URL, DOM
# --------------------------------------------------------------------------
# Constants:
TOP_250_URL = 'http://www.imdb.com/chart/top'
OUTPUT_CSV = 'top250movies.csv'
SCRIPT_DIR = os.path.split(os.path.realpath(__file__))[0]
BACKUP_DIR = os.path.join(SCRIPT_DIR, 'HTML_BACKUPS')
# --------------------------------------------------------------------------
# Unicode reading/writing functionality for the Python CSV module, taken
# from the Python.org csv module documentation (very slightly adapted).
# Source: http://docs.python.org/2/library/csv.html (retrieved 2014-03-09).
class UTF8Recoder(object):
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader(object):
"""
A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeWriter(object):
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
# --------------------------------------------------------------------------
# Utility functions (no need to edit):
def create_dir(directory):
'''
Create directory if needed.
Args:
directory: string, path of directory to be made
Note: the backup directory is used to save the HTML of the pages you
crawl.
'''
try:
os.makedirs(directory)
except OSError as e:
if e.errno == errno.EEXIST:
# Backup directory already exists, no problem for this script,
# just ignore the exception and carry on.
pass
else:
# All errors other than an already exising backup directory
# are not handled, so the exception is re-raised and the
# script will crash here.
raise
def save_csv(filename, rows):
'''
Save CSV file with the top 250 most popular movies on IMDB.
Args:
filename: string filename for the CSV file
rows: list of rows to be saved (250 movies in this exercise)
'''
with open(filename, 'wb') as f:
writer = UnicodeWriter(f) # implicitly UTF-8
writer.writerow([
'title', 'runtime', 'genre(s)', 'director(s)', 'writer(s)',
'actor(s)', 'rating(s)', 'number of rating(s)'
])
writer.writerows(rows)
def make_backup(filename, html):
'''
Save HTML to file.
Args:
filename: absolute path of file to save
html: (unicode) string of the html file
'''
with open(filename, 'wb') as f:
f.write(html)
def main():
'''
Crawl the IMDB top 250 movies, save CSV with their information.
Note:
This function also makes backups of the HTML files in a sub-directory
called HTML_BACKUPS (those will be used in grading).
'''
# Create a directory to store copies of all the relevant HTML files (those
# will be used in testing).
print 'Setting up backup dir if needed ...'
create_dir(BACKUP_DIR)
# Make backup of the IMDB top 250 movies page
print 'Access top 250 page, making backup ...'
top_250_url = URL(TOP_250_URL)
top_250_html = top_250_url.download(cached=True)
make_backup(os.path.join(BACKUP_DIR, 'index.html'), top_250_html)
# extract the top 250 movies
print 'Scraping top 250 page ...'
url_strings = scrape_top_250(top_250_url)
# grab all relevant information from the 250 movie web pages
rows = []
for i, url in enumerate(url_strings): # Enumerate, a great Python trick!
print 'Scraping movie %d ...' % i
# Grab web page
movie_html = URL(url).download(cached=True)
# Extract relevant information for each movie
movie_dom = DOM(movie_html)
rows.append(scrape_movie_page(movie_dom))
# Save one of the IMDB's movie pages (for testing)
if i == 83:
html_file = os.path.join(BACKUP_DIR, 'movie-%03d.html' % i)
make_backup(html_file, movie_html)
# Save a CSV file with the relevant information for the top 250 movies.
print 'Saving CSV ...'
save_csv(os.path.join(SCRIPT_DIR, 'top250movies.csv'), rows)
This function below, should return the webpage links of the top 250 movies:
# --------------------------------------------------------------------------
# Functions to adapt or provide implementations for:
def scrape_top_250(url):
'''
Scrape the IMDB top 250 movies index page.
Args:
url: pattern.web.URL instance pointing to the top 250 index page
Returns:
A list of strings, where each string is the URL to a movie's page on
IMDB, note that these URLS must be absolute (i.e. include the http
part, the domain part and the path part).
'''
movie_urls = []
table_rows = dom.by_id('main').by_tag('table')[1].by_tag('tr')
for tr in table_rows[1:]:
a = tr.by_tag('a')[0]
movie_urls.append(clean_unicode(abs_url(a.attributes.get('href', ''), url.string)))
# YOUR SCRAPING CODE GOES HERE, ALL YOU ARE LOOKING FOR ARE THE ABSOLUTE
# URLS TO EACH MOVIE'S IMDB PAGE, ADD THOSE TO THE LIST movie_urls.
# return the list of URLs of each movie's page on IMDB
return movie_urls
#print scrape_top_250(url)
And finaly this function should return specific contents.
def scrape_movie_page(dom):
'''
Scrape the IMDB page for a single movie
Args:
dom: pattern.web.DOM instance representing the page of 1 single
movie.
Returns:
A list of strings representing the following (in order): title, year,
duration, genre(s) (semicolon separated if several), director(s)
(semicolon separated if several), writer(s) (semicolon separated if
several), actor(s) (semicolon separated if several), rating, number
of ratings.
'''
# YOUR SCRAPING CODE GOES HERE:
for p in movie_urls:
p_url = URL(p)
p_dom = DOM(p_url.download(cached=True))
title = clean_unicode(p_dom.by_class('header')[0].content)
title = plaintext(strip_between('<span', '</span>', title))
runtime = clean_unicode(p_dom.by_class('infobar')[0].by_tag('time')[0].content)
duration = runtime
genres = []
for genre in p_dom.by_class('infobar')[0].by_tag('a')[:-1]:
genres.append(clean_unicode(genre.content))
directors = []
writers = []
actors = []
text_blocks = p_dom.by_class('txt-block')[:3]
for t in text_blocks:
spans = t.by_tag('span')
for s in spans:
if s.attributes.get('itemprop') == 'director':
director = s.by_tag('span')[0].by_tag('a')[0].content
directors.append(clean_unicode(director))
if s.attributes.get('itemprop') == 'writer':
p_writer = s.by_tag('span')[0].by_tag('a')[0].content
writers.append(clean_unicode(p_writer))
if s.attributes.get('itemprop') == 'actors':
actor = s.by_tag('span')[0].by_tag('a')[0].content
actors.append(clean_unicode(actor))
rating = []
ratings_count = []
spans = p_dom.by_class('star-box-details')[0].by_tag('span')
for s in spans:
if s.attributes.get('itemprop') == 'ratingValue':
rating = clean_unicode(s.content)
if s.attributes.get('itemprop') == 'ratingCount':
ratings_count = clean_unicode(s.content)
# format the strings from lists
genres = concat_strings(genres)
directors = concat_strings(directors)
writers = concat_strings(writers)
actors = concat_strings(actors)
# Return everything of interest for this movie (all strings as specified
# in the docstring of this function).
return title, duration, genres, directors, writers, actors, rating, \
n_ratings
if __name__ == '__main__':
main() # call into the progam
# If you want to test the functions you wrote, you can do that here:
# ...
Answer: It's just that ([in the original
revision](http://stackoverflow.com/revisions/22401980/1)) you forgot to indent
the body of the function `scrape_movie_page`. The `for` loop is in module
scope.
|
Retrieving whole genome genbank files for some organism using Biojava or Biopython
Question: does anyone have an idea how to automatically search and parse gbk files from
FTP ncbi using either BIopython or BioJAVA. I have searched for the utilities
in BIojava and have not found any. I have also tried BioPython and here is my
Code:
from Bio import Entrez
Entrez.email = "test@yahoo.com"
Entrez.tool = "MyLocalScript"
handle = Entrez.esearch(db="nucleotide", term="Mycobacterium avium[Orgn]")
record = Entrez.read(handle)
print record
print record["Count"]
id_L = record["IdList"]
print id_L
print len(id_L)
However, there are only 3 mycobacterium avium species (whole genome sequences
and fully annotated) the result I am getting is 59897.
Can anyone tell me how to perform the search either in BioJava or BioPython.
Otherwise I will have to automate this process form scratch.
Thank you.
Answer: The way we do it is by specifying the id specifically using the efetch
interface:
Entrez.efetch(db="nucleotide", id=<ACCESSION ID HERE>, rettype="gb", retmode="text")
Using a search term such as the one you used returns too many matches, all of
which you are downloading. See 48 different bioprojects with your search term
here:
<http://www.ncbi.nlm.nih.gov/bioproject/?term=Mycobacterium+avium>
From experience, the most accurate way to get what you want is to use the
ACCESSION ID.
|
Fortran - Cython Workflow
Question: I would like to set up a workflow to reach fortran routines from Python using
Cython on a Windows Machine
after some searching I found : <http://www.fortran90.org/src/best-
practices.html#interfacing-with-c> and <http://stackoverflow.com/tags/fortran-
iso-c-binding/info>
and some code pices:
Fortran side:
pygfunc.h:
void c_gfunc(double x, int n, int m, double *a, double *b, double *c);
pygfunc.f90
module gfunc1_interface
use iso_c_binding
use gfunc_module
implicit none
contains
subroutine c_gfunc(x, n, m, a, b, c) bind(c)
real(C_FLOAT), intent(in), value :: x
integer(C_INT), intent(in), value :: n, m
type(C_PTR), intent(in), value :: a, b
type(C_PTR), value :: c
real(C_FLOAT), dimension(:), pointer :: fa, fb
real(C_FLOAT), dimension(:,:), pointer :: fc
call c_f_pointer(a, fa, (/ n /))
call c_f_pointer(b, fb, (/ m /))
call c_f_pointer(c, fc, (/ n, m /))
call gfunc(x, fa, fb, fc)
end subroutine
end module
gfunc.f90
module gfunc_module
use iso_c_binding
implicit none
contains
subroutine gfunc(x, a, b, c)
real, intent(in) :: x
real, dimension(:), intent(in) :: a, b
real, dimension(:,:), intent(out) :: c
integer :: i, j, n, m
n = size(a)
m = size(b)
do j=1,m
do i=1,n
c(i,j) = exp(-x * (a(i)**2 + b(j)**2))
end do
end do
end subroutine
end module
Cython side:
pygfunc.pyx
cimport numpy as cnp
import numpy as np
cdef extern from "./pygfunc.h":
void c_gfunc(double, int, int, double *, double *, double *)
cdef extern from "./pygfunc.h":
pass
def f(float x, a=-10.0, b=10.0, n=100):
cdef cnp.ndarray ax, c
ax = np.arange(a, b, (b-a)/float(n))
n = ax.shape[0]
c = np.ndarray((n,n), dtype=np.float64, order='F')
c_gfunc(x, n, n, <double *> ax.data, <double *> ax.data, <double *> c.data)
return c
and the setup file:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
ext_modules = [Extension('pygfunc', ['pygfunc.pyx'])]
setup(
name = 'pygfunc',
include_dirs = [np.get_include()],
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules )
all the files ar in one directory
the fortran files compile ( using NAG Fortran Builder ) pygfunc compiles
but linking them throws a:
error LNK2019: unresolved external symbol _c_gfunc referenced in function
___pyx_pf_7pygfunc_f
and of course:
fatal error LNK1120: 1 unresolved externals
What am I missing ? or is this way to set up a workflow between Python and
Fortran damned from the beginning ?
THX Martin
Answer: Here's a minimum working example. I used gfortran and wrote the compile
commands directly into the setup file.
`gfunc.f90`
module gfunc_module
implicit none
contains
subroutine gfunc(x, n, m, a, b, c)
double precision, intent(in) :: x
integer, intent(in) :: n, m
double precision, dimension(n), intent(in) :: a
double precision, dimension(m), intent(in) :: b
double precision, dimension(n, m), intent(out) :: c
integer :: i, j
do j=1,m
do i=1,n
c(i,j) = exp(-x * (a(i)**2 + b(j)**2))
end do
end do
end subroutine
end module
`pygfunc.f90`
module gfunc1_interface
use iso_c_binding, only: c_double, c_int
use gfunc_module, only: gfunc
implicit none
contains
subroutine c_gfunc(x, n, m, a, b, c) bind(c)
real(c_double), intent(in) :: x
integer(c_int), intent(in) :: n, m
real(c_double), dimension(n), intent(in) :: a
real(c_double), dimension(m), intent(in) :: b
real(c_double), dimension(n, m), intent(out) :: c
call gfunc(x, n, m, a, b, c)
end subroutine
end module
`pygfunc.h`
extern void c_gfunc(double* x, int* n, int* m, double* a, double* b, double* c);
`pygfunc.pyx`
from numpy import linspace, empty
from numpy cimport ndarray as ar
cdef extern from "pygfunc.h":
void c_gfunc(double* a, int* n, int* m, double* a, double* b, double* c)
def f(double x, double a=-10.0, double b=10.0, int n=100):
cdef:
ar[double] ax = linspace(a, b, n)
ar[double,ndim=2] c = empty((n, n), order='F')
c_gfunc(&x, &n, &n, <double*> ax.data, <double*> ax.data, <double*> c.data)
return c
`setup.py`
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# This line only needed if building with NumPy in Cython file.
from numpy import get_include
from os import system
# compile the fortran modules without linking
fortran_mod_comp = 'gfortran gfunc.f90 -c -o gfunc.o -O3 -fPIC'
print fortran_mod_comp
system(fortran_mod_comp)
shared_obj_comp = 'gfortran pygfunc.f90 -c -o pygfunc.o -O3 -fPIC'
print shared_obj_comp
system(shared_obj_comp)
ext_modules = [Extension(# module name:
'pygfunc',
# source file:
['pygfunc.pyx'],
# other compile args for gcc
extra_compile_args=['-fPIC', '-O3'],
# other files to link to
extra_link_args=['gfunc.o', 'pygfunc.o'])]
setup(name = 'pygfunc',
cmdclass = {'build_ext': build_ext},
# Needed if building with NumPy.
# This includes the NumPy headers when compiling.
include_dirs = [get_include()],
ext_modules = ext_modules)
`test.py`
# A script to verify correctness
from pygfunc import f
print f(1., a=-1., b=1., n=4)
import numpy as np
a = np.linspace(-1, 1, 4)**2
A, B = np.meshgrid(a, a, copy=False)
print np.exp(-(A + B))
Most of the changes I made aren't terribly fundamental. Here are the important
ones.
* You were mixing double precision and single precision floating point numbers. _Don't do that._ Use real (Fortran), float (Cython), and float32 (NumPy) together and use double precision (Fortran), double (Cyton), and float64 (NumPy) together. Try not to mix them unintentionally. I assumed you wanted doubles in my example.
* You should pass all variables to Fortran as pointers. It does not match the C calling convention in that regard. The iso_c_binding module in Fortran only matches the C naming convention. Pass arrays as pointers with their size as a separate value. There may be other ways of doing this, but I don't know any.
I also added some stuff in the setup file to show where you can add some of
the more useful extra arguments when building.
To compile, run `python setup.py build_ext --inplace`. To verify that it
works, run the test script.
Here is the example shown on fortran90.org:
[mesh_exp](https://github.com/arrghb2012/fortran90/tree/master/fcython_mesh)
Here are two more that I put together some time ago:
[ftridiag](https://github.com/byuimpact/numerical_computing/tree/develop/Python/cython_wrapping/ftridiag),
[fssor](https://github.com/byuimpact/numerical_computing/tree/develop/Python/cython_wrapping/fssor)
I'm certainly not an expert at this, but these examples may be a good place to
start.
|
Parsing XML string with python
Question: I have an XML string that I take from a wsdl web service. I tried to parse it
with elementTree but it is only for files. I tried to save it in a file in
order to parse it but it says I don't have permission to open the file. So I
used this solution that I found in stackoverflow:
try:
queryresult = client.service.executeQuery(query)
except WebFault, e:
print e
tree = ET.ElementTree(ET.fromstring(queryresult))
rootElem = tree.getroot()
result = rootElem.findall(".//result")
but when I print the result I take a value like Element 'result' at
0x7f6e454bdb90
I also tried to print
result.text
or
for s in result:
test = s.attrib
and in result = rootElem.findall(".//result") i also tried result =
rootElem.findall("result") or result = rootElem.findall("results/result")
This is the xml string (I added only a part of it because it is too big):
<?xml version="1.0" encoding="UTF-8"?> <sparql> <head> <variable name="id"/> <variable name="code"/> <variable name="title"/> <variable name="text"/> <variable name="substanceCode"/> <variable name="patientId"/> <variable name="birthTime"/> <variable name="effectiveTime_start"/> </head> <results> <result> <binding name="id"> <literal>df868fff-9d48-11e2-8ee8-833b8491ffe6</literal> </binding> <binding name="code"> <literal>432102000</literal> </binding> <binding name="title"> <literal>Administration of substance (procedure)</literal> </binding> <binding name="text"> <literal>Aclarubicin (product)</literal> </binding> <binding name="substanceCode"> <literal>326830005</literal> </binding> <binding name="patientId"> <literal>fictitious1</literal> </binding> <binding name="birthTime"> <literal>1965-03-01T00:00:00.0</literal> </binding> </result>
I also tried @alecxe solution:
def index(request,requestresult):
data = requestresult
tree = ET.fromstring(data)
for literal in tree.findall('.//result/binding/literal')
returnresult = literal.text
if tokens_p(request):
account_id = urllib.unquote(request.session['oauth_token_set']['account_id'])
return utils.render_template('ui/index', { 'ACCOUNT_ID': account_id, 'SETTINGS': settings,'returnresult':returnresult})
return HttpResponseRedirect(reverse(login))
And then I printed the results {{returnresult}} in index.html but nothing is
printing. Then I tried:
tree = ET.ElementTree(ET.fromstring(data))
rootElem = tree.getroot()
returnresult = rootElem.findall('.//results/result/binding/literal')
and it prints Element 'literal' at 0x7f6e4529fc10 Element 'literal' at
0x7f6e4529fc90 etc. And when I try to print it with:
for literal in rootElem.findall('.//results/result/binding/literal')
returnresult = literal.text
I have an error invalid syntax in line: "for literal in
rootElem.findall('.//results/result/binding/literal')"
Answer: According to your comment, you want to get the value of `literal` tag inside
`binding` tag that is inside `result`. In this case you should use
`.//result/binding/literal` xpath expression:
import xml.etree.ElementTree as ET
data = """<?xml version="1.0" encoding="UTF-8"?>
<sparql>
<head>
<variable name="id"/>
<variable name="code"/>
<variable name="title"/>
<variable name="text"/>
<variable name="substanceCode"/>
<variable name="patientId"/>
<variable name="birthTime"/>
<variable name="effectiveTime_start"/>
</head>
<results>
<result>
<binding name="id">
<literal>df868fff-9d48-11e2-8ee8-833b8491ffe6</literal>
</binding>
<binding name="code">
<literal>432102000</literal>
</binding>
</result>
</results>
</sparql>"""
tree = ET.fromstring(data)
print [literal.text for literal in tree.findall('.//result/binding/literal')]
prints:
['df868fff-9d48-11e2-8ee8-833b8491ffe6', '432102000']
Note I've cut down xml a bit.
Hope that helps.
|
Python - Exhaust map of multiple iterables
Question:
a=['1','2','3']
`map(int,a)` can be exhausted using list to yield output:
list(map(int,a))
output: `1,2,3`
* * *
a=['1','2','3']
b=['1','2']
How do I exhaust the following:
map(int,a,b)
Answer: If you want to convert each of the lists to a list of integers, you can do
a, b = ['1','2','3'], ['1','2']
print(list(map(lambda x: map(int,x), [a, b])))
# [[1, 2, 3], [1, 2]]
which can be assigned to `a` and `b` back, like this
a, b = map(lambda x: map(int,x), [a, b])
If you want to chain the elements, you can use
[`itertools.chain`](http://docs.python.org/2/library/itertools.html#itertools.chain),
like this
from itertools import chain
print(list(map(int, chain(a,b))))
# [1, 2, 3, 1, 2]
**Edit:** if you want to pass more than iterable as arguments, then the
function also has to accept that many number of parameters. For example,
a, b = [1, 2, 3], [1, 2, 3]
print(list(map(lambda x, y: x + y, a, b)))
# [2, 4, 6]
If we are passing three iterables, the function has to accept three
parameters,
a, b, c = [1, 2, 3], [1, 2, 3], [1, 2, 3]
print(list(map(lambda x, y, z: x + y + z, a, b, c)))
# [3, 6, 9]
If the iterables are not of the same size, then the length of the least sized
iterable will be taken in to consideration. So
a, b, c = [1, 2, 3], [1, 2, 3], [1, 2]
print(list(map(lambda x, y, z: x + y + z, a, b, c)))
# [3, 6]
|
Is it possible to make grequests and requests_cache work together?
Question: Look at this code:
import requests
import grequests
import requests_cache
requests_cache.install_cache('bla')
urls = [
'http://www.heroku.com',
'http://python-tablib.org',
'http://httpbin.org',
'http://python-requests.org',
'http://kennethreitz.com'
]
rs = (grequests.get(u) for u in urls)
results = grequests.map(rs)
I would expect that after executing this I will find `bla.sqlite` file in the
current directory and executing
results = grequests.map(rs)
will be MUCH faster because data will be taken from sqlite cache.
Unfortunately this is not true, file wasn't created at all and there is no
speedup. When I use requests insetead of grequests everything works fine. So
the question is a title says: **Is it possible to make grequests and
requests_cache work together?** and if yes, how?
Answer: The `requests_cache.install_cache()` function patches `requests.Session`, but
you already imported `grequests`, which used:
from requests import Session
As such, `grequests` never uses the patched session object.
Move the import to _after_ you installed the cache:
import requests_cache
requests_cache.install_cache('bla')
import grequests
Alternatively, create a [`CachedSession` object](https://requests-
cache.readthedocs.org/en/latest/api.html#requests_cache.core.CachedSession)
and pass that in to the `grequests.get()` (and related) methods as the
`session` parameter:
import grequests
import requests_cache
session = requests_cache.CachedSession('bla')
urls = [
'http://www.heroku.com',
'http://python-tablib.org',
'http://httpbin.org',
'http://python-requests.org',
'http://kennethreitz.com'
]
rs = (grequests.get(u, session=session) for u in urls)
results = grequests.map(rs)
Take into account that the cache storage backend may not be able to handle the
corcurrent access safely. The `sqlite` backend uses a thread lock, for
example, which might well clash.
|
Why is this program not writing the final variable string to it's destination text file?
Question: I'm almost there with using some Python code to pull down stock data strings
passed to it from SAS to build a text file to read back into SAS, but the
final output text file remains at 0 bytes, despite the code running without
error and the print statements I have put in the log seeming to display valid
output. Here is the code:
import concurrent.futures
import urllib.request
import json
with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_1_a.txt", "r") as myurls:
myurls2 = myurls.read().replace('\n', '')
URLS = [myurls2]
print('URLS =', URLS)
# Retrieve a single page and report the url and contents
def load_url(url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
c = 0
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
a = ''
b = ''
c += 1
mylen = (len(myurls2)) - 1
print('String length = %s' % (len(myurls2)))
a = myurls2[mylen:]
print('a=', a)
if a == 'a':
b = 'Ask'
elif a == 'y':
b = 'Dividend Yield'
elif a == 'b':
b = 'Bid'
elif a == 'd':
b = 'Dividend per Share'
elif a == 'b2':
b = 'Ask (Realtime)'
elif a == 'r1':
b = 'Dividend Pay Date'
elif a == 'b3':
b = 'Bid (Realtime)'
elif a == 'q':
b = 'Ex-Dividend Date'
elif a == 'p':
b = 'Previous Close'
elif a == 'o':
b = 'Open'
elif a == 'c1':
b = 'Change'
elif a == 'd1':
b = 'Last Trade Date'
elif a == 'c':
b = 'Change & Percent Change'
elif a == 'd2':
b = 'Trade Date'
elif a == 'c6':
b = 'Change (Realtime)'
elif a == 't1':
b = 'Last Trade Time'
elif a == 'k2':
b = 'Change Percent (Realtime)'
elif a == 'p2':
b = 'Change in Percent'
elif a == 'c8':
b = 'After Hours Change (Realtime)'
elif a == 'm5':
b = 'Change From 200 Day Moving Average'
elif a == 'c3':
b = 'Commission'
elif a == 'm6':
b = 'Percent Change From 200 Day Moving Average'
elif a == 'g':
b = 'Days Low'
elif a == 'm7':
b = 'Change From 50 Day Moving Average'
elif a == 'h':
b = 'Days High'
elif a == 'm8':
b = 'Percent Change From 50 Day Moving Average'
elif a == 'k1':
b = 'Last Trade (Realtime) With Time'
elif a == 'm3':
b = '50 Day Moving Average'
elif a == 'l':
b = 'Last Trade (With Time)'
elif a == 'm4':
b = '200 Day Moving Average'
elif a == 'l1':
b = 'Last Trade (Price Only)'
elif a == 't8':
b = '1 yr Target Price'
elif a == 'w1':
b = 'Days Value Change'
elif a == 'g1':
b = 'Holdings Gain Percent'
elif a == 'w4':
b = 'Days Value Change (Realtime)'
elif a == 'g3':
b = 'Annualized Gain'
elif a == 'p1':
b = 'Price Paid'
elif a == 'g4':
b = 'Holdings Gain'
elif a == 'm':
b = 'Days Range'
elif a == 'g5':
b = 'Holdings Gain Percent (Realtime)'
elif a == 'm2':
b = 'Days Range (Realtime)'
elif a == 'g6':
b = 'Holdings Gain (Realtime)'
elif a == 'k':
b = '52 Week High'
elif a == 'v':
b = 'More Info'
elif a == 'j':
b = '52 week Low'
elif a == 'j1':
b = 'Market Capitalization'
elif a == 'j5':
b = 'Change From 52 Week Low'
elif a == 'j3':
b = 'Market Cap (Realtime)'
elif a == 'k4':
b = 'Change From 52 week High'
elif a == 'f6':
b = 'Float Shares'
elif a == 'j6':
b = 'Percent Change From 52 week Low'
elif a == 'n':
b ='Name'
elif a == 'k5':
b = 'Percent Change From 52 week High'
elif a == 'n4':
b = 'Notes'
elif a == 'w':
b = '52 week Range'
elif a == 's':
b = 'Symbol'
elif a == 's1':
b = 'Shares Owned'
elif a == 'x':
b = 'Stock Exchange'
elif a == 'j2':
b = 'Shares Outstanding'
elif a == 'v':
b = 'Volume'
elif a == 'a5':
b = 'Ask Size'
elif a == 'b6':
b = 'Bid Size'
elif a == 'k3':
b = 'Last Trade Size'
elif a == 't7':
b = 'Ticker Trend'
elif a == 'a2':
b = 'Average Daily Volume'
elif a == 't6':
b = 'Trade Links'
elif a == 'i5':
b = 'Order Book (Realtime)'
elif a == 'l2':
b = 'High Limit'
elif a == 'e':
b = 'Earnings per Share'
elif a == 'l3':
b = 'Low Limit'
elif a == 'e7':
b = 'EPS Estimate Current Year'
elif a == 'v1':
b = 'Holdings Value'
elif a == 'e8':
b = 'EPS Estimate Next Year'
elif a == 'v7':
b = 'Holdings Value (Realtime)'
elif a == 'e9':
b = 'EPS Estimate Next Quarter'
elif a == 's6':
b = 'Revenue'
elif a == 'b4':
b = 'Book Value'
elif a == 'j4':
b = 'EBITDA'
elif a == 'p5':
b = 'Price-Sales'
elif a == 'p6':
b = 'Price-Book'
elif a == 'r':
b = 'P-E Ratio'
elif a == 'r2':
b = 'P-E Ratio (Realtime)'
elif a == 'r5':
b = 'PEG Ratio'
elif a == 'r6':
b = 'Price - EPS Estimate Current Year'
elif a == 'r7':
b = 'Price - EPS Estimate Next Year'
elif a == 's7':
b = 'Short Ratio'
print('b =', b)
print('c =', c)
filename = "%s" % (b)
filepath = "C:\\Python33\\Stock Data\\" + str(filename) + ".txt"
print(filepath)
print("future.result = ", future.result())
try:
data = future.result()
d = open(filepath,"wb")
d.write(data)
d.close
# do json processing here
except Exception as exc:
for e in range(1,11):
if len(data) > 0:
print('Byte length = %d' % (len(data)))
print(e)
print('%r generated an exception: %s' % (url, exc))
print('retrying %r' % (url))
def load_url(url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
time.sleep(10)
print("press ENTER to exit")
else:
print('%r page is %d bytes' % (url, len(data)))
The various print statement shows the source text file contents being picked
up correctly and passed through to the code ok. The line `print("future result
=", future.result())` shows the following result:
b'31.90\r\n36.66\r\nN/A\r\n3.69\r\n25.52\r\n27.10\r\n525.33\r\n31.81\r\n56.90\r\n38.23\r\n23.86\r\n2.19\r\n66.93\r\n35.74\r\n21.74\r\n2.10\r\n26.08\r\n14.20\r\n26.73\r\n14.92\r\n48.42\r\n12.49\r\n19.31\r\n4.09\r\n3.37\r\n57.78\r\n45.85\r\n3.32\r\n60.02\r\n2.31\r\n18.50\r\n37.74\r\n3.42\r\n12.46\r\n14.03\r\n1.25\r\n15.13\r\n2.53\r\n1.73\r\n56.72\r\n44.98\r\n35.89\r\n1.05\r\n67.50\r\n17.35\r\n50.72\r\n20.72\r\n50.37\r\n6.27\r\n13.23\r\n77.50\r\n27.62\r\n24.49\r\n34.02\r\n24.56\r\n50.59\r\n25.50\r\n21.53\r\n31.33\r\n4.65\r\n4.65\r\n24.00\r\n52.04\r\n2.73\r\n24.78\r\n39.94\r\n20.57\r\n6.84\r\n2.97\r\n1.27\r\n24.08\r\n20.50\r\n7.44\r\n14.49\r\n13.22\r\n37.62\r\n4.39\r\n44.46\r\n44.46\r\n43.80\r\n22.58\r\n22.58\r\n48.92\r\n14.60\r\n50.12\r\n60.75\r\n2.36\r\n35.10\r\n8.47\r\n29.81\r\n53.13\r\n19.57\r\n12.95\r\n16.76\r\n59.70\r\n16.63\r\n4.74\r\n23.44\r\n37.52\r\n10.37\r\n52.81\r\n107.50\r\n6.64\r\n46.15\r\n15.50\r\n14.85\r\n72.06\r\n79.08\r\n14.25\r\n8.90\r\n1.91\r\n5.54\r\n35.43\r\n5.12\r\n177.09\r\n20.30\r\n20.60\r\n18.80\r\n28.30\r\n31.93\r\n31.93\r\n10.24\r\n1.65\r\n10.09\r\n1.83\r\n2.15\r\n74.23\r\n7.51\r\n14.38\r\n123.76\r\n12.89\r\n6.17\r\n23.22\r\n11.80\r\n19.70\r\n9.95\r\n17.93\r\n1.81\r\n4.18\r\n2.13\r\n42.81\r\n44.29\r\nN/A\r\n32.72\r\n373.95\r\n21.12\r\n1.85\r\n114.72\r\n20.25\r\n2.03\r\n16.89\r\n57.65\r\n13.28\r\n16.79\r\n42.24\r\n33.87\r\n77.08\r\n3.49\r\n7.26\r\nN/A\r\n33.95\r\n34.02\r\n32.33\r\n3.07\r\n2.42\r\n16.00\r\n2.87\r\n10.26\r\nN/A\r\nN/A\r\n13.45\r\n9.70\r\n17.36\r\n2.89\r\n14.61\r\n14.61\r\n29.00\r\n20.78\r\n11.39\r\n8.25\r\n71.81\r\n3.34\r\n22.15\r\n80.82\r\n47.80\r\n6.56\r\n26.67\r\n2.17\r\n28.43\r\n5.06\r\n48.16\r\nN/A\r\n6.00\r\n4.29\r\n20.20\r\n22.79\r\n17.75\r\n17.52\r\n17.52\r\n13.80\r\n'
This looks like the correct values to me, but just needing cleaning up. The
destination text file resolves correctly and the all OK statement below the
error handling returns the byte length of the URL submission correctly. The
text file though remains empty.
Can anyone spot an obvious mistake I have made?
Thanks
Answer: Move `d = open(filepath,"wb")` and `d.close()` outside of the for loop.
Every iteration of the loop deletes and overwrites the file.
<http://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files>
EDIT: I didn't see that the filepath is calculated in the forloop. I'd do what
@sabbahillel pointed out, and open the file with "ab" mode to ensure it's not
overwritten.
|
Trying to produce automated daily call reports through RingCentral either by webscraping or by emailing the .csv export
Question: Since RingCentral (VOIP) phone provider does not provide any call statistic
reporting, I am looking for an alternative.
I want to automate this as much as possible, and avoid having to go to the
website everyday, send the report through email, open the email import the
`.csv` into Excel and run the script.
I have believe I have two options here (correct me if you know of more):
1. Webscrape from Ringcentral.com
2. Create an email address to send automatic reports to daily. I then would probably use Python to access this `.csv` file, apply macro, and send results to another email.
I am looking for guidance on the best way to approach this problem. If someone
would like to see how the data is embedded in the website I can provide the
source code. It is JavaScript, which I am not familiar with.
Any suggestions are appreciated.
Thanks, J
Answer: You can use the RingCentral REST API to retrieve Call Log Records in JSON
format. This is available directly from the API and via the SDKs which
includes both Python and JavaScript.
* API Guide: <https://developers.ringcentral.com/api-docs/index.html##GetCallLog.html>
* SDKs: <https://github.com/ringcentral>
As a note, the RingCentral Online Account Portal does provide some call
reporting now, so if that works for you, there would be no development
necessary.
|
Can't install python mysql library on Mac Mavericks
Question: It was working like a charm before the update from Mountain Lion.
After the update it is broken and I cannot get the environment up again.
Does anybody know how to fix this?
The error is bolded, below.
fedorius@this:~$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.5.zip (108kB): 108kB downloaded
Running setup.py (path:/private/var/folders/21/zjvwzn891jnf4rnp526y13200000gn/T/pip_build_fedorius/mysql-python/setup.py) egg_info for package mysql-python
Installing collected packages: mysql-python
Running setup.py install for mysql-python
building '_mysql' extension
cc -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -pipe -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/mysql/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.9-intel-2.7/_mysql.o -Os -g -fno-strict-aliasing -arch x86_64
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: command 'cc' failed with exit status 1
Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/21/zjvwzn891jnf4rnp526y13200000gn/T/pip_build_fedorius/mysql-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/21/zjvwzn891jnf4rnp526y13200000gn/T/pip-_yi6sy-record/install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build/lib.macosx-10.9-intel-2.7
copying _mysql_exceptions.py -> build/lib.macosx-10.9-intel-2.7
creating build/lib.macosx-10.9-intel-2.7/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb
creating build/lib.macosx-10.9-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-intel-2.7/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.9-intel-2.7
cc -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -pipe -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/mysql/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.9-intel-2.7/_mysql.o -Os -g -fno-strict-aliasing -arch x86_64
**clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: command 'cc' failed with exit status 1**
----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/21/zjvwzn891jnf4rnp526y13200000gn/T/pip_build_fedorius/mysql-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/21/zjvwzn891jnf4rnp526y13200000gn/T/pip-_yi6sy-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/var/folders/21/zjvwzn891jnf4rnp526y13200000gn/T/pip_build_fedorius/mysql-python
Storing debug log for failure in /var/folders/21/zjvwzn891jnf4rnp526y13200000gn/T/tmp5QBn55
UPDATE:
As suggested, I've added
export CFLAGS=-Qunused-arguments export CPPFLAGS=-Qunused-arguments
But it changed the error to
error: /Library/Python/2.7/site-packages/_mysql.so: Permission denied
I just chmoded this directory to allow writing and it worked :) This is due to
mixing macports, easy_install and pip... shame on me.
Answer: The problem is due to changes introduced in Xcode 5.1 and due to the way the
Apple-supplied system Python 2.7 is built. Try adding these environment
variable values before running `pip`:
export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments
See [clang error: unknown argument: '-mno-fused-madd' (python package
installation failure)](http://stackoverflow.com/questions/22313407/clang-
error-unknown-argument-mno-fused-madd-psycopg2-installation-
failure/22322645#22322645) for more information.
UPDATE [2014-05-16]: As expected, Apple has fixed this problem with updated
system Pythons (2.7, 2.6, and 2.5) in `OS X 10.9.3` so the workaround is no
longer necessary when using the latest Mavericks and `Xcode 5.1+`. However, as
of now, the workaround is still required for `OS X 10.8.x` (Mountain Lion,
currently 10.8.5) if you are using `Xcode 5.1+` there.
|
rescale and normalize x axis numbers in python3.2 and matplotlib
Question: I am working in python 3.2 and matplotlib.
The numbers of x-axis are between 0 and 1000000.
In my plot, the numbers of x-axis are long and overlap each other.
I want to re-scale and normalize them between 0 and 10 and also show the unit
(such as 10^6) around the x-axis.
How can I do that?
Any help would be appreciated.
Answer: use `set_powerlimits()`:
import pylab as pl
x = np.linspace(0, 1000000, 100)
y = x * 2
pl.plot(x, y)
ax = pl.gca()
xaxis = ax.xaxis
xaxis.major.formatter.set_powerlimits((0, 4))
|
subprocess.Popen stdin read file
Question: I'm trying to call a process on a file after part of it has been read. For
example:
with open('in.txt', 'r') as a, open('out.txt', 'w') as b:
header = a.readline()
subprocess.call(['sort'], stdin=a, stdout=b)
This works fine if I don't read anything from a before doing the
subprocess.call, but if I read anything from it, the subprocess doesn't see
anything. This is using python 2.7.3. I can't find anything in the
documentation that explains this behaviour, and a (very) brief glance at the
subprocess source didn't reveal a cause.
Answer: If you open the file unbuffered then it works:
import subprocess
with open('in.txt', 'rb', 0) as a, open('out.txt', 'w') as b:
header = a.readline()
rc = subprocess.call(['sort'], stdin=a, stdout=b)
`subprocess` module works at a file descriptor level (low-level unbuffered I/O
of the operating system). It may work with `os.pipe()`, `socket.socket()`,
`pty.openpty()`, anything with a valid `.fileno()` method if OS supports it.
_It is not recommended to mix the buffered and unbuffered I/O on the same
file._
On Python 2, `file.flush()` causes the output to appear e.g.:
import subprocess
# 2nd
with open(__file__) as file:
header = file.readline()
file.seek(file.tell()) # synchronize (for io.open and Python 3)
file.flush() # synchronize (for C stdio-based file on Python 2)
rc = subprocess.call(['cat'], stdin=file)
The issue can be reproduced without `subprocess` module with `os.read()`:
#!/usr/bin/env python
# 2nd
import os
with open(__file__) as file: #XXX fully buffered text file EATS INPUT
file.readline() # ignore header line
os.write(1, os.read(file.fileno(), 1<<20))
If the buffer size is small then the rest of the file is printed:
#!/usr/bin/env python
# 2nd
import os
bufsize = 2 #XXX MAY EAT INPUT
with open(__file__, 'rb', bufsize) as file:
file.readline() # ignore header line
os.write(2, os.read(file.fileno(), 1<<20))
It eats more input if the first line size is not evenly divisible by
`bufsize`.
The default `bufsize` and `bufsize=1` (line-buffered) behave similar on my
machine: the beginning of the file vanishes -- around 4KB.
`file.tell()` reports for all buffer sizes the position at the beginning of
the 2nd line. Using `next(file)` instead of `file.readline()` leads to
`file.tell()` around 5K on my machine on Python 2 due to the [read-ahead
buffer bug](http://bugs.python.org/issue3907) (`io.open()` gives the expected
2nd line position).
Trying `file.seek(file.tell())` before the subprocess call doesn't help on
Python 2 with default stdio-based file objects. It works with `open()`
functions from `io`, `_pyio` modules on Python 2 and with the default `open`
(also `io`-based) on Python 3.
Trying `io`, `_pyio` modules on Python 2 and Python 3 with and without
`file.flush()` produces various results. It confirms that _mixing buffered and
unbuffered I/O on the same file descriptor is not a good idea_.
|
Read a binary file *.SRS (Solar Radio Spectrograph)
Question: I wanna read a binary file (K7120127.SRS) with caractristhics detailed in the
word file (Documentacion SRS DATA.doc) ,2.2. chapter, that adding in the next
link
[https://drive.google.com/folderview?id=0B_NlxFaQkpgHb00yTm5kU0MyaUU&usp=sharing](https://drive.google.com/folderview?id=0B_NlxFaQkpgHb00yTm5kU0MyaUU&usp=sharing)
In the link is included a viewer of that data (Srsdisp.exe), but i wanna
process this data not only view it, that's why I'd want to read it in Python.
I know plot using matplotlib, but work with binary files is new for me. I 'd
wanna plot something like this (That plot was made using the viewer included
in the link)

Answer: Try that.
from struct import unpack
# constants from the file spec
RECORD_SIZE=826
RECORD_HEADER_SIZE=24
RECORD_ARRAY_SIZE=401
# verbosity values
VERBOSITY_ALL = 2 # print warnings and errors
VERBOSITY_ERRORS = 1 # print errors
VERBOSITY_NONE = 0 # print nothing
class SRSRecord:
"""Holds one 826 byte SRS Record."""
_site_to_name = {
1: "Palehua",
2: "Holloman",
3: "Learmonth",
4: "San Vito",
# add new site names here ..
}
def __init__(self):
self.year = None
self.month = None
self.day = None
self.hour = None
self.minute = None
self.seconds = None
self.site_number = None
self.site_name = None
self.n_bands_per_record = None
self.a_start_freq = None
self.a_end_freq = None
self.a_num_bytes = None
self.a_analyser_reference_level = None
self.a_analyser_attenuation = None
self.b_start_freq = None
self.b_end_freq = None
self.b_num_bytes = None
self.b_analyser_reference_level = None
self.b_analyser_attenuation = None
# dictionary that maps frequency in mega hertz to level
self.a_values = {}
# dictionary that maps frequency in mega hertz to level
self.b_values = {}
return
def _parse_srs_file_header(self, header_bytes, verbosity = VERBOSITY_ALL):
fields = unpack(
# General header information
'>' # (data packed in big endian format)
'B' # 1 Year (last 2 digits) Byte integer (unsigned)
'B' # 2 Month number (1 to 12) "
'B' # 3 Day (1 to 31) "
'B' # 4 Hour (0 to 23 UT) "
'B' # 5 Minute (0 to 59) "
'B' # 6 Second at start of scan (0 to 59) "
'B' # 7 Site Number (0 to 255) "
'B' # 8 Number of bands in the record (2) "
# Band 1 (A-band) header information
'h' # 9,10 Start Frequency (MHz) Word integer (16 bits)
'H' # 11,12 End Frequency (MHz) "
'H' # 13,14 Number of bytes in data record (401) "
'B' # 15 Analyser reference level Byte integer
'B' # 16 Analyser attenuation (dB) "
# Band 2 (B-band) header information
# 17-24 As for band 1
'H' # 17,18 Start Frequency (MHz) Word integer (16 bits)
'H' # 19,20 End Frequency (MHz) "
'H' # 21,22 Number of bytes in data record (401) "
'B' # 23 Analyser reference level Byte integer
'B', # 24 Analyser attenuation (dB) "
header_bytes)
self.year = fields[0]
self.month = fields[1]
self.day = fields[2]
self.hour = fields[3]
self.minute = fields[4]
self.seconds = fields[5]
# read the site number and work out the site name
self.site_number = fields[6]
if self.site_number not in SRSRecord._site_to_name.keys():
# got an unknown site number.. complain a bit..
if verbosity >= VERBOSITY_ALL:
print("Unknown site number: %s" % self.site_number)
print("A list of known site numbers follows:")
for site_number, site_name in SRSRecord._site_to_name.items():
print("\t%s: %s" % (site_number, site_name))
# then set the site name to unknown.
self.site_name = "UnknownSite"
else:
# otherwise look up the site using our lookup table
self.site_name = SRSRecord._site_to_name[self.site_number]
# read the number of bands
self.n_bands_per_record = fields[7] # should be 2
if self.n_bands_per_record != 2 and verbosity >= VERBOSITY_ERRORS:
print("Warning.. record has %s bands, expecting 2!" % self.n_bands_per_record)
# read the a record meta data
self.a_start_freq = fields[8]
self.a_end_freq = fields[9]
self.a_num_bytes = fields[10]
if self.a_num_bytes != 401 and verbosity >= VERBOSITY_ERRORS:
print("Warning.. record has %s bytes in the a array, expecting 401!" %
self.a_num_bytes)
self.a_analyser_reference_level = fields[11]
self.a_analyser_attenuation = fields[12]
# read the b record meta data
self.b_start_freq = fields[13]
self.b_end_freq = fields[14]
self.b_num_bytes = fields[15]
if self.b_num_bytes != 401 and verbosity >= VERBOSITY_ERRORS:
print("Warning.. record has %s bytes in the b array, expecting 401!" %
self.b_num_bytes)
self.b_analyser_reference_level = fields[16]
self.b_analyser_attenuation = fields[17]
return
def _parse_srs_a_levels(self, a_bytes):
# unpack the frequency/levels from the first array
for i in range(401):
# freq equation from the srs file format spec
freq_a = 25 + 50 * i / 400.0
level_a = unpack('>B', a_bytes[i])[0]
self.a_values[freq_a] = level_a
return
def _parse_srs_b_levels(self, b_bytes):
for i in range(401):
# freq equation from the srs file format spec
freq_b = 75 + 105 * i / 400.0
level_b = unpack('>B', b_bytes[i])[0]
self.b_values[freq_b] = level_b
return
def __str__(self):
return ("%s/%s/%s, %s:%s:%s site: %s/%s bands: %s "
"[A %s->%s MHz ref_level: %s atten: %s dB], "
"[B %s->%s MHz ref_level: %s atten: %s dB]"
)% (
self.day, self.month, self.year,
self.hour, self.minute, self.seconds,
self.site_number, self.site_name,
self.n_bands_per_record,
self.a_start_freq, self.a_end_freq,
self.a_analyser_reference_level, self.a_analyser_attenuation,
self.b_start_freq, self.b_end_freq,
self.b_analyser_reference_level, self.b_analyser_attenuation,
)
def _dump(self, values):
freqs = values.keys()
freqs.sort()
for freq in freqs:
print "%5s %s" % (freq, values[freq])
return
def dump_a(self):
self._dump(self.a_values)
return
def dump_b(self):
self._dump(self.b_values)
return
def read_srs_file(fname):
"""Parses an srs file and returns a list of SRSRecords."""
# keep the records we read in here
srs_records = []
f = open(fname, "rb")
while True:
# read raw record data
record_data = f.read(RECORD_SIZE)
# if the length of the record data is zero we've reached the end of the data
if len(record_data) == 0:
break
# break up the record bytes into header, array a and array b bytes
header_bytes = record_data[:RECORD_HEADER_SIZE]
a_bytes = record_data[RECORD_HEADER_SIZE : RECORD_HEADER_SIZE + RECORD_ARRAY_SIZE]
b_bytes = record_data[RECORD_HEADER_SIZE + RECORD_ARRAY_SIZE :
RECORD_HEADER_SIZE + 2 * RECORD_ARRAY_SIZE]
# make a new srs record
record = SRSRecord()
record._parse_srs_file_header(header_bytes, verbosity = VERBOSITY_ERRORS)
record._parse_srs_a_levels(a_bytes)
record._parse_srs_b_levels(b_bytes)
srs_records.append(record)
return srs_records
if __name__ == "__main__":
# parse the file.. (this is where the magic happens ;)
srs_records = read_srs_file(fname = "K7120127.SRS")
# play with the data
for i in range(3):
print srs_records[i]
r0 = srs_records[0]
r0.dump_a()
r0.dump_b()
|
Can't get hello world in django
Question: I tried writing the hello world program in django but i get didn't get the
expected outcome. Please help- 2nd day stuck here. My Python version 2.7.
Django 1.6.2
**Directory list:**
1. mysite
* manage.py
* mysite
* _init_.py
* _init.pyc
* settings.py
* settings.pyc
* urls.py
* urls.pyc
* wsgi.py
* wsgi.pyc
* views.py
**1\. Code in Views file**
from django.http import HttpResponse
def hello(request):
return HttpResponse(“hello world”)
**2\. Code in urls file**
from django.conf.urls import patterns, include, url
from mysite.views import hello
#from django.contrib import admin
#admin.autodiscover()
#urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
#url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'mysite.views.hello’, name=‘hello’)
)
**SyntaxError at "":**
Exception Value:
Non-ASCII character '\xe2' in file /Users/**_*_ ***/_*_
*/djcode/mysite/mysite/urls.py on line 16, but no encoding declared; see
<http://www.python.org/peps/pep-0263.html> for details (urls.py, line 16)
[please note: asterisk used to hide the path above]
Answer: You are using different characters:
`url(r'^$', 'mysite.views.hello’, name=‘hello’)`
should be:
`url(r'^$', 'mysite.views.hello', name='hello')`
so to clarify `’` should be `'` in that line of code.
|
MySQLdb windows create database
Question: I am trying to create a `MySQL database` in `python`.
I am using `MySQL db`.
Currently, here is what I do:
import MySQLdb
db1 = MS.connect(host="localhost",user="root",passwd="****")
Everywhere I go it seems that everybody assumes that you know how to create a
database, but I do not. As you could guess when I run the above code I get an
error, and I assume it is because I have not created a database.
How do I create a database?
Answer: You can use SQL on the commandline/terminal:
$ echo 'CREATE DATABASE <dbname>;' | mysql -u <username> -p
where
* `<dbname>` : Name for New Database,
* `<username>` : is your mysql username.
Also you need to type your mysql `<password>` when prompted.
OR:
you can also use: `mysql -u <username> -p -e "create database <dbname>";`
|
Reportlab error: 'Table' object has no attribute '_colpositions'
Question: I'm trying to teach myself reportlab from the user guide. The document I need
to create is just formatted text that needs to go in specific places on the
page. In the following snippets, table_data is a list containing 3 strings. I
imported Table as pdfTable because my application has a Table class.
First, I tried this:
top_row = pdfTable(table_data, colWidths=(3*inch, 3*inch, inch))
That gave me this error:
Traceback:
File "C:\Python33\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:/Users/Phoenix/PycharmProjects/gamecon\gameconapp\views\utilities.py" in splash_page
86. generate_signup_sheets()
File "C:/Users/Phoenix/PycharmProjects/gamecon\gameconapp\views\utilities.py" in generate_signup_sheets
354. top_row = pdfTable(table_data, colWidths=(3*inch, 3*inch, inch))
File "C:\Python33\lib\site-packages\reportlab-3.0-py3.3-win-amd64.egg\reportlab\platypus\tables.py" in __init__
253. raise ValueError("%s data error - %d columns in data but %d in column widths" % (self.identity(),ncols, len(colWidths)))
File "C:\Python33\lib\site-packages\reportlab-3.0-py3.3-win-amd64.egg\reportlab\platypus\tables.py" in identity
332. v = cv[i][j]
Exception Type: IndexError at /index.html
Exception Value: list index out of range
Since it looked like the problem was the column widths, and the docs say that
colWidths is optional, I tried this:
top_row = pdfTable(table_data)
Which caused this error:
Traceback:
File "C:\Python33\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:/Users/Phoenix/PycharmProjects/gamecon\gameconapp\views\utilities.py" in splash_page
86. generate_signup_sheets()
File "C:/Users/Phoenix/PycharmProjects/gamecon\gameconapp\views\utilities.py" in generate_signup_sheets
355. top_row.drawOn(p, 0.75*inch, 0.5*inch)
File "C:\Python33\lib\site-packages\reportlab-3.0-py3.3-win-amd64.egg\reportlab\platypus\flowables.py" in drawOn
110. self._drawOn(canvas)
File "C:\Python33\lib\site-packages\reportlab-3.0-py3.3-win-amd64.egg\reportlab\platypus\flowables.py" in _drawOn
91. self.draw()#this is the bit you overload
File "C:\Python33\lib\site-packages\reportlab-3.0-py3.3-win-amd64.egg\reportlab\platypus\tables.py" in draw
1363. self._drawBkgrnd()
File "C:\Python33\lib\site-packages\reportlab-3.0-py3.3-win-amd64.egg\reportlab\platypus\tables.py" in _drawBkgrnd
1386. colpositions = self._colpositions
Exception Type: AttributeError at /index.html
Exception Value: 'Table' object has no attribute '_colpositions'
None of the examples in the reportlab documentation show Table actually being
used.
Thanks in advance for any help.
Edited to add executable code that's still failing:
import os
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.platypus import Table as pdfTable
filename = os.path.join(BASE_DIR, 'pdf_test_%s.pdf' %
( datetime.now().strftime('%d-%b-%Y %H-%M')))
p = canvas.Canvas(filename, pagesize=letter, bottomup=1)
table_data = [['a', 'b', 'c'], ['d', 'e', 'f']]
top_row = pdfTable([table_data]) #, colWidths=(3*inch, 3*inch, inch))
top_row.drawOn(p, 0.75*inch, 0.5*inch)
p.showPage()
p.save()
Answer: I think the problem is that your just passing a list. `Table` wants to have a
list of lists e.g. a 2D-Array. From the user-guide:
> The data argument is a sequence of sequences of cell values each of which
> should be convertible to a string value using the str function or should be
> a Flowable instance (such as a Paragraph) or a list (or tuple) of such
> instances.
If you just have one row, encapsulate that row into another list and pass that
to Table. If this doesn't work, please post a minimal and also executable code
example.
P.S. On page 77 of the user guide is a straightforward example of the
`Table`-class
**UPDATE** Now i see. You are using a `Flowable` which is normally supposed to
go through platypus layout-engine by using it in combination with a
`DocTemplate`. This is explained in detail in Chapter 5. You are using the
_manual_ way by drawing directly to a canvas, so you also have to code your
"own" layout-engine. In this case you first have to use the `wrapOn` method of
your `Table`. I don't really know why, but it doesn't seem to matter what
sizes you pass as arguments. If it doesn't work, try to play with the values.
Here is my adjusted version of your code:
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.platypus import Table as pdfTable
filename = 'pdf_test.pdf'
p = canvas.Canvas(filename)
table_data = [['a', 'b', 'c'], ['d', 'e', 'f']]
top_row = pdfTable(table_data)
w, h = top_row.wrapOn(p, 0, 0)
top_row.drawOn(p, 0.75*inch, 0.5*inch)
p.showPage()
p.save()
|
Pythonic way to simple array handling
Question:
import numpy as np
data = np.array([[2,0,1,2,0],[0,1,2,0,1],[2,0,1,2,2]])
I require the following threes as separate variables
class0 = np.where(data==0)
class1 = np.where(data==1)
class2 = np.where(data==2)
I knew how to write them in three lines as above. However, what is the
Pythonic way to do it using the examples below:
classes = ['class0', 'class1', 'class2']
values =[0,1,2]
for x, y in zip(classes, values):
x = np.where(data == y)
print x
HERE how can I name the answers resulted by x as class0,class1,class2???
Answer: Dictionary:
classes = ['class0', 'class1', 'class2']
values =[0,1,2]
output = {} #create a dictionary instance
for x, y in zip(classes, values):
output[x] = np.where(data == y) #use the class name as the dictionary key
|
multiply string element per int element from two arrays Java
Question: I am learning Java and looking for a comprehensive code of multiplying the
elements from 2 arrays, possibly without importing anything to achieve it.
In Python it's quite easy:
a=['a','b','c','d']
b=[1,2,3,4]
[x*y for x,y in zip(a,b)]
['a', 'bb', 'ccc', 'dddd']
How can I achieve the same thing in Java, when the first array is an array of
strings and the second is integers?
Answer: I'm afraid Java isn't going to support this kind of thing natively, and you'll
need to perform some of your own logic to implement it. Let's say you've got
your `String[]`..
String[] a = {"a", "b", "c", "d"};
And you've got your `int[]`..
int[] b = {1,2,3,4};
Next, you'll need to check that the arrays are the same size.
if(a.length == b.length) {
// Continue.
}
Then you need to implement a loop, to go through each item in the arrays.
for(int x = 0; x < a.length; x++)
{
// Some looping code.
}
And you're going to grab each item.
String value = a[x];
int multiplier = b[x];
If you're not importing anything, you declare the total value:
String total = "";
But if you're allowing for a `StringBuilder`, then you'll import it and
declare..
StringBuilder total = new StringBuilder();
_**NOTE:_** StringBuilder is strongly recommended here.
And then you're looping `multiplier` amount of times..
for(int y = 0; y < multiplier; y++)
{
// If you use StringBuilder..
total.append(value);
// If you don't..
total += value;
}
// If you use StringBuilder..
a[x] = total.toString();
// If you don't...
a[x] = total;
This will set the value of `a[x]` to the repeated `String`.
_**NOTE_** : Something that's also important is leaning good practise. If
you're using Java code, it's considered terrible practise to repeatedly
concatenate `String` objects. `StringBuilder` is more efficient, and is the
Java standard. I would strongly recommend using this.
Have fun putting it all together!!
|
Exceptions are not handled in assertRaise()
Question: I am having trouble and difficulties with Pilgrim's Dive into python 3 Unit
Testing chapter. I've run the exact same code in romantest2.py. Exceptions are
not being handled in the code provided on the examples. I have deduced the
example on the book into a smaller snippet:
TestCase1.py
import unittest
class ToRomanBadInput(unittest.TestCase):
def test_too_large(self):
'''to_roman should fail with large input'''
self.assertRaises(roman2.OutOfRangeError,roman2.to_roman,4000)
if __name__ == '__main__':
unittest.main()
the file roman2.py
class OutOfRangeError(ValueError):
pass
def to_roman(n):
raise OutOfRangeError("Value n {0} is larger than 3999.".format(n))
I can't seem to move on this part. What happen is that I expect the test case
to fail. But it didn't instead it shows:
..
------------------------------------------------------------
Ran 2 tests in 0.000s
OK
I am using and running this code PyDev in Eclipse and the version of python is
version 3.3.3
Answer: You are asserting that the `to_roman()` function raises an exception. **That
test succeeds** , your function indeed raises the exception.
|
How to extract character ngram from sentences? - python
Question: The following `word2ngrams` function extracts character 3grams from a word:
>>> x = 'foobar'
>>> n = 3
>>> [x[i:i+n] for i in range(len(x)-n+1)]
['foo', 'oob', 'oba', 'bar']
This post shows the character ngrams extraction for a single word, [Quick
implementation of character n-grams using
python](http://stackoverflow.com/questions/18658106/quick-implementation-of-
character-n-grams-using-python).
But what if i have sentences and i want to extract the character ngrams, **is
there a faster method other than iteratively call the`word2ngram()`**?
**What will be the regex version of achieving the same`word2ngram` and
`sent2ngram` output? would it be faster?**
I've tried:
import string, random, time
from itertools import chain
def word2ngrams(text, n=3):
""" Convert word into character ngrams. """
return [text[i:i+n] for i in range(len(text)-n+1)]
def sent2ngrams(text, n=3):
return list(chain(*[word2ngrams(i,n) for i in text.lower().split()]))
def sent2ngrams_simple(text, n=3):
text = text.lower()
return [text[i:i+n] for i in range(len(text)-n+1) if not " " in text[i:i+n]]
# Generate 10000 random strings of length 100.
sents = [" ".join([''.join(random.choice(string.ascii_uppercase) for j in range(10)) for i in range(100)]) for k in range(100)]
start = time.time()
x = [sent2ngrams(i) for i in sents]
print time.time() - start
start = time.time()
y = [sent2ngrams_simple(i) for i in sents]
print time.time() - start
print x==y
[out]:
0.0205280780792
0.0271739959717
True
**EDITED**
The regex method looks elegant but it performs slower than iteratively calling
`word2ngram()`:
import string, random, time, re
from itertools import chain
def word2ngrams(text, n=3):
""" Convert word into character ngrams. """
return [text[i:i+n] for i in range(len(text)-n+1)]
def sent2ngrams(text, n=3):
return list(chain(*[word2ngrams(i,n) for i in text.lower().split()]))
def sent2ngrams_simple(text, n=3):
text = text.lower()
return [text[i:i+n] for i in range(len(text)-n+1) if not " " in text[i:i+n]]
def sent2ngrams_regex(text, n=3):
rgx = '(?=('+'\S'*n+'))'
return re.findall(rgx,text)
# Generate 10000 random strings of length 100.
sents = [" ".join([''.join(random.choice(string.ascii_uppercase) for j in range(10)) for i in range(100)]) for k in range(100)]
start = time.time()
x = [sent2ngrams(i) for i in sents]
print time.time() - start
start = time.time()
y = [sent2ngrams_simple(i) for i in sents]
print time.time() - start
start = time.time()
z = [sent2ngrams_regex(i) for i in sents]
print time.time() - start
print x==y==z
[out]:
0.0211708545685
0.0284190177917
0.0303599834442
True
Answer: Why not just `(?=(...))`
**edit** Same thing, but not whitespace `(?=(\S\S\S))`
**edit2** You can use just what you want as well. Ex. uses alphanum only
`(?=([^\W_]{3}))`
Uses a lookahead to capture 3 characters. Then the engine bumps the position
up 1 time each
match. Then captures next 3.
Result of `foobar` is
foo
oob
oba
bar
# Compressed regex
# (?=(...))
# Expanded regex
(?= # Start Lookahead assertion
( # Capture group 1 start
. # dot - metachar, matches any character except newline
. # dot - metachar
. # dot - metachar
) # Capture group 1 end
) # End Lookahead assertion
|
inspect.isfunction doesn't work for all modules?
Question: I'm attempting to use the answer to [Is it possible to list all functions in a
module?](http://stackoverflow.com/questions/4040620/is-it-possible-to-list-
all-functions-in-a-module) to list functions in a range of modules. But in my
interpreter I get as follows:
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> import math
>>> math.pow(5,4)
625.0
>>> inspect.getmembers(math, inspect.isfunction)
[]
>>> inspect.getmembers(inspect, inspect.isfunction)
[('_check_class', <function _check_class at 0x00C9F9C0>), ('_check_instance', <f
unction _check_instance at 0x00C9F978>), ('_get_user_defined_method', <function
_get_user_defined_method at 0x00C9FB70>), ('_getfullargs', <function _getfullarg
s at 0x00C6A4F8>), ('_is_type', <function _is_type at 0x00C9FA08>), ('_missing_a
rguments', <function _missing_arguments at 0x00C9F198>), ('_shadowed_dict', <fun
ction _shadowed_dict at 0x00C9FA50>)... foo, bar, etc]
>>> math
<module 'math' (built-in)>
>>> inspect
<module 'inspect' from 'E:\\Python33\\lib\\inspect.py'>
>>> import win32api
>>> inspect.getmembers(win32api, inspect.isfunction)
[]
>>> win32api
<module 'win32api' from 'E:\\Python33\\lib\\site-packages\\win32\\win32api.pyd'>
As per usual, I assume there's some blindingly obvious reason as to why this
is failing to list all functions in half the modules I try. The best I can
guess is isfunction() only works for .py modules? If there is an innate
problem not related to my stupidity, is there a way to rectify this matter?
It's clearly an issue with the isfunction(), as getmembers seems to work fine:
>>> import math
>>> import inspect
>>> inspect.getmembers(math)
[('__doc__', 'This module is always available. It provides access to the\nmathe
matical functions defined by the C standard.'), ('__loader__', <class '_frozen_i
mportlib.BuiltinImporter'>), ('__name__', 'math'), ('__package__', ''), ('acos',
<built-in function acos>), ('acosh', <built-in function acosh>), ('asin', <buil
t-in function asin>)... foo, bar, etc]
I understand there's a dir() which can be used, but it's not really quite as
neat.
Answer: C-defined functions are not instances of the user-defined `function` type;
they are defined in C instead, for which you _could_ use
[`inspect.isbuiltin()`](http://docs.python.org/2/library/inspect.html#inspect.isbuiltin).
The fool-proof method to list all functions in modules is to use
[`inspect.isroutine()`](http://docs.python.org/2/library/inspect.html#inspect.isroutine)
instead:
> Return true if the object is a user-defined or built-in function or method.
Demo on the `math` module:
>>> import inspect
>>> import math
>>> inspect.getmembers(math, inspect.isroutine)
[('acos', <built-in function acos>), ('acosh', <built-in function acosh>), ('asin', <built-in function asin>), ('asinh', <built-in function asinh>), ('atan', <built-in function atan>), ('atan2', <built-in function atan2>), ('atanh', <built-in function atanh>), ('ceil', <built-in function ceil>), ('copysign', <built-in function copysign>), ('cos', <built-in function cos>), ('cosh', <built-in function cosh>), ('degrees', <built-in function degrees>), ('erf', <built-in function erf>), ('erfc', <built-in function erfc>), ('exp', <built-in function exp>), ('expm1', <built-in function expm1>), ('fabs', <built-in function fabs>), ('factorial', <built-in function factorial>), ('floor', <built-in function floor>), ('fmod', <built-in function fmod>), ('frexp', <built-in function frexp>), ('fsum', <built-in function fsum>), ('gamma', <built-in function gamma>), ('hypot', <built-in function hypot>), ('isinf', <built-in function isinf>), ('isnan', <built-in function isnan>), ('ldexp', <built-in function ldexp>), ('lgamma', <built-in function lgamma>), ('log', <built-in function log>), ('log10', <built-in function log10>), ('log1p', <built-in function log1p>), ('modf', <built-in function modf>), ('pow', <built-in function pow>), ('radians', <built-in function radians>), ('sin', <built-in function sin>), ('sinh', <built-in function sinh>), ('sqrt', <built-in function sqrt>), ('tan', <built-in function tan>), ('tanh', <built-in function tanh>), ('trunc', <built-in function trunc>)]
Note the `built-in` part of the string representation of each function object.
`isroutine()` returns true if one of
[`inspect.isbuiltin()`](http://docs.python.org/2/library/inspect.html#inspect.isbuiltin),
[`inspect.isfunction()`](http://docs.python.org/2/library/inspect.html#inspect.isfunction),
[`inspect.ismethod()`](http://docs.python.org/2/library/inspect.html#inspect.ismethod)
or
[`inspect.ismethoddescriptor()`](http://docs.python.org/2/library/inspect.html#inspect.ismethoddescriptor)
returns True.
|
How to read an untrusted certificate to extract informations using Python?
Question: I know it's possible to read a certificate in Python by using either OpenSSL
or M2Crypto, as greatly explained at [How can I retrieve the SSL certificate
information for a connection whether it's self-signed or not using
python?](http://stackoverflow.com/questions/7689941/how-can-i-retrieve-the-
ssl-certificate-information-for-a-connection-whether-its), but I'd like to be
able to do the same, with a non trusted certificate.
By non trusted, I mean a certificate I (for example) just generated and paster
the csr output into my python function.
Here's how I generated the csr :
openssl req -new -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr
And used the output of domain.csr into the code in the S.O. question before.
As expected, this doesn't work. To be quicker, doing the same using Openssl
result in the same error :
openssl x509 -text -in Domain.csr -noout
> unable to load certificate 139698977908608:error:0906D06C:PEM
> routines:PEM_read_bio:no start >line:pem_lib.c:703:Expecting: TRUSTED
> CERTIFICATE
**Expecting: TRUSTED CERTIFICATE** is the key issue here.
How can I do ?
Thank you for your help !
**Update :** By searching more, I read that this would work if the PRIVATE KEY
was inside the cert (aka pem) from this S.O answer
<http://stackoverflow.com/a/12312994/330867>, but what I'm trying to implement
is a system that can extract informations from certificates that come from
other people than mine. And I'm pretty sure "other people" won't want to share
their private key, so I remain stuck. Any ideas ?
**Update 2:** It appears that there is a difference between x509 and req
certificates. The one generated with the command before is a req, as stated.
So now I now I can read a x509 certificate with the first SO link, but how can
I read a req certificate in python ?
Answer: Ok I found my answer and I believe it will help others !
So, there is an important difference between a "req" certificate and a x509
certificate!
In the x509, the Private Key is also included in the file !
So, in the following, I'll show how to generate a certificate and read it in
Python, using REQ and x509 type of certificate.
**Using a "req" certificate :**
To generate it :
openssl req -new -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr
And to read it :
import OpenSSL
# cert contains the content of domain.csr
OpenSSL.crypto.load_certificate_request(OpenSSL.crypto.FILETYPE_PEM, cert).get_subject().get_components()
**Using a "x509" certificate :**
To generate it :
openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
And to read it :
import OpenSSL
# cert contains the content of cert.pem
OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert).get_subject().get_components()
That's it !
The difference is located in how you load the certificate in `OpenSSL.crypto`
:
* For "req" : `load_certificate_request()`
* For "x509" : `load_certificate()`
It was that simple ;)
|
Python program returning error I cannot seem to fix
Question: I began this code by using a while loop to establish the menu (line 19-40) and
it worked perfectly before adding the functions and import at the top. Now it
keeps throwing back an indentation error at line 19 and none of my attempts
other than removing all the functions seem to fix this problem. Any chance I
overlooked something?
import string
def encrypt(input_val):
en_key = input("Enter the number to shift by:")
var = to_encrypt.upper()
for char in var:
shift = ord(char) + en_key
encrypted += chr(shift)
return encrypted.upper()
def decrypt(input_val):
de_key = input("Enter the number to shift by:")
var = to_decrypt.upper()
for char in var:
shift = ord(char) - de_key
decrypted += chr(shift)
return decrypted.upper()
def crack(input_val):
program_on = True
while program_on == True:
print("Please select from the following options:\n \t1. Encrypt A Message\n \t2. Decrypt A Message\n \t3. Attempt To Crack A Message\n \t4. Quit")
user_choice = input("Enter Your Choice: ")
if user_choice == "1":
to_encrypt = input("Enter message to encrypt:")
encrypt(to_encrypt)
program_on = True
elif user_choice == "2":
to_decrypt = input("Enter encrypted message:")
decrypt(to_decrypt)
program_on = True
elif user_choice == "3":
to_crack = input("Enter encrypted message:")
crack(to_crack)
program_on = True
elif user_choice == "4":
print("Goodbye")
program_on = False
else:
print("Give a valid response")
program_on = True
Answer: Seems to work now.
def crack(input_val):
pass
You can't define an empty function.
|
Python - Convert time to different time zone with am/pm
Question: In Python, using this function (takes Eastern Standard Time (EST) with am/pm,
should output it in 3 time formats. Central Time (CT), Mountain Time(MT), and
Pacific Time(PT) all in the correct am/pm):
def time_in_24h(time,time_day): #time is eastern time
''' (number, str)--> number
This function converts a 12-hour time, represented by am/pm,to its equivalent 24-hour time.
Returns time in the 24-hour format.
'''
cCentral = 'Central Time(CT)' #-1 hour offset
mMountain = 'Mountain Time(MT)'#-2 hours offset
pPacific = 'Pacific Time(PT)'#-3 hours offset
eEst = 'EST is'
if time_day!='pm' and time_day!='am':
print('Input is not in the right format') #this is where input is not in the right format
return 0
else:
print(time, time_day, eEst, time-1, cCentral)
print(time, time_day, eEst, time-2, mMountain)
print(time, time_day, eEst, time-3, pPacific)
Using this command:
time_in_24h(7,'am')
I get this output:
7 am EST is 6 Central Time(CT)
7 am EST is 5 Mountain Time(MT)
7 am EST is 4 Pacific Time(PT)
I am trying to output the correct 3 times based on the input of EST,am/pm to
Central Time (CT), Mountain Time(MT), and Pacific Time(PT) all in the correct
am/pm. How can I get the correct am/pm outputted based on the offsets? For
example, 2pm EST input, should output:
1 pm EST is 12 pm Central Time(CT)
1 pm EST is 11 am Mountain Time(MT)
1 pm EST is 10 am Pacific Time(PT)
As you see, pm/am change based on the offsets and it is not consistent. What
would be the best way to handle this as it varies based on the time (am/pm)?
Anything built in python already to handle this without an issue? Any solution
to my dilemma? I gave it my all and really stuck on this one.
Answer: If you are talking about timezones then you must specify a date (year, month,
day) in addition to the time.
To convert given `hours` and `am_or_pm` to a different timezone:
1. convert to 24 hours
2. add date
3. create timezone-aware datetime object in the source timezone
4. convert it to the given timezones
`time_in_24h` shouldn't try to do too much. Let it do what its name implies,
namely: convert input hours, am or pm to 24 hours format:
def time_in_24h(hours, am_or_pm):
"""Convert to 24 hours."""
if not (1 <= hours <= 12):
raise ValueError("hours must be in 01,..,12 range, got %r" % (hours,))
hours %= 12 # accept 12am as 00, and 12pm as 12
am_or_pm = am_or_pm.lower()
if am_or_pm == 'am':
pass
elif am_or_pm == 'pm':
hours += 12
else:
raise ValueError("am_or_pm must be 'am' or 'pm', got: %r" % (am_or_pm,))
return hours
You could also implement it using `strptime()`:
from datetime import datetime
def time_in_24h(hours, am_or_pm):
return datetime.strptime("%02d%s" % (hours, am_or_pm), '%I%p').hour
Then you could define `print_times()` function that prints times in the 3
different timezones:
from datetime import datetime, time
import pytz
def astimezone(aware_dt, dest_tz):
"""Convert the time to `dest_tz` timezone"""
return dest_tz.normalize(aware_dt.astimezone(dest_tz))
def print_times(hours, am_or_pm, date=None, is_dst=None):
source_tz = pytz.timezone('US/Eastern')
# 2. add date
if date is None: # if date is not specified; use today
date = datetime.now(source_tz).date()
naive_dt = datetime.combine(date, time(time_in_24h(hours, am_or_pm), 0, 0))
# 3. create timezone-aware datetime object in the source timezone
source_dt = source_tz.localize(naive_dt, is_dst=is_dst)
#NOTE: these timezone names are deprecated,
# use Continent/City format instead
fmt = '%I %p %Z'
for tzname in 'US/Central', 'US/Mountain', 'US/Pacific':
dest_dt = astimezone(source_dt, pytz.timezone(tzname))
print("{source_dt:{fmt}} is {dest_dt:{fmt}} ({tzname})".format(
**locals()))
It is important to specify the date correctly, otherwise you won't know the
correct UTC offset. The code uses `pytz` module to access timezone
information. [`strftime()` format
codes](http://docs.python.org/2/library/datetime.html#strftime-strptime-
behavior) are used for printing.
Example:
>>> print_times(7, 'am')
07 AM EDT is 06 AM CDT (US/Central)
07 AM EDT is 05 AM MDT (US/Mountain)
07 AM EDT is 04 AM PDT (US/Pacific)
>>> print_times(1, 'pm')
01 PM EDT is 12 PM CDT (US/Central)
01 PM EDT is 11 AM MDT (US/Mountain)
01 PM EDT is 10 AM PDT (US/Pacific)
>>> print_times(9, 'pm')
09 PM EDT is 08 PM CDT (US/Central)
09 PM EDT is 07 PM MDT (US/Mountain)
09 PM EDT is 06 PM PDT (US/Pacific)
Special note:
* `datetime.now(source_tz)` allows to get the correct current time in the given timezone. `datetime.now()` would be incorrect here if the local timezone is not `source_tz`
* `is_dst=None` means that `tz.localize()` method raises an exception for ambiguous or non-existing local times. Otherwise it just defaults to `is_dst=False` that might not be what you want
* `tz.normalize()` might be necessary if the conversion happens across DST boundary
|
Python count substrings
Question: How do I find how many times does substring appears in string? I have
molecular formula and if the letters are uppercase it is one element(e.g.H),
if it has first Upper case letter and second lower case than it is one
element(e.g.Ba), and if there is number after element i have to add that
number to elment
example: input : Ba4H2Ba5Li3
if i search Ba it should print number 9(i have Ba4 and Ba5, that is 9), if i
search H it should print 2(one letter H but number 2 after it), and Li it
should print number 3.
Answer: You can use Regular Expression, like this
data = "Ba4H2Ba5Li3"
import re
result = {}
for element, count in re.findall(r"([A-Z][a-z]?)(\d*)", data):
result[element] = result.get(element, 0) + int(1 if count == "" else count)
print result
# {'H': 2, 'Ba': 9, 'Li': 3}
Now, you can get the count of each items from the `result`, like this
print result.get("Ba", 0)
# 9
print result.get("H", 0)
# 2
print result.get("Li", 0)
# 3
print result.get("Sa", 0)
# 0
|
How to call a method from an already running python script
Question: I need to check if the python script is already running then calling a method
from the same running python script. But it must be on same process(pid), no
new process. Is this possible?
I tried some codes but not worked.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Tkinter as tk
from Tkinter import *
import socket
class Main():
def mainFunc(self):
self.root = tk.Tk()
self.root.title("Main Window")
self.lbl = Label(self.root, text = "First Text")
self.lbl.pack()
openStngs = Button(self.root, text = "Open Settings", command=self.settingsFunc)
openStngs.pack()
def settingsFunc(self):
stngsRoot = Toplevel()
stngsRoot.title("Settings Window")
changeTextOfLabel = Button(stngsRoot, text = "Change Main Window Text", command=self.change_text)
changeTextOfLabel.pack()
def change_text(self):
self.lbl.config(text="Text changed")
# the get_lock from http://stackoverflow.com/a/7758075/3254912
def get_lock(process_name):
lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
try:
print lock_socket
lock_socket.bind('\0' + process_name)
print 'I got the lock'
m.mainFunc()
mainloop()
except socket.error:
print 'lock exists'
m.settingsFunc()
mainloop()
# sys.exit()
if __name__ == '__main__':
m=Main()
get_lock('myPython.py')
Answer: You either need:
* A proactive check in your running process to look at the environment (for instance, the contents of a file or data coming through a socket) to know when to fire the function,
* or for your running process to receive unix signals or some other IPC (possibly one of the user-defined signals) and perform a function when one is received.
Either way you can't just reach into a running process and fire a function
inside that process (it MIGHT not be literally impossible if you hook the
running process up to a debugger, but I wouldn't recommend it).
`Tkinter` necessarily has its own event loop system, so I recommend reading up
on how that works and how to either run something on a timer in that event
loop system, or set up a callback that responds to a signal. You could also
wrap a non-event loop based system in a try/except block that will catch an
exception generated by a UNIX signal, but it may not be straightforward to
resume the operation of the rest of the program after that signal is caught,
in that case.
|
Creating radio buttons from a list in python?
Question: The code below creates a check button for each item in the list:
cb_strings = ['item 1', 'item 2', 'item 3', 'item 4']
self.check_btns = []
for i in range(len(cb_strings)):
v = StringVar()
self.check_btns.append(Checkbutton(parent, width = 20, variable = v, anchor = W, onvalue = cb_strings[i], offvalue = '*', text = cb_strings[i] , command = self.display_selections))
self.check_btns[i].var = v
self.check_btns[i].deselect()
self.check_btns[i].pack()
Could you show me how to do a similar thing, but to create radio buttons
instead?
Thanks in advance :)
Answer: Here's an example:
from Tkinter import *
cb_strings = ['item 1', 'item 2', 'item 3', 'item 4']
def sel():
print "You selected the option " + str(var.get())
root = Tk()
var = StringVar()
var.set(cb_strings[0])
for item in cb_strings:
button = Radiobutton(root, text=item, variable=var, value=item, command=sel)
button.pack(anchor=W)
root.mainloop()
Also see [example from "An Introduction to
Tkinter"](http://effbot.org/tkinterbook/radiobutton.htm).
|
How to dump http request in python
Question: I am using http in my application.
request = urllib2.Request(url, postdata)
Is possible to get dump of this request on client side (after this line) ?
I need exactly what is sent to server (TCP dump ?), so
POST url HTTP/version\r\nHeaderKey: HeaderValue\r\n....
Answer: > Is possible to get dump of this request on client side (after this line) ? I
> need exactly what is sent to server (TCP dump ?)
you are looking for a log at the tcp layer, but you haven't actually sent
anything over the wire via tcp?
All you did was create a Request object.
If you were to send the request you created, you could enable debug in a
handler and view headers/data both sent and received:
import httplib
import urllib
import urllib2
url = 'http://example.com'
headers = {'HeaderKey': 'HeaderValue'}
data = urllib.urlencode({})
request = urllib2.Request(url, headers=headers, data=data)
handler = urllib2.HTTPHandler()
handler.set_http_debuglevel(1)
opener = urllib2.build_opener(handler)
response = opener.open(request)
response.read()
response.close()
ouput:
send: 'POST / HTTP/1.1\r\nAccept-Encoding: identity\r\nContent-Length: 0\r\nHost: example.com\r\nUser-Agent: Python-urllib/2.7\r\nConnection: close\r\nContent-Type: application/x-www-form-urlencoded\r\nHeaderkey: HeaderValue\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
[snip]
|
Python urllib2 with headers not working
Question: I am trying to scrape a page for a certain url and I am using BeautifulSoup to
do so, with a request from urllib2. The problem I am having right now is that
it sends a different url to my python client than my browser. So I went around
and had a look at the header requests and tried my best to imitate them to
make it appear as though my python client is a real browser to no avail.
Basically:
Browser: ThisIsARealUrlToDocuments.doc Python: ThisIsADummyForNonHumans.doc
I should also mention that if I refresh the url in my browser then run the
python script it downloads successfully a single time, then it will give me
the dummy until I refresh the page.
I'm not exactly a veteran at anything web so help would be appreciated.
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
req.add_header('Referer', url_to_open)
soup = BeautifulSoup(urllib2.urlopen(req).read()
# Dummy video url always contains 779de9061
if '779de9061' in soup.find("div", {'id':'divDownload'}).a['href']:
return "Failed to get valid video link."
# Returns the found video link
return soup.find("div", {'id':'divDownload'}).a['href']
The page I'm trying to scrape is any page with video here:
<http://kissanime.com/Anime/Neon-Genesis-Evangelion/Episode-026?id=5260>
Right now I'm using a hacky method of just loading their page quickly in a
native browser then downloading, as it seems to grant me one single non dummy
download per pageload.
Answer: When I try the URL provided with `curl`, I get
$ curl --silent "http://kissanime.com/Anime/Neon-Genesis-Evangelion/Episode-026?id=5260" | grep "divDownload"
<div style="font-size: 14px; font-weight: bold; padding-top: 15px" id="divDownload">
So it doesn't look like anything weird happening from my location...
Why not look at [PyQuery](https://pypi.python.org/pypi/pyquery)?
>>> from pyquery import PyQuery
>>> doc = PyQuery('http://kissanime.com/Anime/Neon-Genesis-Evangelion/Episode-026?id=5260')
>>> print doc.find('#divDownload a')[0].attrib['href']
http://redirector.googlevideo.com/videoplayback?id=779de9061bfeb5d6&itag=37&source=picasa&cmo=sensitive_content=yes&ip=0.0.0.0&ipbits=0&expire=1397587987&sparams=id,itag,source,ip,ipbits,expire&signature=45A93E092F1750C81437ED7F0A5EEB5ABFCD5611.D30926273240E4116B91E85D59FF1268D0E5D5A1&key=lh1
|
Scrollbar not functioning properly Tkinter
Question: I am a newbie to Python.
I am trying to create a Scrollbar, which I did but the scrollbar is not
functioning properly.
The frame already shows all labels but what I expected was the frame will only
show up to 5 labels
and if frame contains more than 5 labels, then the scrollbar will function to
show the unseen remaining labels.
Any help?
Code:
from Tkinter import *
class GUI():
def __init__(self):
root=Tk()
frame=Frame(root,width=300,height=300)
frame.grid(row=0,column=0)
self.canvas=Canvas(frame,bg='#FFFFFF',width=300,height=300,scrollregion=(0,0,500,500))
Label(self.canvas,text="1").pack()
Label(self.canvas,text="2").pack()
Label(self.canvas,text="3").pack()
Label(self.canvas,text="4").pack()
Label(self.canvas,text="5").pack()
Label(self.canvas,text="6").pack()
Label(self.canvas,text="1").pack()
Label(self.canvas,text="2").pack()
Label(self.canvas,text="3").pack()
Label(self.canvas,text="4").pack()
Label(self.canvas,text="5").pack()
Label(self.canvas,text="6").pack()
hbar=Scrollbar(frame,orient=HORIZONTAL)
hbar.pack(side=BOTTOM,fill=X)
hbar.config(command=self.canvas.xview)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.pack(side=RIGHT,fill=Y)
self.canvas.bind('<Configure>',self._On_Configure())
vbar.config(command=self.canvas.yview)
self.canvas.config(width=300,height=300)
self.canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
self.canvas.pack(side=LEFT,expand=True,fill=BOTH)
root.mainloop()
def _On_Configure(self):
self.canvas.configure(scrollregion=self.canvas.bbox('all'))
GUI = GUI()
Answer: I will not implement it for you. Here are some methods which you might be
interested in:
from Tkinter import *
class GUI():
def __init__(self):
root=Tk()
frame=Frame(root,width=300,height=300)
frame.grid(row=0,column=0)
self.canvas=Canvas(frame,bg='#FFFFFF',width=300,height=300,scrollregion=(0,0,500,500))
self.canvas_frame = Frame(self.canvas)
self.canvas.create_window(0,0, anchor = NW, window = self.canvas_frame)
self.labels = []
for i in range(10):
label = Label(self.canvas_frame,text=str(i))
label.pack()
self.labels.append(label)
hbar=Scrollbar(frame,orient=HORIZONTAL)
hbar.pack(side=BOTTOM,fill=X)
hbar.config(command=self.canvas.xview)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.pack(side=RIGHT,fill=Y)
self.canvas.bind('<Configure>',self._On_Configure) # MISTAKE! do not use () here
vbar.config(command=self.canvas.yview)
self.canvas.config(width=300,height=300)
self.canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
self.canvas.pack(side=LEFT,expand=True,fill=BOTH)
root.mainloop()
def _On_Configure(self, event = None):
print self.canvas.bbox(self.canvas_frame)
for label in self.labels:
print label.winfo_pointerxy(), label.winfo_rootx(), label.winfo_rooty(), label.winfo_height(), label.winfo_reqheight()
print "canvas:", self.canvas.winfo_height(), self.canvas.winfo_pointerxy()
self.canvas.configure(scrollregion=self.canvas.bbox(self.canvas_frame))
GUI = GUI()
The output shows the position of the labels and other pixel stuff.
None
(664, 607) 0 0 21 21
(664, 607) 0 21 21 21
(664, 607) 0 42 21 21
(664, 607) 0 63 21 21
(664, 607) 0 84 21 21
(664, 607) 0 105 21 21
(664, 607) 0 126 21 21
(664, 607) 0 147 21 21
(664, 607) 0 168 21 21
(664, 607) 0 189 21 21
canvas: 304 (664, 607)
With the knowledge about how big the labels are or how big the frame is you
can use store the `vbar` in `self.vbar` and do `self.vbar.pack_forget()` or
`vbar.pack()` whenever you need it or not in the function `_On_Configure`.
When you have your code ready for a scrolled frame then please do not hesitate
to post it. I remember other people also lloking for a frame with scrollbars.
|
Recording video with webcam using VideoCapture
Question: I want to record a video with python (using my webcam) and I came across
[VideoCapture](http://videocapture.sourceforge.net/) which was easy to install
on windows. I know there is OpenCV out there, but that was too much for me.
So far I can create every 0.04 seconds a .jpg with this code:
from VideoCapture import Device
import time
cam = Device(devnum=0) #uses the first webcame which is found
x = 0
while True:
cam.saveSnapshot(str(x)+'.jpg', timestamp=3, boldfont=1) #########################
x += 1
time.sleep(0.04)
0.04 seconds * 25 = 1. So what I am planning to do is an animated gif, that
has 25 frames/sec. If somebody of you knows how to produce a real video file
like .mp4, I really would prefer the .mp4 rather than .gif. However if thats
not possible, the next thing I need to do is, to concatenate all .jpg files
(0.jpg, 1.jpg, 2.jpg ...) but as you can imagine with increasing recording
time I get A LOT of files. So I was wondering if it would be possible to write
the .jpg files (the frames) to one .gif file consecutively. If thats not
possible in python, how would you concatenate the jpg files to get an animated
gif in the end?
Answer: OpenCV will make it more easy. You will find more problem in your method. To
use opencv you have to install 1 more package known as `numpy` (numerical
python). It's easy to install. If you want to install it automatically:
## Install
1. Install pip manually
2. After that go to your `cmd>python folder>Lib>site-packages` and type `pip install numpy` *but for using pip you have to be in internet access.
3. After installation of numpy just type `pip intall opencv`.
Now you can import all the packages. If numpy somehow fails, maunually
downlaod numpy 1.8.0 and install it.
|
Iterate through and print the keys of a dictionary instead of its values?
Question: I have a series of extremely long URLs with keys in the format of
`myurls21,1`, `myurls21,2`, etc. that I am breaking up into component parts
using the following statement:
import concurrent.futures
import urllib.request
import json
myurls2 = {}
for x in range(1, 15):
for y in range(1, 87):
strvar1 = "%s" % (x)
strvar2 = "%s" % (y)
with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_{}_{}.txt".format(x,y),"r") as f:
myurls2[x,y] = f.read().replace('\n', '')
#print("myurls_" + str(strvar1) + "_" + str(strvar2) + "=", myurls2[x,y])
#print(myurls2[x,y])
URLS = myurls2.values()
# Retrieve a single page and report the url and contents
def load_url(url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
c = 0
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
a = ''
b = ''
c += 1
for url in URLS:
a = url.rsplit("=", 1)[-1]
print(myurls2.keys())
How can I print the key of each URL being split into the log? I have tried
`print(myurls2.keys())`, but that prints all of the keys stored within the
dictionary (URLS is defined from the contents of the `myurls2` dictionary).
Answer: If you want to iterate over the keys _and_ values in a dictionary, you can do
for example:
for key, url in myurls2.items():
print(key)
a = url.rsplit("=", 1)[-1]
* * *
If you want the keys for the urls you have passed to `concurrent`, refactor to
allow this:
future_to_url = {executor.submit(load_url, url, 60): (key, url)
for key, url in myurls2.items()}
Now you can access it:
for future in concurrent.futures.as_completed(future_to_url):
key, url = future_to_url[future]
# print key and process url
|
How do I fix a "memory leak of type 'wxPyXmlSubclassFactory *', no destructor found" error from wxPython/wxFormBuilder?
Question: I'm trying to follow [this
tutorial](http://vcansimplify.wordpress.com/2013/04/08/ultra-quick-guis-with-
wxformbuilderpython/) to quickly make simple GUIs using wxPython and
wxFormBuilder.
Using the wxFormBuilder, I created a super simple frame with one vertical
layout, one edit text control and a button, which only clears the value of the
text control. WxFormBuilder generated the Python code and I just added a few
lines to clear the value of the text control when the button is clicked. Here
is an image of the stupid simple frame.

When I run this file in Python, the GUI does clear the text I type in the text
control. When I click on the Frame's close button, I see this:
`swig/python detected a memory leak of type 'wxPyXmlSubclassFactory *', no
destructor found.`
I tried Googling the issue but only found that Python is dynamic enough to not
require destructors. I did try out adding the `__del__` function, but I still
got the same error message.
Ideas for getting rid of that error? I'm using:
* Python 2.7.6
* wxPython 3.0.0.0 for Python 2.7
* wxFormBuilder 3.4.2
* Windows 7, 32-bit
Thank you so much in advance!
Here's the code I have if anyone needs it:
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Feb 26 2014)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
import wx
import wx.xrc
###########################################################################
## Class MyFrame1
###########################################################################
class MyFrame1 ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 203,155 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
bSizer1 = wx.BoxSizer( wx.VERTICAL )
self.edit = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer1.Add( self.edit, 1, wx.ALL|wx.EXPAND, 5 )
self.clearButton = wx.Button( self, wx.ID_ANY, u"Clear", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer1.Add( self.clearButton, 1, wx.ALL|wx.EXPAND, 5 )
self.SetSizer( bSizer1 )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.clearButton.Bind( wx.EVT_BUTTON, self.clearFunc )
def __del__( self ):
pass
# Virtual event handlers, overide them in your derived class
def clearFunc( self, event ):
event.Skip()
class SimpleFrame(MyFrame1):
def __init__(self,parent):
MyFrame1.__init__(self,parent)
def clearFunc(self,event):
self.edit.SetValue("")
app = wx.App(False)
frame = SimpleFrame(None)
frame.Show(True)
app.MainLoop()
Answer: I keep getting the same error with the latest version (3.0.0). No new
version's been released since. No need to worry though. Expect to see a fix
sometime soon.
Take a look at the last post [here](http://wxpython-
users.1045709.n5.nabble.com/ANNOUNCE-wxPython-3-0-0-0-td5719588.html)
|
how do I sum up this python Dictionary and get the average?
Question: d =[{'C': 0, 'B': 2.0, 'A': 7.0, 'D': 3.0}, {'C': 2.0, 'B': 0, 'A': 5.0, 'D':
5.0}, {'C': 7.0, 'B': 5.0, 'A': 0, 'D': 10.0}, {'C': 3.0, 'B': 5.0, 'A': 10.0,
'D': 0}]
how do I sum up this python Dictionary and get the average ?...
Answer:
>>> from functools import reduce
>>> d
[{'D': 3.0, 'A': 7.0, 'C': 0, 'B': 2.0}, {'D': 5.0, 'A': 5.0, 'C': 2.0, 'B': 0}, {'D': 10.0, 'A': 0, 'C': 7.0, 'B': 5.0}, {'D': 0, 'A': 10.0, 'C': 3.0, 'B': 5.0}]
>>> l = len(d)
>>> s = reduce(lambda x,y: {z:x[z]+y[z] for z in ['A','B','C','D']}, d)
>>> s = {x:s[x]/l for x in s}
>>> s
{'D': 4.5, 'A': 5.5, 'C': 3.0, 'B': 3.0}
>>>
|
using multiprocessing.Pool on bound methods
Question: I'm trying to use `multiprocessing.Pool` in my code but I got this exception:
`PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup
__builtin__.instancemethod failed`
I found [this](http://stackoverflow.com/questions/1816958/cant-pickle-type-
instancemethod-when-using-pythons-multiprocessing-pool-ma) and it's [preferred
solution recipe](http://bytes.com/topic/python/answers/552476-why-cant-you-
pickle-instancemethods#edit2155350)
my problem is that I don't know how to implement this solution in my code.
my code is something like that:
class G(class):
def submit(self,data):
cmd = self.createCommand(data)
subprocess.call(cmd, shell=True)
# call for a short command
def main(self):
self.pool = multiprocessing.Pool()
while(True):
data = self.GenerateData()
self.pool.apply_async(self.Submit, args=(data,))
some notes:
* the main `while` should work for a long time (few days)
* I'm using `pool` for performance purposes, if you have a better solution I will be glad to here it
## update:
after using @unutbu solution I got the next exception: `PicklingError: Can't
pickle <type 'thread.lock'>: attribute lookup thread.lock failed`
now , all the solutions I found were talking about `Queue.Queue` and
`mp.Pool.map` but I'm not using those attributes so I can't figure it out.
Answer: This is an application of Steven Bethard's solution to your situation:
import multiprocessing as mp
import time
import copy_reg
import types
def _pickle_method(method):
"""
Author: Steven Bethard
http://bytes.com/topic/python/answers/552476-why-cant-you-pickle-instancemethods
"""
func_name = method.im_func.__name__
obj = method.im_self
cls = method.im_class
cls_name = ''
if func_name.startswith('__') and not func_name.endswith('__'):
cls_name = cls.__name__.lstrip('_')
if cls_name:
func_name = '_' + cls_name + func_name
return _unpickle_method, (func_name, obj, cls)
def _unpickle_method(func_name, obj, cls):
"""
Author: Steven Bethard
http://bytes.com/topic/python/answers/552476-why-cant-you-pickle-instancemethods
"""
for cls in cls.mro():
try:
func = cls.__dict__[func_name]
except KeyError:
pass
else:
break
return func.__get__(obj, cls)
# This call to copy_reg.pickle allows you to pass methods as the first arg to
# mp.Pool methods. If you comment out this line, `pool.map(self.foo, ...)` results in
# PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup
# __builtin__.instancemethod failed
copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)
class G(object):
def submit(self, data):
print('processing {}'.format(data))
# cmd = self.createCommand(data)
# subprocess.call(cmd, shell=True)
# call for a short command
time.sleep(2)
def main(self):
pool = mp.Pool()
while True:
data = (1, 2, 3)
pool.apply_async(self.submit, args=(data,))
if __name__ == '__main__':
g = G()
g.main()
|
Optimising Pandas multi-index lookup
Question: I Use Pandas 0.12.0. Say `multi_df` is a Pandas dataframe with multiple index.
And I have a (long) list of tuples (multiple indexes), named `look_up_list`. I
want to perform an operation if a tuple in `look_up_list` is in `multi_df`.
Below is my code. **Is there a faster way to achieve this?** In reality
`len(multi_df)`and `len(look_up_list)` are quite large so I need to
**optimise** this line: `[multi_df.ix[idx]**2 for idx in look_up_list if idx
in multi_df.index]`.
In particular, [line_profiler](http://pythonhosted.org/line_profiler/) tells
me that the contidional check: `if idx in multi_df.index` takes a long time.
import pandas as pd
df = pd.DataFrame({'id' : range(1,9),
'code' : ['one', 'one', 'two', 'three',
'two', 'three', 'one', 'two'],
'colour': ['black', 'white','white','white',
'black', 'black', 'white', 'white'],
'texture': ['soft', 'soft', 'hard','soft','hard',
'hard','hard','hard'],
'shape': ['round', 'triangular', 'triangular','triangular','square',
'triangular','round','triangular']
}, columns= ['id','code','colour', 'texture', 'shape'])
multi_df = df.set_index(['code','colour','texture','shape']).sort_index()['id']
# define the list of indices that I want to look up for in multi_df
look_up_list = [('two', 'white', 'hard', 'triangular'),('five', 'black', 'hard', 'square'),('four', 'black', 'hard', 'round') ]
# run a list comprehension
[multi_df.ix[idx]**2 for idx in look_up_list if idx in multi_df.index]
P.S: The actual operation in the list comprehension is not
`multi_df.ix[idx]**2`, but something like:
`a_slow_function(multi_df.ix[idx])`.
Answer: Perhaps use `multi_df.loc[look_up_list].dropna()`.
import pandas as pd
df = pd.DataFrame(
{'id': range(1, 9),
'code': ['one', 'one', 'two', 'three',
'two', 'three', 'one', 'two'],
'colour': ['black', 'white', 'white', 'white',
'black', 'black', 'white', 'white'],
'texture': ['soft', 'soft', 'hard', 'soft', 'hard',
'hard', 'hard', 'hard'],
'shape': ['round', 'triangular', 'triangular', 'triangular', 'square',
'triangular', 'round', 'triangular']
}, columns=['id', 'code', 'colour', 'texture', 'shape'])
multi_df = df.set_index(
['code', 'colour', 'texture', 'shape']).sort_index()['id']
# define the list of indices that I want to look up for in multi_df
look_up_list = [('two', 'white', 'hard', 'triangular'), (
'five', 'black', 'hard', 'square'), ('four', 'black', 'hard', 'round')]
subdf = multi_df.loc[look_up_list].dropna()
print(subdf ** 2)
yields
(two, white, hard, triangular) 9
(two, white, hard, triangular) 64
Name: id, dtype: float64
Note:
* `multi_df` as defined above is a Series, not a DataFrame. I don't think that affects the solution though.
* The code you posted above raises `IndexingError: Too many indexers` so I'm guessing (a little bit) at the intention of the code.
|
Reading and Compressing a picture with RLE
Question: Currently I am learning python and I'd like to get a little bit more into Data
Compression. So I decided to try to code Run-Length Encoding(RLE).
From what I've read it can be useful when you try to compress pictures.
I would like to know what would be the easiest image-file-type for a beginner?
How can I read out pixel RGB values or similar from a picture with python?
Answer: As for the second part of your question: I would highly recommend
[OpenCV](http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_table_of_contents_imgproc/py_table_of_contents_imgproc.html#py-
table-of-content-imgproc). It is very power for image processing and analysis.
A very basic example of getting the pixel values of an image in Python using
OpenCV:
import cv2
image = cv2.imread("some_image.jpg")
image[x, y, z]
This will return the value of the pixel at `x, y, z` coordinates. Note that
indexing begins at 0 so if you want to access the third RGB component, you
have to do `image[x, y, 2]` where `x` and `y` are the line and column.
|
Python how to direct subprocess to output file
Question: I have created a script that receives a bunch of log files as input in order
to do some pattern matching. However, my "processFiles" method is not working
properly. It should write all data to "fileDest". But the created file remains
empty. If I put a "print processFiles" statement under the function itself I
can see lines as throughput on my terminal.
To make matters more interesting, bunzip2 reports this error while I run the
script:
* * *
Proccessing /opt/syslog/app/applog-20140314.bz2. bunzip2: Can't open input
file > : No such file or directory. bunzip2: Compressed file ends
unexpectedly; perhaps it is corrupted? *Possible reason follows. bunzip2: No
such file or directory Input file =
/var/tmp/parsed_applog-20140314.decompressed, output file = (stdout)
* * *
It seems something in my code sends the output to stdout. And not to the file.
def parse_log_files(self):
sub_dir = os.listdir(self.base_path)
for directory in sub_dir:
if re.search('app\d+', directory):
fileInput = self.base_path + '/' + directory + '/applog-' + str(self.date.strftime('%Y%m%d')) + '.bz2'
fileDest = '/var/tmp/parsed_log_files-' + str(self.date.strftime('%Y%m%d')) + '.decompressed'
if not os.path.isfile(fileDest):
subprocess.Popen(['touch',fileDest]).communicate()[0]
proccessFiles = subprocess.Popen(['/bin/bunzip2','-cd',fileInput,' > ',fileDest],stdout=subprocess.PIPE).communicate()[0]
accessFileHandle = open(self.file_out, 'r')
readFileHandle = accessFileHandle.readlines()
print "Proccessing %s." % fileInput
Answer: `' > '` is a shell redirection syntax. `Popen` doesn't spawn the shell unless
you ask (you shouldn't). If you want to redirect the output of a subprocess to
a file then use `stdout=file_object` parameter e.g.:
from subprocess import check_call
with open('/path/to/output', 'wb', 0) as output_file:
check_call(['command', 'arg1', 'arg2'], stdout=output_file)
|
Python - Decode UTF-16 file with BOM
Question: I have a [UTF-16](https://en.wikipedia.org/wiki/UTF-16)
[LE](https://en.wikipedia.org/wiki/UTF-16#Byte_order_encoding_schemes) file
with [BOM](https://en.wikipedia.org/wiki/Byte_order_mark). I'd like to flip
this file in to UTF-8 without BOM so I can parse it using Python.
The usual code that I use didn't do the trick, it returned unknown characters
instead of the actual file contents.
f = open('dbo.chrRaces.Table.sql').read()
f = str(f).decode('utf-16le', errors='ignore').encode('utf8')
print f
What would be the proper way to decode this file so I can parse through it
with `f.readlines()`?
Answer: Firstly, you should read in binary mode, otherwise things will get confusing.
Then, check for and remove the BOM, since it is part of the file, but not part
of the actual text.
import codecs
encoded_text = open('dbo.chrRaces.Table.sql', 'rb').read() #you should read in binary mode to get the BOM correctly
bom= codecs.BOM_UTF16_LE #print dir(codecs) for other encodings
assert encoded_text.startswith(bom) #make sure the encoding is what you expect, otherwise you'll get wrong data
encoded_text= encoded_text[len(bom):] #strip away the BOM
decoded_text= encoded_text.decode('utf-16le') #decode to unicode
Don't encode (to `utf-8` or otherwise) until you're done with all
parsing/processing. You should do all that using unicode strings.
Also, `errors='ignore'` on `decode` may be a bad idea. Consider what's worse:
having your program tell you something is wrong and stop, or returning wrong
data?
|
PermissionError when using python 3.3.4 and RotatingFileHandler
Question: I am trying to get a rotating log file for a GUI application I am writing with
python 3.3.4 and PyQt4.
I have the following snippet of code in my main script:
import logging
import resources
logger = logging.getLogger('main.test')
def main():
logger.setLevel(logging.DEBUG)
fh = RotatingFileHandler(resources.LOG_FILE_PATH, maxBytes=500, backupCount=5)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.info('main')
I have the maxBytes low so that I can test the rotating is working correctly,
which it is not. I am getting the following error whenever the log should be
rotated:
Traceback (most recent call last):
File "C:\Python33\lib\logging\handlers.py", line 73, in emit
self.doRollover()
File "C:\Python33\lib\logging\handlers.py", line 176, in doRollover
self.rotate(self.baseFilename, dfn)
File "C:\Python33\lib\logging\handlers.py", line 116, in rotate
os.rename(source, dest)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\myuser\\.logtest\\test.log.1'
And nothing is logged. Any help is much appreciated. Thank you
Answer: Check that the file isn't being kept open by e.g. Windows file indexing, anti-
virus or other software. Files that are open can't be renamed.
|
SqlAlchemy not using utf8 charset even if specified
Question: I'm using Flask with Flask-SqlAlchemy with MySQL and my connection string does
have the `charset-utf8` parameter on my connection string.
I'm also using reflection and my Model is specified as this:
class Value(db.Model):
__bind_key__ = 'values'
__tablename__ = 'values'
I've also tried the trick of putting `# -*- coding:utf8 -*-` inside my files
but I'm still getting these stacktraces:
Traceback (most recent call last):
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request
return view_func(**req.view_args)
File "/usr/lib/python2.7/cProfile.py", line 149, in runcall
return func(*args, **kw)
File "/home/numkem/src/sd/application/views/player.py", line 54, in player_show
return render_template('player/show.html', **locals())
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/flask/templating.py", line 128, in render_template
context, ctx.app)
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/flask/templating.py", line 110, in _render
rv = template.render(context)
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/home/numkem/src/sd/venv/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/numkem/src/sd/application/templates/player/show.html", line 1, in top-level template code
{% extends "base.html" %}
File "/home/numkem/src/sd/application/templates/base.html", line 62, in top-level template code
{% block body %}{% endblock %}
File "/home/numkem/src/sd/application/templates/player/show.html", line 27, in block "body"
<td>{{ field.values }}</td>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 16: ordinal not in range(128)
Why is the charset ignored on connection? Shouldn't it be set by the
connection string? Maybe it's just not something that possible/supported when
using reflections.
Thanks!
Answer: Turns out the problem was not really coming from SqlAlchemy but more from
Jinja2 itself since it wasn't seeing that I wanted to use utf8 encoding
througout the application. the
[documentation](http://jinja.pocoo.org/docs/api/?highlight=unicode#unicode)
states that the default encoding is set to ascii if nothing is specified.
This [answer](http://stackoverflow.com/questions/5040532/python-ascii-codec-
cant-decode-byte) shows the solution to my problem.
The fix is to add this to your first code:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
I'm not 100% familiar with python but I'm assuming this might have to do with
using a WSGI application instead of a standard script so the `# -*-
coding:utf8 -*-` trick doesn't work.
|
Python exception handling: Check return value of function
Question: Before using the value of a return of a function, I want to check if the value
is useable. So what I have is more or less the following:
def get_module():
import foo
return foo
def do_something():
try:
module = get_module()
except:
print "error"
module.bar()
Unfortunately, it seems to me that this never raises an exception. In
particular, I want to check (a) that the module was transferred correctly and
(b) that the module is one of three possible modules.
I know I can check through if-statements, but I feel that exception handing is
ought to be the correct way.
Answer: If `foo` cannot be imported, the code below will produce an
[ImportError](http://docs.python.org/2/library/exceptions.html#exceptions.ImportError)
exception:
def get_module():
import foo
return foo
def do_something():
try:
module = get_module()
except ImportError:
print "Import Error!"
raise
module.bar()
do_something()
Produces:
Import Error!
Traceback (most recent call last):
...
import foo
ImportError: No module named foo
Note, that you should either reraise the exception via `raise` in the `except`
block, or make a `return`, so that you don't get an error on `module.bar()`
line because of undefined `module` variable.
Hope that helps.
|
Error converting list to string
Question: I am trying to specify the position where I would like my data to be written
in my output file but I am getting the following error. Could I please be
advised on how I might resolve this issue?
Traceback (most recent call last):
File "C:/Python33/Upstream and downstream shores.py", line 20, in <module>
upstream_shore.writerow (line[0] + [upstream_1] + line[1])
TypeError: Can't convert 'list' object to str implicitly
Here is my code:
import csv
file1 = open ('fileA.csv', 'rt', newline ='')
reader = csv.reader(file1)
upstream = open ('fileB.csv', 'wt', newline = '')
upstream_shore = csv.writer(upstream)
downstream = open ('fileC.csv', 'wt', newline = '')
downstream_shore = csv.writer(downstream)
count_upstream = 0
count_downstream = 0
for line in reader:
downstream = [(int(x) - 2000) for x in line[2]]
upstream = [(int(y) - 2000) for y in line [1]]
upstream_1 = str(upstream)
downstream_1 = str(downstream)
upstream_shore.writerow (line[0] + [upstream_1] + line[1])
count_upstream += 1
downstream_shore.writerow(line[0] + line [2] + [downstream_1])
count_downstream += 1
print ('Number of upstream shore counts:', count_upstream)
print ('Number of downstream shore counts:', count_downstream)
file1.close()
upstream.close()
downstream.close()
Thanks
Answer: In the following line:
upstream_shore.writerow (line[0] + [upstream_1] + line[1])
`line[0]` (and `line[1]`) is a string, not a list. Python is trying to
concatenate a string and a list, but it doesn't know how so it gives you the
`TypeError`. You probably want `[line[0]]` instead so that it's concatenating
2 lists (which is knows how to do) e.g.:
upstream_shore.writerow ([line[0]] + [upstream_1] + [line[1]])
Note, you'll have the same error again 2 lines down.
|
Do Dictionaries have a key length limit?
Question: I was wondering if Python had a limit on the length of a dictionary key.
For clarification, I'm not talking about the number of keys, but the length of
each individual key. I'm going to be building my dictionaries based on dynamic
values (after validation), but I'm not sure if I should be taking length into
account in this case.
Answer: Here's a bit of sample code:
from string import ascii_letters
from random import choice
def make_str(length):
return "".join(choice(ascii_letters) for i in range(length))
test_dict = {make_str(10000000): i for i in range(5)}
Conclusion: Python will quite happily use a 10-million-character string as a
dict key.
|
Python: How Close (or exit) Python Process After QMainWindow Dialog is closed
Question: There are two .py files placed in a same folder:
dialog_01.py and dialog_02.py
Both files are copy of each other. Both build a simple QMainWindow dialog
window with two buttons: 'Ok' and 'Cancel'.
Clicking 'Ok' button closes a currently opened dialog window and opens
another. So if Dialog_01's Ok button is clicked the dialog_01 is closed and
dialog_02 is opened. If Dialog_02's Ok button is clicked then dialog_02 is
closed and dialog_01 is opened and so on.
# EDITED QUESTION:
Closing the dialog box leaves Python process still running at the background
(it can be seen in OSX Activity Monitor or Windows Task Manager).
**How to make sure the Python process is terminated after the dialog window is
closed?**
# dialog_01.py
import sys, os
from PyQt4 import QtCore, QtGui
if 'app' not in globals().keys(): app = QtGui.QApplication(sys.argv)
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
Cancel_button = QtGui.QPushButton("Cancel")
Cancel_button.clicked.connect(self.Cancel)
myBoxLayout.addWidget(Cancel_button)
Button_01 = QtGui.QPushButton("Press to close this dialog and open Dialog 02")
Button_01.clicked.connect(self.callAnotherQMainWindow)
myBoxLayout.addWidget(Button_01)
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.setWindowTitle('Dialog 01')
def callAnotherQMainWindow(self):
from dialog_02 import Dialog_02
self.close()
self.dialog_02 = Dialog_02()
self.dialog_02.show()
self.dialog_02.raise_()
def Cancel(self):
self.close()
def closeEvent(self):
self.deleteLater()
if __name__ == '__main__':
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
# dialog_02.py
import sys, os
from PyQt4 import QtCore, QtGui
if 'app' not in globals().keys(): app = QtGui.QApplication(sys.argv)
class Dialog_02(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
Cancel_button = QtGui.QPushButton("Cancel")
Cancel_button.clicked.connect(self.Cancel)
myBoxLayout.addWidget(Cancel_button)
Button_02 = QtGui.QPushButton("Press to close this dialog 02 and re-open Dialog 01")
Button_02.clicked.connect(self.callAnotherQMainWindow)
myBoxLayout.addWidget(Button_02)
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.setWindowTitle('Dialog 02')
def callAnotherQMainWindow(self):
from dialog_01 import Dialog_01
self.close()
self.dialog_01 = Dialog_01()
self.dialog_01.show()
self.dialog_01.raise_()
def Cancel(self):
self.close()
def closeEvent(self):
self.deleteLater()
if __name__ == '__main__':
dialog_2 = Dialog_02()
dialog_2.show()
dialog_2.resize(480,320)
sys.exit(app.exec_())
Answer: Override the closeEvent() function of your QtGui.QMainWindow classes like
below:
def closeEvent(self, event):
self.deleteLater()
This seemed to work:
Removing this:
if 'app' not in globals().keys(): app = QtGui.QApplication(sys.argv)
and this:
if __name__ == '__main__':
dialog_2 = Dialog_02()
dialog_2.show()
dialog_2.resize(480,320)
sys.exit(app.exec_())
...from dialog2 file did the trick.
|
Python, Mockito, Mocking Another Module's Imports
Question: Suppose I have module1.py
from my_library import useful_function
def do_something(x):
return useful_function(x)
I am testing module2.py
from module1 import do_something
def do_something_else(x):
return do_something(x+1)
useful_function does database calls, and I would therefore like to stub it out
to return a constant value.
How can I use mockito to stub out useful_function? I have tried importing
my_library, and using
when( my_library ).useful_function('abc').thenReturn(...)
but that does not work. If I pause Eclipse and hover over the useful_function
line inside do_something(), it appears that useful_function() has not been
stubbed.
Answer:
import module1
module1.useful_function = Mock(...)
return do_something(x+1)
|
update a variable within a function?
Question: I'm teaching myself python 3.x and am struggling to resolve an issue I'm
having with variable scope.
In my program, I ask the user for an input, and then run a function to check
its value. If the value is correct, I continue. Otherwise, I wish to allow the
user to change their previous input and retest with the new value. The values
I am looking for are the strings: '0', '1', '2',... '8', '9'.
The code below is incorrect, but its the best I've been able to come up with
so far. The problem I see is that while I can change the variable user_input
within the function check_input(), I do not know how to change the scope of
the variable.
For example, if I run the program and type 'abc' for rating_A, I will get the
'too many characters' message, and will be asked to try again. I now enter
'7', and all seems dandy. But when I call rating_A later, I will get 'abc',
not the desired '7'.
I've tried to fix this with the global variable technique. My difficulty with
that is that I wish to check a large amount of input values, and each will
have its own variable (rating_A, rating_B.... rating_Y, rating_Z). I imagine
there is a much more elegant way to accomplish this?
from string import digits
def check_input(user_input):
while True:
if len(user_input) != 1:
print (user_input, 'has too many characters!')
user_input = input('try again: ')
continue
elif user_input in digits:
print (user_input, 'is valid!')
user_input = int(user_input)
return user_input
break
else:
print (user_input, 'is not a valid input!')
user_input = input('try again: ')
continue
rating_A = input('Please enter a value for A: ')
check_input(rating_A)
print ()
rating_B = input('Please enter a value for B: ')
check_input(rating_B)
Answer: Not sure I understand you really, but in case it's valid, you are already
returning user_input, thus
rating_A = input('Please enter a value for A: ')
rating_A = check_input(rating_A)
assigns the final return value to your variable and you are set.
Otherwise I apologize for not understanding your request well.
|
scikit learn imputing values other than NaN
Question: I'm trying to impute values for different placeholders which represent empty
values in a matrix. For example, I want to impute a value whenever "?" is
present in a numpy 2darray.
To this end I create an `Imputer` like so:
from sklearn import preprocessing
imputer = preprocessing.Imputer(missing_values="?", strategy='mean', axis=0, copy=False)
data = imputer.fit_transform(data)
But I get this error:
/usr/local/lib/python2.7/dist-packages/sklearn/preprocessing/imputation.pyc in _get_mask(X, value_to_mask)
27 def _get_mask(X, value_to_mask):
28 """Compute the boolean mask X == missing_values."""
---> 29 if value_to_mask == "NaN" or np.isnan(value_to_mask):
30 return np.isnan(X)
31 else:
NotImplementedError: Not implemented for this type
Am I misunderstanding what `missing_values` can be set to?
I was under the impression it could be any string, not just "NaN", which is
what the scikit-learn source seems to suggest.
Answer: The type `"integer or string"` really means "either an integer, or the string
`'NaN'`". The input to `fit`/`fit_transform` should still be numeric. (The
only reason `"NaN"` is passed as a string is that passing `np.nan` can lead to
confusing situations because it's not equal to itself, i.e. `np.nan == np.nan`
evaluates to `False`.)
|
How to use django template tag 'url' with django 1.6?
Question: I'm using Python 2.7.5, django 1.6.2 and bootstrap 3.
I know the template tag `{% url %}` changed since django 1.5. I've read the
[documentation for reverse
url](https://docs.djangoproject.com/en/1.6/topics/http/urls/#reverse-
resolution-of-urls) on django website but I must do something wrong because I
can't get it to work.
Here is my teams/urls.py, I use the named url `delete_team_url` :
from django.conf.urls import patterns, url
import teams.views
urlpatterns = patterns('',
url(r'^$', teams.views.index, name='teams_index'),
url(r'^new-team/$', teams.views.index, {'add_new_team':True}, name='teams_index_new_team'),
url(r'^delete/$', teams.views.delete_team, name='delete_team_url'),
)
Here is the project global urls.py :
from django.conf.urls import patterns, include, url
from django.contrib import admin
import bbch.views
import auth.views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^rosetta/', include('rosetta.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^auth/', include('auth.urls', namespace="auth")),
url(r'^rules/', include('rules.urls', namespace="rules")),
url(r'^forum/', include('forum.urls', namespace="forum")),
url(r'^teams/', include('teams.urls', namespace="teams")),
url(r'^accounts/login/$', auth.views.connection, {'log_required':True}),
url(r'^home/log_in/$', bbch.views.home, {'log_message':True}, name="home_log_message"),
url(r'^home/$', bbch.views.home, name="bbch"),
url(r'^$', bbch.views.home, name="bbch"),
)
Here is my view (I'm using dummy `id=0` just for the test) :
def delete_team(request):
team = teams.models.Team.objects.get(id=0)
team.delete()
return render(request, 'teams/index.html', context)
And finally here is my html code part where I use the reverse url template tag
:
<div class="row">
<div class="col-md-2">
<a href="{% url 'delete_team_url' %}" class="btn btn-danger delete-team"><span class="glyphicon glyphicon-trash"></span> {% trans "Delete team" %}</a>
</div>
<div class="col-md-2">
<a href="#" class="btn btn-info edit-team"><span class="glyphicon glyphicon-pencil"></span> {% trans "Edit team" %}</a>
</div>
<div class="col-md-2 col-md-offset-6 btn-right">
<a href="#" class="btn btn-success add-player"><span class="glyphicon glyphicon-plus"></span> {% trans "Add a player" %}</a>
</div>
</div>
I get the following error :
NoReverseMatch at /teams/
Reverse for 'delete_team_url' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Let me know if you need more informations ! Thank you for your help !
* * *
Edit : Here is the `teams.views.index` (asked by weasel) :
@login_required
def index(request, add_new_team=False) :
if request.method == 'POST' :
t_form = teams.forms.CreateTeamForm(request.POST)
p_form = teams.forms.CreatePlayerForm(request.POST)
t_errors = t_form.errors
p_errors = p_form.errors
if t_form.is_valid() :
create_new_team = t_form.cleaned_data['new_team']
else :
create_new_team = False
if p_form.is_valid() :
add_player = p_form.cleaned_data['new_player']
else :
add_player = False
#import ipdb; ipdb.set_trace()
if create_new_team :
if t_form.is_valid() :
name = t_form.cleaned_data['name']
reroll = t_form.cleaned_data['reroll']
apo = t_form.cleaned_data['apo']
assistant = t_form.cleaned_data['assistant']
pompom = t_form.cleaned_data['pompom']
pop = t_form.cleaned_data['pop']
value = t_form.cleaned_data['value']
treasury = t_form.cleaned_data['treasury']
team = teams.models.Team(
name=name,
coach=request.user.username,
reroll=reroll,
apo=apo,
assistant=assistant,
pompom=pompom,
pop=pop,
value=value,
treasury=treasury,
)
team.save()
team_set = teams.models.Team.objects.filter(coach=request.user.username)
player_form = teams.forms.CreatePlayerForm()
context = {
'create_player_form' : player_form,
'teams' : team_set,
'username' : request.user,
'loged_in' : request.user.is_authenticated(),
}
return render(request, 'teams/index.html', context)
elif add_player :
if p_form.is_valid() :
name = p_form.cleaned_data['name']
position = p_form.cleaned_data['position']
number = p_form.cleaned_data['number']
team_id = request.POST.get('team_id')
team = teams.models.Team.objects.get(coach=request.user.username, id=team_id)
team.player_set.create(name=name, position=position, number=number)
team.size = team.player_set.count()
team.save()
team_set = teams.models.Team.objects.filter(coach=request.user.username)
player_form = teams.forms.CreatePlayerForm()
context = {
'tab_id': team.id,
'create_player_form' : player_form,
'teams' : team_set,
'username' : request.user,
'loged_in' : request.user.is_authenticated(),
}
return render(request, 'teams/index.html', context)
else :
team_set = teams.models.Team.objects.filter(coach=request.user.username)
team_form = teams.forms.CreateTeamForm()
player_form = teams.forms.CreatePlayerForm()
context = {
'create_player_form' : player_form,
'create_team_form' : team_form,
'alert_form_player' : p_errors,
'alert_form_team' : t_errors,
'teams' : team_set,
'username' : request.user,
'loged_in' : request.user.is_authenticated(),
}
return render(request, 'teams/index.html', context)
elif request.method == 'GET' :
team_set = teams.models.Team.objects.filter(coach=request.user.username)
team_form = teams.forms.CreateTeamForm()
player_form = teams.forms.CreatePlayerForm()
context = {
'add_new_team': add_new_team,
'create_player_form' : player_form,
'create_team_form' : team_form,
'teams' : team_set,
'username' : request.user,
'loged_in' : request.user.is_authenticated(),
}
return render(request, 'teams/index.html', context)
Answer: Perhaps because of the missing `$` (dollar) sign at the end of your
urlpatterns you're getting this error.
You should perhaps try this:
url(r'^new-team/$' ...),
url (r'^delete/$' ...),
**UPDATE:**
Okay, got it. You're using namespace in your urls which is why you've to use
`{% url %}` tag something like below:
<a href="{% url 'teams:delete_team_url' %}" ... > ... </a>
|
"from __future__ import unicode_literals" gives segfault in python 2.7
Question: all~
The segfault occured while i try to use rest_framework in a webapp as this:
from rest_framework import viewsets
finally, i pointed the problem occured here:
>>> from __future__ import unicode_literals
Segmentation fault
but i have no idea for the next, so i posted here for some help. thx for any
advice.
FYI:
1\. I have compared a normal __future__.py with this buggy __future__.py. But
i found nothing.
2\. I have tried the different version of django-rest-framework, so i can get
the piont above.
Something may be useful:
platform: Linux 3.2.12-gentoo #1 SMP
python: Python 2.7.3 (default, Oct 8 2012, 16:37:44) [GCC 4.4.5] on linux2
######Update Info. Really thx for U;-)########
The details of core:
# gdb python core
GNU gdb (Gentoo 7.3.1 p2) 7.3.1
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu".
For bug reporting instructions, please see:
<http://bugs.gentoo.org/>...
Reading symbols from /bin/python...done.
[New LWP 6349]
warning: Can't read pathname for load map: Input/output error.
[Thread debugging using libthread_db enabled]
Core was generated by `python'.
Program terminated with signal 11, Segmentation fault.
#0 binary_iop1 (op_slot=<optimized out>, iop_slot=<optimized out>, w=<optimized
1280 Objects/abstract.c: No such file or directory.
in Objects/abstract.c
(gdb) bt
#0 binary_iop1 (op_slot=<optimized out>, iop_slot=<optimized out>, w=<optimized out>, v=<optimized out>) at Objects/abstract.c:1280
#1 binary_iop (op_name=<optimized out>, op_slot=<optimized out>, iop_slot=<optimized out>, w=<optimized out>, v=<optimized out>) at Objects/abstract.c:1298
#2 PyNumber_InPlaceTrueDivide (v=0x39, w=0xb76e03d0) at Objects/abstract.c:1332
#3 0x080e0f54 in PyEval_EvalFrameEx (f=0x88a1f7c, throwflag=0) at Python/ceval.c:1514
#4 0x080e6a44 in PyEval_EvalCodeEx (co=0xb751d9b0, globals=0xb757035c, locals=0xb757035c, args=0x0, argcount=0, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0)
at Python/ceval.c:3263
#5 0x080e6b77 in PyEval_EvalCode (co=0xb751d9b0, globals=0xb757035c, locals=0xb757035c) at Python/ceval.c:669
#6 0x08103f27 in run_mod (arena=<optimized out>, flags=<optimized out>, locals=<optimized out>, globals=<optimized out>, filename=<optimized out>, mod=<optimized out>)
at Python/pythonrun.c:1353
#7 PyRun_InteractiveOneFlags (fp=0xb76df440, filename=0x815b7a4 "<stdin>", flags=0xbfbb23ec) at Python/pythonrun.c:852
#8 0x08104198 in PyRun_InteractiveLoopFlags (fp=0xb76df440, filename=0x815b7a4 "<stdin>", flags=0xbfbb23ec) at Python/pythonrun.c:772
#9 0x081049e5 in PyRun_AnyFileExFlags (fp=0xb76df440, filename=0x815b7a4 "<stdin>", closeit=0, flags=0xbfbb23ec) at Python/pythonrun.c:741
#10 0x0805bacd in Py_Main (argc=1, argv=0xbfbb24d4) at Modules/main.c:674
#11 0x0805abab in main (argc=1, argv=0xbfbb24d4) at ./Modules/python.c:23
(gdb)
Answer: To solve your current issue you can place a `u` before each used string
literal, so out of `'foo'` make `u'foo'` etc. This of course can be a lot of
code to change, **BUT** :
Segmentation Faults are _always_ a problem within the implementation of Python
(either the core language interpreter or a module in use). There is no way
within the Python language to produce a Segmentation Fault because this kind
of memory management is hidden from the Python developer.
This means that this kind of bug needs to be fixed within the implementation
of the Python language or module. You should provide your information as a bug
report to the developers of the faulty code. The faulty code can be be found
by producing a core file and analyzing this. It is a lucky coincidence that
you can reproduce the problem so easily, so you can configure your shell to
produce core files:
$ ulimit -c unlimited
Then produce the Segfault:
$ python
>>> from __future__ import unicode_literals
Segmentation fault (core dumped)
Now you should have a core file and can load this in the Gnu debugger:
$ gdb /usr/bin/python core # maybe adjust path-to-python for your system
GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04
...
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `python'.
Program terminated with signal 11, Segmentation fault.
#0 0x00007f21c08705d5 in ?? () from /lib/x86_64-linux-gnu/libc.so.6
(gdb)
Or something like this. Then type:
(gdb) bt
This will print a large backtrace of the situation which lead to the Segfault
(frame #0 will be the one who raised the problem, frame #1 called frame #0
etc., so this backtrace is innermost-first). Maybe you can figure out by the
names of the functions etc. which module is involved. Then you should provide
this backtrace to the developers of the involved module. They are the ones to
solve the issue at hand.
|
Execute a Python statement in a Bash script
Question: Is it possible to have Python evaluate a Python statement within a Bash shell
script? I am thinking about something along the lines of perl's `-e` option.
The problem at hand is that I'd like to use Python's `split` function on a
Bash string. I know it's doable in Bash alone, but I am curious.
Answer: The equivalent of `perl -e` is `python -c`:
$ python -c "import sys;print sys.argv[1].split(',')" "foo,bar,baz"
['foo', 'bar', 'baz']
|
Memory issue in Python. Dictionary v.s. Database (or can you combine both?)
Question: I'm trying to find patterns of words for a huge input. I was using a
dictionary for this purpose, and after some hours the program crashed with
`MemoryError`.
I modified the program. I created a database via MySQLdb and I inserted there
the values of the `pattern-index`. So for every word I check if it is in the
index and if not I write it into the index with a value. Problem is that the
database approach is too slow.
I was wondering if there is any way to combine dictionaries and database for
example:
if ram <90% usage:
seek into dict
append to dict
else:
if not (seek into dict):
seek into database
append to database
Using a dictionary for the same purpose of inputting 100 kb of data takes ~1.5
sec
Using a database for the same input takes ~84 sec
Original input is 16 GB . I do not know yet how much it will take to process.
Answer: short answer (detailed answer to come):
your use of MySQL was poor, you don't want to commit at all as you just use
the database as an extension of memory. Just removing the commmit should give
you a big improvement
better than using MySQL use [leveldb](http://code.google.com/p/py-leveldb/)
(pip install leveldb) with sync = false
adjust the following values with your memory you want to use
* block_cache_size = 512*1024*1024 #512Mo #the more important
* write_buffer_size = 10*1024*1024 #10Mo
as you have a MemoryError that means you have a 32bits system it means that
the total memory enable for a process can't be more than 4 Go so adjust the
values to fit in min(your system memory,4Go)
|
Selenium - screenshot images taken by headless server are mangled
Question: I am using selenium webdriver (Python version) to take images of a web page
after it loads. When I go to a page and save an image using a python script on
my local computer, it looks fine. However, I am running the script on a server
and there the screenshots are mangled- the edge might be cut off with text
missing, banners on the right side might be pushed to the bottom in a jumbled
fashion, etc. I even tried maximizing the window
driver.get(url)
driver.maximize_window()
time.sleep(4)
driver.save_screenshot('screen.png')
On the server, I cannot load firefox in a headed version and must manually
start/stop the display in my script before/after running selenium
from pyvirtualdisplay.xvnc import XvncDisplay
display = XvncDisplay(rfbport='####')
display.start()
So I'm thinking this might have to do with the settings of my display.
Anyone have any ideas on how to fix this? Thanks
Answer: Try chomium + chromedriver instead. It works for me, even though I didn't have
the problem you describe. Just an idea.
Download chromedriver to /usr/local/bin
<https://sites.google.com/a/chromium.org/chromedriver/downloads> and don't
forget `chmod a+x /usr/local/bin/chromedriver`
I used this blog post: <http://coreygoldberg.blogspot.cz/2011/07/python-
taking-browser-screenshots-with.html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.