text
stringlengths 226
34.5k
|
---|
Euler's method in python
Question: I'm trying to implement [euler's
method](http://en.wikipedia.org/wiki/Euler_method) to approximate the value of
e in python. This is what I have so far:
def Euler(f, t0, y0, h, N):
t = t0 + arange(N+1)*h
y = zeros(N+1)
y[0] = y0
for n in range(N):
y[n+1] = y[n] + h*f(t[n], y[n])
f = (1+(1/N))^N
return y
However, when I try to call the function, I get the error "ValueError: shape
<= 0". I suspect this has something to do with how I defined f? I tried
inputting f directly when euler is called, but gave me errors related to
variables not being defined. I also tried defining f as its own function,
which gave me a division by 0 error.
def f(N):
for n in range(N):
return (1+(1/n))^n
(not sure if N was the appropriate variable to use here...)
Answer: Are you sure you are not trying to implement the Newton's method? Because
Newton's method is used to approximate the roots.
In case you decide to go with Newton's method, here is a slightly changed
version of your code that approximates the square-root of 2. You can change
`f(x)` and `fp(x)` with the function and its derivative you use in your
approximation to the thing you want.
import numpy as np
def f(x):
return x**2 - 2
def fp(x):
return 2*x
def Newton(f, y0, N):
y = np.zeros(N+1)
y[0] = y0
for n in range(N):
y[n+1] = y[n] - f(y[n])/fp(y[n])
return y
print Newton(f, 1, 10)
gives
`[ 1. 1.5 1.41666667 1.41421569 1.41421356 1.41421356 1.41421356 1.41421356
1.41421356 1.41421356 1.41421356]`
which are the initial value and the first ten iterations to the square-root of
two.
Besides this a big problem was the usage of `^` instead of `**` for powers
which is a legal but a totally different (bitwise) operation in python.
|
python lazy translation - add line break to translation string
Question: How do I add line breaks to a lazy translation? I have searched
[django](https://docs.djangoproject.com/en/1.4/topics/i18n/translation/#), SO
& Google, but no information is found.
I have my lazy translation working with multiline below, but the newline /
line breaks are rendered to the screen.
messages.success(
request,
_("If the e-mail address has been registered, you'll receive an e-mail with instructions."
"/n/n"
"If you don't receive this e-mail, check your spam e-mail folder or contact us for assistance."))
I have also tried < b r / >, and backslash n but these are not rendered as new
lines on the django template screen.
Answer: You should use backslash `\n` for newline symbol.
Note that `\n` symbol is the regular whitespace and on HTML page it is looks
like simple space. If you want to show multi-line message then you should use
`<br />` tags and make the message "safe":
from django.utils.safestring import mark_safe
messages.success(request,
mark_safe("If the e-mail address has been registered ..."
"<br /><br />"
"If you don't receive this e-mail, check your spam ...."))
|
My life calculater project
Question: I'm currently working on a life calculator that i have programmed in python. I
need ideas of what to add to it and examples on how to add it and also how do
i add a end control so i can just input end and the program stops. I'm trying
to make this better because i plan to take it to a technology fair im going
to. Here is my code.
print("The Life Calculator")
name = input("What is you're name? ")
age = int(input("age: "))
months = age * 12 #This equals to how many months you have been alive.
days = age * 365 #This equals to how many days you have been alive.
hours = age * 8765.81 #This equals to how many hours you have been alive.
minutes = age * 31556926 #This equals to how many minutes you have been alive.
seconds = age * 3.156e+7 #This equals to how many seconds you have been alive.
miliseconds = age * 3.15569e10 #This equals to how many miliseconds you have been alive.
microseconds = age * 3.156e+13 #This equals to how many microseconds you have been alive.
nanoseconds = age * 3.156e+16 #This equals to how many nanoseconds you have been alive.
print("This is how many months you have been alive.")
print (months) #This shows how many months you have been alive.
print("This is how many days you have been alive.")
print (days) #This shows how many months you have been alive.
print("This is how many hours you have been alive.")
print (hours) #This shows how many hours you have been alive.
print("This is how many minutes you have been alive.")
print (minutes) #This shows how many minutes you have been alive.
print("This is how many seconds you have been alive.")
print (seconds) #This shows how many seconds you have been alive.
print("This is how many miliseconds you have been alive.")
print (miliseconds) #This shows how many miliseconds you have been alive.
print("This is how many microseconds you have been alive.")
print (microseconds) #This shows how many microseconds you have been alive.
print("This is how many nanoseconds you have been alive.")
print (nanoseconds) #This shows how many nanoseconds you have been alive.
lastline = ("this is how long you have been alive, so what are you going to do with the rest of your life?")
print (name)
print (lastline)
Answer: Here is a spiffed-up version.
I took a lot of the repetitive statements and converted them to data:
from collections import namedtuple
TimeUnit = namedtuple("TimeUnit", ["name", "per_year"])
units = [
TimeUnit("decade", 0.1 ),
TimeUnit("month", 12.0 ),
TimeUnit("fortnight", 26.09),
TimeUnit("day", 365.25),
TimeUnit("hour", 8765.81),
TimeUnit("minute", 31556926),
TimeUnit("second", 3.156e+7),
TimeUnit("millisecond", 3.15569e10)
]
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
pass
def main():
print("The Life Calculator")
name = input("What is your name? ")
years = get_float("What is your age? ")
print("You have been alive for:")
for unit in units:
print(" {} {}s".format(years * unit.per_year, unit.name))
print("what are you going to do with the rest of your life, {}?".format(name))
if __name__ == "__main__":
main()
|
Using class/function in another module
Question: I come from a mostly Java background, but have recently been delving into some
Python. I've been mostly getting it, but there's some syntax that seems really
weird to me. I have this project I'm working on that contains multiple files/
classes. I have one class, Mesh.py:
class Mesh:
def __init__(self, name):
#dostuff
that I want to instantiate in another file, Main.py. I noticed two things,
1. I have to import Mesh, which seems odd to me, since it's in my project,
2. To create a Mesh I have to do this:
mesh = Mesh.Mesh('name')
which seems super awkward. Why can't I just do
mesh = Mesh('name')
Am I doing something wrong here, or is this just an unavoidable part of
Python?
Answer: In Python, _every file you create is a module_ and a collection of modules can
be logically grouped as a
[package](https://docs.python.org/2/tutorial/modules.html#packages). Python is
little different than Java, which allows files in the same package to be used
without importing explicitly.
Since a module is a namespace, whenever you use an identifier in a module, it
must be defined in it, otherwise you will get a `NameError`.
When you import a module,
import Mesh
Python understands that you have imported a module and all the items in it can
be referenced with the module's name. If you do
Mesh('name')
you will get an error, because only the `Mesh` module is imported in the
current module, not the `Mesh` class. That is why you have to explicitly
specify
Mesh.Mesh('name')
It means that, you are telling Python that, I am referring to the `Mesh` class
in the `Mesh` module, which I imported.
But in your case, you can import only the particular class from the `Mesh`
module into the current module's namespace, like this
from Mesh import Mesh
And then create an object of it, like this
Mesh('name')
|
How to "join" two text files with python?
Question: I have two txt files like this: txt1:
Foo
Foo
Foo
Foo
txt2:
Bar
Bar
Bar
Bar
How can I concatenate them in a new file by the left and the right side let's
say like this:
Bar Foo
Bar Foo
Bar Foo
Bar Foo
I tried the following:
folder = ['/Users/user/Desktop/merge1.txt', '/Users/user/Desktop/merge2.txt']
with open('/Users/user/Desktop/merged.txt', 'w') as outfile:
for file in folder:
with open(file) as newfile:
for line in newfile:
outfile.write(line)
Answer: Use
[`itertools.izip`](https://docs.python.org/2/library/itertools.html#itertools.izip)
to combine the lines from both the files, like this
from itertools import izip
with open('res.txt', 'w') as res, open('in1.txt') as f1, open('in2.txt') as f2:
for line1, line2 in zip(f1, f2):
res.write("{} {}\n".format(line1.rstrip(), line2.rstrip()))
**Note:** This solution will write lines from both the files only till either
of the files exhaust. For example, if the second file contains 1000 lines and
the first one has only 2 lines, then only two lines from each file is copied
to the result. In case you want lines from the longest file even after the
shortest file exhausted, you can use
[`itertools.izip_longest`](https://docs.python.org/2/library/itertools.html#itertools.izip_longest),
like this
from itertools import izip_longest
with open('res.txt', 'w') as res, open('in1.txt') as f1, open('in2.txt') as f2:
for line1, line2 in izip_longest(f1, f2, fillvalue=""):
res.write("{} {}\n".format(line1.rstrip(), line2.rstrip()))
In this case, even after the smaller file exhausts, the lines from longer file
will still be copied and the `fillvalue` will be used for the lines from the
shorter file.
|
PYTHONPATH sys.path difference
Question: I am having trouble adding a directory to my `PYTHONPATH` The directory is
`/usr/local/lib/python2.7/dist-packages`
When I run
PYTHONPATH=/usr/local/lib/python2.7/dist-packages python -c 'import sys; print sys.path'
I can't find it in the result. Trying things out I noticed the following: The
directory disappears from `sys.path` when `/usr/local/lib/python2.7` is there
as a prefix, e.g. the following works fine:
PYTHONPATH=/usr/local/lib python -c 'import sys; print sys.path'
I am not setting `PYTHONPATH` anywhere else, and I checked running it with
sudo.
Answer: There are several reasons why a path may show up. Make sure you don't hit one
of these:
* The path must exist, non-existing paths are ignored. From the [`PYTHONPATH` documentation](https://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH):
> Non-existent directories are silently ignored.
* Duplicates are removed (the first entry is kept); paths are made absolute (relative to the current working directory) and compared case-insensitively on platforms where this matters.
So if you have a relative path that comes down to the same absolute path in
your `sys.path`, only the first entry is kept.
* After normilization and cleanup, the [`site` module](https://docs.python.org/2/library/site.html) tries to import `sitecustomize` and `usercustomize` modules. These could manipulate `sys.path` too.
You can take a closer look at your `sys.path` right after cleaning and if
there is a `usercustomize` module to be imported by running the `site` module
as a command line tool:
python -m site
It'll print out your `sys.path` in a readable one-line-per-entry format.
|
How to setup rethinkdb with django?
Question: I have followed various posts and tutorials but couldn't find anything that is
relevant. I found a ORM for rethinkdb
"<https://github.com/dparlevliet/rwrapper>" but don't know how to use it? I am
new to to django and python.
Answer: It depends on what you want to do.
* There is no way to simple replacement of Django's ORM with RethinkDB now. However, working with RethinkDB driver is simple enough, and similar to how you would use Django ORM.
* The nearest thing is indeed rwrapper, you can try starting with [this tutorial](http://c2journal.com/2013/03/25/django-and-rethinkdb-a-tutorial/).
* If you don't need to use Model classes, then you just need to find a place to connect to database (or use some sort of Singleton or Factory to connect to the database), and then just `import rethinkdb as r` and `r.connect()` and then just write queries with ReQL.
* If you need realtime data, then Django is not suitable for that at all. You can consider [mixing Django with Tornado](https://github.com/thejsj/django-and-rethinkdb)
|
Flask import error: No module named app. While creating the database with Sqlite
Question: Hi I am very new to flask and I am trying to set up a database using sqlite
with my app. I have the file structure like this
app
|--Static(folder)
|--Templates(folder)
|--__init__.py (empty python file)
|--models.py(containes table classes)
|--app.py (application module)
inside my app.py file I have the following code
import os
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, render_template, url_for, request, redirect, flash
from datetime import datetime
from logging import DEBUG
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'database.db')
db = SQLAlchemy(app)
So when I try to run the command
from app.app import db
in the python shell, I get the error saying that "no module named app". Can
anyone tell me what I am doing wrong here?
Answer: You shouldn't need to run
from app.app import db
This command would import a module from a "app" class called "db" in the file
"app", which you don't have and I don't imagine you're trying to do.
You should just be executing your app from the terminal via
python app.py
This will just execute the code that is in the app.py file.
You can find more about this by following the flask tutorial
[here](http://flask.pocoo.org/docs/0.10/tutorial/setup/)
|
How do I debug a python multiple-sentence generator?
Question: I made my own Python code like this:
import random
# nouns-----------------------------------------------------------------------------------------------------------------
nouns = 'noun1 noun2 noun3 noun4 noun5 noun6 noun7 noun8 noun9 noun10 noun11 noun12 noun13 noun14 noun15 noun16' .split()
def getRandomWord(nounList):
wordIndex = random.randint(0, len(nounList) - 1)
return nounList[wordIndex]
noun_var = getRandomWord(nouns)
# verbs-----------------------------------------------------------------------------------------------------------------
verbs = 'verb1 verb2 verb3 verb4 verb5 verb6 verb7 verb8 verb9 verb10 verb11 verb12 verb13 verb14 verb15 verb16' .split()
def getRandomWord(verbList):
wordIndex = random.randint(0, len(verbList) - 1)
return verbList[wordIndex]
verb_var = getRandomWord(verbs)
# infinitives-----------------------------------------------------------------------------------------------------------
infi = 'verb1 verb2 verb3 verb4 verb5 verb6 verb7 verb8 verb9 verb10 verb11 verb12 verb13 verb14 verb15 verb16' .split()
def getRandomWord(infiList):
wordIndex = random.randint(0, len(infiList) - 1)
return infiList[wordIndex]
infi_var = getRandomWord(infi)
# print strings
for i in range(1):
print (noun_var, verb_var, infi_var)
But whenever I wanted to change the 1 in "Line 25, Char 16" into an input
variable letting you be able to make the choice of how many sentences wanted,
it just repeats the same sentence again and again instead of generating new
ones. Is there another way to make an app with Python with the same principles
or is there a way to fix this?
This code is in Python-3.x
Answer: If you want to display a different sentence in each iteration of your loop,
then _generate_ a new sentence. Right now you're picking 3 random words, and
then printing them over and over again.
for i in range(int(input())):
print (random.choice(nouns), random.choice(verbs), random.choice(infi))
|
Bottle py and Jinja2 global variable
Question: I am using bottle.py framework along with Jinja2 templates in a new
application.
Whenever a user logs into the application I would like to add a new global
Jinja2 variable with the name of the active user, so in a partial template
(the header) I can display this name.
In my python (bottle) file I've tried several things according to what I
googled so far, but no success yet.
This is the last thing I tried inside a function:
import jinja2
env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'))
env.globals['myglobal'] = 'My global'
#env.globals.update({'myglobal': 'My global'})
But, when putting this into the header template: {{myglobal}} it simply
doesn't show up.
Since this is my first time with bottle and jinja2 anyone knows how can
achieve this?
Answer: I have a similar setup, and this works for me using the BaseTemplate built
into bottle:
from bottle import BaseTemplate
BaseTemplate.defaults['myglobal'] = 'My global'
|
Django app crashing on Heroku
Question: I am trying to port an app that runs fine on my computer using runserver to
Heroku. I am new to Django and have never deployed an app on Heroku before. I
am not sure what I am missing.
Here is the heroku error:
2015-01-18T00:59:22.855761+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run
2015-01-18T00:59:22.855803+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
2015-01-18T00:59:22.855877+00:00 app[web.1]: super(Application, self).run()
2015-01-18T00:59:22.856001+00:00 app[web.1]: self.manage_workers()
2015-01-18T00:59:22.856023+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 477, in manage_workers
2015-01-18T00:59:22.856111+00:00 app[web.1]: self.spawn_workers()
2015-01-18T00:59:22.856132+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 542, in spawn_workers
2015-01-18T00:59:22.855899+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 71, in run
2015-01-18T00:59:22.856230+00:00 app[web.1]: time.sleep(0.1 * random.random())
2015-01-18T00:59:22.856252+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 209, in handle_chld
2015-01-18T00:59:22.856491+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
2015-01-18T00:59:22.856303+00:00 app[web.1]: self.reap_workers()
2015-01-18T00:59:22.856324+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 459, in reap_workers
2015-01-18T00:59:22.856408+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2015-01-18T00:59:22.855680+00:00 app[web.1]: Traceback (most recent call last):
2015-01-18T00:59:22.855699+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 11, in <module>
2015-01-18T00:59:22.855732+00:00 app[web.1]: sys.exit(run())
2015-01-18T00:59:22.855825+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 185, in run
2015-01-18T00:59:22.855932+00:00 app[web.1]: Arbiter(self).run()
2015-01-18T00:59:22.855953+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 169, in run
2015-01-18T00:59:23.546103+00:00 heroku[web.1]: Process exited with status 1
2015-01-18T00:59:23.550975+00:00 heroku[web.1]: State changed from starting to crashed
2015-01-18T00:59:25.538419+00:00 heroku[api]: Scale to web=1 by [email protected]
2015-01-18T01:00:20.825543+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"
my wsgi file looks like this:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ssbo.settings")
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
from dj_static import Cling
application = Cling(get_wsgi_application())
application = DjangoWhiteNoise(application)
I have created several settings files (base, local, staging, production). I am
using staging on heroku by setting
DJANGO_SETTINGS_MODULE="ssbo.settings.staging"
Staging file:
DEBUG = True
TEMPLATE_DEBUG = True
WSGI_APPLICATION = 'ssbo.wsgi.application'
SESSION_COOKIE_AGE = 300
SECRET_KEY = get_env_variable("SECRET_KEY")
import dj_database_url
DATABASES = {}
DATABASES['default'] = dj_database_url.config()
base settings file:
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
BASE_DIR = os.path.join(os.path.dirname(__file__), '..')
requirements.txt:
Django==1.7.3
psycopg2==2.5.4
stripe==1.19.0
gunicorn==19.1.1
dj-database-url==0.3.0
whitenoise==1.0.6
dj-static==0.0.6
Procfile:
web: gunicorn ssbo.wsgi
Project structure:
ssbo
app
migrations
static
app
templates
app
admin.py
forms.py
models.py
views.py
ssbo
settings
base.py
local.py
production.py
staging.py
urls.py
wsgi.py
manage.py
Answer: Running the gunicorn server with the --preload flag revealed the problem. The
Procfile had an incorrect argument.
|
PythonAnywhere Django 404 Page Not Found for Homepage
Question: I know there is a similar post like this one. I've reviewed it and it is quite
different from what I'm experiencing at the moment on
[Pythonanywhere.com](http://www.pythonanywhere.com)
I'm trying to deploy my rango tutorial project that I completed through
tangowithdjango.com onto Pythonanywhere.com. When I try to open the site (url
is ragzputin.pythonanywhere.com), I get this page:

Here's my urls.py file for my project:
from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^rango/', include('rango.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
If you guys need some extra information, here's my app urls.py (app name is
rango):
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name="index"),
url(r'^about/$', views.about, name="about"),
url(r'^add_category/$', views.add_category, name="add_category"),
url(r'^category/(?P<category_name_url>\w+)/add_page/$', views.add_page, name="add_page"),
url(r'^category/(?P<category_name_url>\w+)/$', views.category, name="category"),
url(r'^register/$', views.register, name="register"),
url(r'^login/$', views.user_login, name="login"),
url(r'^restricted/$', views.restricted, name="restricted"),
url(r'^logout/$', views.user_logout, name="logout"),
url(r'^profile/$', views.profile, name="profile"),
url(r'^goto/$', views.track_url, name="track_url"),
url(r'^like_category/$', views.like_category, name="like_category"),
url(r'^suggest_category/$', views.suggest_category, name="suggest_category"),
url(r'^auto_add_page/$', views.auto_add_page, name="auto_add_page"),
)
As you can see from the 404 page above, the server is not able to get to the
main page which starts with '^rango/'. Any suggestions?
Answer: You should add url for home page into the project's urls.py:
urlpatterns = patterns('',
url(r'^$', 'rango.views.index', name="index"),
url(r'^rango/', include('rango.urls')),
url(r'^admin/', include(admin.site.urls)),
)
And don't forget to remove the same (first) url from `rango/urls.py`.
The other option is to add redirect from `/` to `/rango/`. If you choose this
option then project's urls.py should be:
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', RedirectView.as_view(url='/rango/')),
url(r'^rango/', include('rango.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Of course in this case `rango/urls.py` should be untouched.
|
How to to make a file private by securing the url that only authenticated users can see
Question: I was wondering if there is a way to secure an image or a file to be hidden
when it is not authenticated.
Suppose there is an image in my website which can only be seen if that user is
authenticated. But the thing is I can copy the url or open the image in the
new tab.
`http://siteis.com/media/uploaded_files/1421499811_82_Chrysanthemum.jpg`
And again, even if I am not authenticated, I can view that particular image by
going to that url. So, my question is or my problem is, how do I secure the
files, so that only authenticated users will see. I hope I was clear, if not
please ask. I will really appreciate if you could help me. And if possible in
a pythonic/django way. Thank you.
**Update:**
view:
def pictures(request, user_id):
user = User.objects.get(id=user_id)
all = user.photo_set.all()
return render(request, 'pictures.html',{
'pictures': all
})
models:
def get_upload_file_name(instance, filename):
return "uploaded_files/%s_%s" %(str(time()).replace('.','_'), filename)
class Photo(models.Model):
photo_privacy = models.CharField(max_length=1,choices=PRIVACY, default='F')
user = models.ForeignKey(User)
image = models.ImageField(upload_to=get_upload_file_name)
settings:
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "myproject", "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "myproject", "static", "media")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "myproject", "static", "static"),
)
**Update:**
template:
{% if pictures %}
{% for photo in pictures %}
<img src="/media/{{ photo.image }}" width="300" alt="{{ photo.caption }}"/>
{% endfor %}
{% else %}
<p>You have no picture</p>
{% endif %}
url:
url(r'^(?P<user_name>[\w@%.]+)/photos/$', 'pictures.views.photos', name='photos'),
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Answer: By securing any media file not to serve by anonymous user, better way url
protection.
**Code ( Updated ):**
from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from django.views.static import serve
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import HttpResponse
@login_required
def protected_serve(request, path, document_root=None):
try:
obj = Photobox.objects.get(user=request.user.id)
obj_image_url = obj.image.url
correct_image_url = obj_image_url.replace("/media/", "")
if correct_image_url == path:
return serve(request, path, document_root)
except ObjectDoesNotExist:
return HttpResponse("Sorry you don't have permission to access this file")
url(r'^{}(?P<path>.*)$'.format(settings.MEDIA_URL[1:]), protected_serve, {'file_root': settings.MEDIA_ROOT}),
Note: previously any logged in user can access any page, now this update
restrict non user to view other files...
|
how to disable all webkit browser plugins?
Question: I'm using Ubuntu 14.04.
I have [Pipelight](https://launchpad.net/pipelight) installed - this NPAPI
browser plugin allows me to view Silverlight & new Flash based stuff in
Firefox.
However this has an unfortunate side effect - all web-browsers that support
NPAPI plugins such as WebKit also load this plugin.
Programatically, I would like to disable all browser plugins when I create the
WebKit.WebView - thus to my question. How do I do this?
* * *
Investigations:
I've looked at using WebKit2 - this does work probably because WebKit2 does
not have NPAPI support. However I cannot use this method because Rhythmbox by
default has another native plugin which is WebKit i.e. I'm creating another
Rhythmbox plugin. When I attempt to load both a WebKit.WebView and
WebKit2.WebView at the same time then the process hangs.
I've looked at using [WebKit.WebSettings](https://lazka.github.io/pgi-
docs/#WebKit-3.0/classes/WebSettings.html#WebKit.WebSettings) and its [enable-
plugins](https://lazka.github.io/pgi-
docs/#WebKit-3.0/classes/WebSettings.html#WebKit.WebSettings.props.enable_plugins)
property but it appears you cannot apply the new WebSettings instance until
after the WebView has been created (thus the pipelight browser plugin is
already loaded).
Again - I've tried to assign the new WebSettings instance via the constructor
but no joy: `x = WebKit.WebView(settings=webkit_settings)`
When you have pipelight installed a simple test program (web.py) like this
shows the issue:
from gi.repository import WebKit
webkit_settings = WebKit.WebSettings.new()
webkit_settings.props.enable_plugins=False
x = WebKit.WebView.new()
x.set_settings(webkit_settings)
Then running `python web.py` shows an example output of
[PIPELIGHT:LIN:unknown] attached to process.
[PIPELIGHT:LIN:unknown] checking environment variable PIPELIGHT_SILVERLIGHT5_0_CONFIG.
[PIPELIGHT:LIN:unknown] searching for config file pipelight-silverlight5.0.
[PIPELIGHT:LIN:unknown] trying to load config file from '/home/foss/.config/pipelight-silverlight5.0'.
[PIPELIGHT:LIN:unknown] unrecognized configuration key 'diagnosticmode'.
[PIPELIGHT:LIN:unknown] sandbox not found or not installed!
[PIPELIGHT:LIN:silverlight5.0] using wine prefix directory /home/foss/.wine-pipelight.
I've posed this
[question](https://answers.launchpad.net/pipelight/+question/260874) to the
Pipelight developers and they have indicated that I need to disable plugins
via the WebKit engine. As you can see - I thought WebKit2 was my solution but
I cannot use this as stated above.
I've seen this [stackoverflow
question](http://stackoverflow.com/questions/2209844/suppress-plugin-loading-
in-webkit) but I'm not really after disabling specific plugins - at least I
dont think so - just want to disable all external plugins
I'm writing this using Python3 but I dont think the python version is the
issue here since I've run the test program using both the python and python3
interpreter and the same results are seen.
Answer: I hacked this by writing my own access() function which calls strstr(pathname,
"/plugins/"); If this returns non-null function sets errno to ENOENT and
returns -1.
Otherwise my access() calls the original access() (system call wrapper) from c
library.
In c program such a function can just be implemented, for other programs
separate c module and LD_PRELOAD can be used...
like this:
static void * dlsym_next(const char * symbol)
{
void * sym = dlsym(RTLD_NEXT, symbol);
char * str = dlerror();
if (str != null)
exit(1);
return sym;
}
#define set_next(name) *(void**)(&name##_next) = dlsym_next(#name)
int access(const char * pathname, int mode)
{
static int (*access_next)(const char *, int) = NULL;
if (! access_next)
set_next(access);
if (strstr(pathname, "/plugins/") != NULL) {
errno = ENOENT;
return -1;
}
return access_next(pathname, mode);
}
|
asyncio.run_until_complete block after future is set
Question: I'm learning asyncio in python3, I wrote a simple RPC server and client for
study, but when i test it with asyncio.run_until_complete, it blocks after the
future is already set, the code is as below, checkout the **main** part. i'm
using python 3.4.2
import asyncio
import struct
_req_struct = struct.Struct('<4i')
_req_size = _req_struct.size
_resp_struct = struct.Struct('<3i')
_resp_size = _resp_struct.size
class SimpleRPCClient(asyncio.Protocol):
_transport = None
def __init__(self):
self._pendings = {}
self.seq_id = 0
self._cached = bytearray()
def connection_made(self, transport):
"""
First event, create ref to transport
"""
self._transport = transport
def send(self, data):
"""
proxy to transport.write
"""
self._transport.write(data)
def data_received(self, data):
c = self._cached
c.extend(data)
cursor = 0
while len(self._cached) >= (cursor + _resp_size):
rid, status, result = _resp_struct.unpack(
c[cursor:cursor + _resp_size])
if rid in self._pendings:
f = self._pendings.pop(rid)
f.set_result(result)
print("future result: ", f.result())
def calc(self, oprand, op1, op2):
rid = self.seq_id
self.seq_id += 1
future = asyncio.Future()
self._pendings[rid] = future
self.send(_req_struct.pack(rid, oprand, op1, op2))
return future
if __name__ == '__main__':
loop = asyncio.get_event_loop()
host = "127.0.0.1"
port = 8087
_tr, client = loop.run_until_complete(loop.create_connection(
SimpleRPCClient,
host,
port))
f = client.calc(1, 3, 5)
loop.run_until_complete(f)
print("final result: ", f.result())
the function is to calc 3+5, when i run the program, it correctly display the
result in data_received like
> future result: 8
however the program blocks after that, never shows the final result, the
future is successfully set but the function do not return, why is that?
the server side is attached below if you'd like to run it
import asyncio
import struct
_req_struct = struct.Struct('<4i')
_req_size = _req_struct.size
_resp_struct = struct.Struct('<3i')
_resp_size = _resp_struct.size
class SimpleRPCServer(object):
def build_protocol(self):
return SimpleRPCConnection()
class SimpleRPCConnection(asyncio.Protocol):
_transport = None
def __init__(self):
self._cached = bytearray()
def connection_made(self, transport):
"""
First event, create ref to transport
"""
self._transport = transport
def send(self, data):
"""
proxy to transport.write
"""
self._transport.write(data)
def data_received(self, data):
c = self._cached
c.extend(data)
cursor = 0
while len(self._cached) >= (cursor + _req_size):
seq_id, oprand, op1, op2 = _req_struct.unpack(
c[cursor:cursor + _req_size])
self.respond(seq_id, oprand, op1, op2)
cursor += _req_size
if cursor > len(self._cached):
self._cached.clear()
else:
self._cached[:cursor] = b''
def respond(self, seq_id, oprand, op1, op2):
if oprand == 1:
self.send(_resp_struct.pack(seq_id, 0, op1 + op2))
elif oprand == 2:
self.send(_resp_struct.pack(seq_id, 0, op1 - op2))
elif oprand == 3:
self.send(_resp_struct.pack(seq_id, 0, op1 * op2))
elif oprand == 4:
try:
self.send(_resp_struct.pack(seq_id, 0, op1 / op2))
except ZeroDivisionError:
self.send(_resp_struct.pack(seq_id, 1, 0))
else:
self.send(_resp_struct.pack(seq_id, 0xff, 0))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
server = SimpleRPCServer()
loop.run_until_complete(loop.create_server(
server.build_protocol,
"0.0.0.0",
8087))
loop.run_forever()
Answer: The loop in your SimpleRPCClient.data_received() method never stop.
|
Are Mixin classes abstract base classes
Question: Are Mixin classes abstract base classes? In the example below, the calls to
test_base would fail because python wouldn't be able to resolve
self.assertEqual for example.
Also, is PyCharm incorrect as flagging Mixin classes like the one below has
having unresolved attribute errors?
class TestConverterMixin(object):
def setUp(self):
self.alt_hasher = getattr(hash, self.converter.__class__.__name__)
def test_base(self):
with self.settings(PASSWORD_HASHERS=[self.hasher, ]):
load_hashers(settings.PASSWORD_HASHERS)
for password in PASSWORDS:
orig = self.alt_hasher.encrypt(password)
conv = self.converter.from_orig(orig)
# see if we get a working hash:
self.assertTrue(check_password(password, conv))
# convert back and test with passlib:
back = self.converter.to_orig(conv)
self.assertEqual(orig, back)
Answer: Are Mixin classes AbstractBaseClasses? The most accurate answer for your case
is no but it probably should be.
Your class as a stand-alone cannot survive for you reasons you pointed out. By
making it an [ABC](https://docs.python.org/3/library/abc.html#module-abc) you
explicitly tell anyone looking at your class (like pycharm) that
from abc import ABCMeta, abstractmethod
class TestConverterMixin(object):
__metaclass__ = ABCMeta
@abstractmethod
def assertEqual(self, other):
"Need concrete implementation somewhere"
.... the rest of your code
The problem is that you would need this for all of the other methods
(self.AssertTrue, self.converter etc). You could have something else in mind
but this seriously looks like just a subclass of
[`unittest.TestCase`](https://docs.python.org/2/library/unittest.html) to me.
Oh and was PyCharm wrong. No, they got it right. If you made this an ABC or a
subclass of TestCase, they would not have complained. If you used Interfaces,
like zope.Interface, pycharm and the like usually get that wrong since they
don't understand the registration and lookup process.(it is outside the python
core)
|
reading middlebury 'flow' files with python (bytes array & numpy)
Question: I'm trying to read a .flo file as a numpy 2Channels image.
The format is described like this:
".flo" file format used for optical flow evaluation
Stores 2-band float image for horizontal (u) and vertical (v) flow components.
Floats are stored in little-endian order.
A flow value is considered "unknown" if either |u| or |v| is greater than 1e9.
bytes contents
0-3 tag: "PIEH" in ASCII, which in little endian happens to be the float 202021.25
(just a sanity check that floats are represented correctly)
4-7 width as an integer
8-11 height as an integer
12-end data (width*height*2*4 bytes total)
the float values for u and v, interleaved, in row order, i.e.,
u[row0,col0], v[row0,col0], u[row0,col1], v[row0,col1], ...
(Excerpt from this [readme](http://vision.middlebury.edu/flow/code/flow-
code/README.txt))
Here's my code but I'm kind of stuck, I don't know how to read the file as a 2
Channels numpy 2D array.
import numpy as np
import os
# test.flo, 512*512 optical flow file
f = open('test.flo', 'rb')
f.seek(11, os.SEEK_SET) # skip header bytes
data_array = np.fromfile(f, np.float16)
data_2D = np.resize(data_array, (512, 512))
Maybe someone knows how to do that ?
Answer: Try this. I've tested it on one .flo file so far.
import numpy as np
import os
import sys
# WARNING: this will work on little-endian architectures (eg Intel x86) only!
if '__main__' == __name__:
if len(sys.argv) > 1:
with open(sys.argv[1], 'rb') as f:
magic = np.fromfile(f, np.float32, count=1)
if 202021.25 != magic:
print 'Magic number incorrect. Invalid .flo file'
else:
w = np.fromfile(f, np.int32, count=1)
h = np.fromfile(f, np.int32, count=1)
print 'Reading %d x %d flo file' % (w, h)
data = np.fromfile(f, np.float32, count=2*w*h)
# Reshape data into 3D array (columns, rows, bands)
data2D = np.resize(data, (w, h, 2))
else:
print 'Specify a .flo file on the command line.'
|
Python Checking if prime number
Question: so...this is my code down below. I altered it all ways I can think of, but
regardless of what I do it will ether say all the numbers are prime or all the
numbers are not prime. I was hoping someone can point out the obvious error.
Currently this code says all numbers are not prime. Thanks.
import math
x = int(input('Enter a number: '))
def isPrime(x):
if x==2:
print ("The number you entered is not Prime.")
return
i = 2
x = int(math.sqrt(x))
while i < x+1:
if x%i==0:
print ("The number you entered is not Prime.")
return
i = i+1
print ("This number is Prime")
return
isPrime(x)
Answer: The main bug is here:
x = int(math.sqrt(x))
You are altering `x`, so the subsequent divisibility checks incorrectly use
this altered value of `x`.
You should store the square root in a different variable:
sqrt_x = int(math.sqrt(x))
while i < sqrt_x + 1:
...
Also, the number 2 is prime since it's only divisible by itself and one.
|
running django python 3.4 on mod_wsgi with apache2
Question: Hi I am getting the error below when going to the website url on ubuntu server
14.10 running apache 2 with mod_wsgi and python on django.
My django application uses python 3.4 but it seems to be defaulting to python
2.7, I am unable to import image from PIL and AES from pycrypto.
> ImportError at /
> cannot import name _imaging
> Request Method: GET
> Request URL:
> Django Version: 1.7.3
> Exception Type: ImportError
> Exception Value:
> cannot import name _imaging
> Exception Location: /usr/local/lib/python3.4/dist-packages/PIL/Image.py in
> , line 63
> Python Executable: /usr/bin/python
> Python Version: 2.7.6
> Python Path:
> ['/var/www/blabla',
> '/usr/local/lib/python3.4/dist-packages',
> '/usr/lib/python2.7',
> '/usr/lib/python2.7/plat-x86_64-linux-gnu',
> '/usr/lib/python2.7/lib-tk',
> '/usr/lib/python2.7/lib-old',
> '/usr/lib/python2.7/lib-dynload',
> '/usr/local/lib/python2.7/dist-packages',
> '/usr/lib/python2.7/dist-packages',
> '/var/www/blabla',
> '/usr/local/lib/python3.4/dist-packages']
>
Answer: I believe that mod_wsgi is compiled against a specific version of python, so
you need a py3.4 version of mod_wsgi. You may be able to get one from your
os's package repository or you can build one without too much drama. From
memory you'll need gcc and python-dev packages (python3-dev?) to build.
OK, quick google, for ubuntu 14.10: `sudo apt-get install libapache2-mod-wsgi-
py3` should install a py3 version of mod_wsgi (will probably want to remove
the existing py2 version).
Adding a shebang line won't do any good as the python interpreter is already
loaded before the wsgi.py script is read.
|
Understanding Python documentation: how to know what a function returns?
Question: I am having trouble understanding the background assumptions for reading
Python documentation.
An example: Documentation for the `importlib.import_module` function can be
found at
<https://docs.python.org/3/library/importlib.html#importlib.import_module>.
The function documentation does not specify a return value for the function,
but it (maybe obviously) returns the module it has just loaded.
I feel like there are actually a lot of functions for which the return value
is not specified. I'm trying to decide which of the following options is
closest to the truth.
1. The documentation of this function happens to be incomplete. Don't be so paranoid.
2. Whenever there is no specified return value, the function is assumed to be sufficiently auto-documenting that you can work it out. Just assign a name to the return value: `foo = f(bar)` and then `print(foo)`.
3. There is a conventional way of knowing what the return value is, and I need to learn the convention.
Case 3 is obviously the one that really worries me!
Any advice would be much appreciated.
Answer: The [documentation for
`import_lib.import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module)
says what it returns.
> The most important difference is that import_module() returns the specified
> package or module (e.g. pkg.mod), while _ _import__() returns the top-level
> package or module (e.g. pkg).
Generally speaking: The documentation might be incomplete in places, if it is,
do not assume it's a convention you know nothing about.
|
Calling a python script which has input Fields
Question: I am writing a Python script that has to call a second python script which has
input fields. The normal way to call the second script in Linux command window
is:
python 2ndpythonscript.py input_variable output_variable
Now, I want to call this script from inside the first script. How do I do it?
Thanks in advance.
Answer: Use the [`subprocess`](https://docs.python.org/2/library/subprocess.html)
module, e.g.:
import subprocess
retcode = subprocess.call(['python', '2ndpythonscript.py', 'input_variable', 'output_variable'])
There are different specialized functions in the module which you can use if
you want only the return code, only the output, both, stdout/stderr redirected
in custom pipes and so on.
|
Python-Selenium won't wait for my website to refresh?
Question: I am trying to test that logged in users can logout.
To tell Selenium I am logged in I [cookie-jack the
sessionid](http://stackoverflow.com/a/27990317/1075247), like so:
@step(r'I am logged in as "(\w*)"')
def log_in(step, name):
can_login = world.client.login(username=name, password=name)
if can_login:
session_key = world.client.cookies['sessionid'].value
world.browser.add_cookie({'name':'sessionid', 'value':session_key})
world.browser.get(world.browser.current_url)
from time import sleep #Really should have to do this
sleep(100)
else:
raise Exception("Could not login with those credentials")
I need to refresh for the html to change on 'login', but selenium is taking so
long to refresh the page (it's on localhost, which I know can have problems).
I do have an implicit wait in my terrain.py:
world.browser.implicitly_wait(10)
But I don't think it's taking effect. How can I tell selenium to wait for the
page to load each time?
Answer: Implicit wait would not help since it is just telling how long to wait while
finding an element.
Instead, you need to [explicitly wait](http://selenium-
python.readthedocs.org/en/latest/waits.html#explicit-waits) for an element
appearing after the page load:
world.browser.get(world.browser.current_url)
element = WebDriverWait(world.browser, 50).until(
EC.presence_of_element_located((By.ID, "header"))
)
This would tell selenium to wait for at most 50 seconds, checking element
existence every 500 milliseconds, think about it as polling.
|
wxPython in Python 3.4.1
Question: I'm relatively new to Python programming, so apologies in advance if this
question seems stupid. I'm trying to download a new Python editor (drpython)
that is written with wxpython. I have Python 3.4.1 64-bit on a Windows 8.1
machine.
I was under the impression that wxpython was bundled into the standard library
in Python 3, yet whenever I try to use applications that utilize it I get a
'can't import' error. On the wxpython website, it seems they only have
downloads for Python 2.
Is wxpython not supported on Python 3.4? Has anyone else had trouble using
wxpython with Python 3.4?
Answer: wxPython is not part of Python. You may be thinking of Tkinter, a UI toolkit
that is included with Python. Currently, wxPython is only supported on Python
3 via the Phoenix project. At the time of this writing, Project Phoenix has
the core wxPython widgets ported, but much of the 3rd party widgets are not.
As already mentioned, you can read about Phoenix here:
* <http://wiki.wxpython.org/ProjectPhoenix>
You need the latest version of pip to install a wheel. Make sure you have the
latest. Once you do, you can do something like this to install wxPython
Phoenix:
pip install -U --pre -f http://wxpython.org/Phoenix/snapshot-builds/ wxPython_Phoenix
See also:
* <https://groups.google.com/forum/#!searchin/wxpython-dev/pip>$20install/wxpython-dev/LmGIrQyh7jc/_qe3FiVJv1MJ
|
What is the simplest way to get from MIDI to real audio coming out my speakers (sound synthesis) in Python?
Question: I'm starting work on an app that will need to create sound from lots of pre-
loaded ".mid" files.
I'm using Python and Kivy to create an app, as I have made an app already with
these tools and they are the only code I know. The other app I made uses no
sound whatsoever.
Naturally, I want to make sure that the code I write will work cross-platform.
Right now, I'm simply trying to prove that I can create any real sound from a
midi note.
I took this code suggested from another answer to a similar question using
FluidSynth and Mingus:
from mingus.midi import fluidsynth
fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2',"alsa")
fluidsynth.play_Note(64,0,100)
But I hear nothing and get this error:
fluidsynth: warning: Failed to pin the sample data to RAM; swapping is possible.
Why do I get this error, how do I fix it, and is this the simplest way or even
right way?
Answer: I could be wrong but I don't think there is a "0" channel which is what you
are passing as your second argument to .play_Note(). Try this:
fluidsynth.play_Note(64,1,100)
or (from some
[documentation](https://code.google.com/p/mingus/wiki/refMingusMidiFluidsynth))
from mingus.containers.note import Note
n = Note("C", 4)
n.channel = 1
n.velocity = 50
fluidSynth.play_Note(n)
UPDATE:
There are references to only channels 1-16 in the source code for that method
with the default channel set to 1:
def play_Note(self, note, channel = 1, velocity = 100):
"""Plays a Note object on a channel[1-16] with a \
velocity[0-127]. You can either specify the velocity and channel \
here as arguments or you can set the Note.velocity and Note.channel \
attributes, which will take presedence over the function arguments."""
if hasattr(note, 'velocity'):
velocity = note.velocity
if hasattr(note, 'channel'):
channel = note.channel
self.fs.noteon(int(channel), int(note) + 12, int(velocity))
return True
|
python global name 'collections' is not defined even I imported collections
Question: The following is config.py:
from collections import OrderedDict
def test_config(fileName):
tp_dict = collections.OrderedDict()
with open("../../config/" + fileName, 'r') as myfile:
file_str = myfile.read().replace(' ', '').split('\n')
tp_list = []
for i, x in enumerate(file_str):
x = x.strip()
try:
key = x[:x.index(':')].strip()
value = x[x.index(':')+1:]
if key == 'testpoint':
pass
else:
tp_dict[key] = value.strip().split(',')
except ValueError,e:
pass
if i % 4 == 0 and i != 0:
tp_list.append(tp_dict.copy())
return tp_list
I'm using the function in another file test.py:
import config
a = config.test_config('test.txt')
NameError: global name 'collections' is not defined
But if I copy paste the whole code from config.py to the top of test.py, and
then use the function, then I have no error(See code below). Can anybody
explain this to me please? I'm so so so confused. Thank you very much!
"""
This is test.py
"""
from collections import OrderedDict
def test_config(fileName):
tp_dict = collections.OrderedDict()
with open("../../config/" + fileName, 'r') as myfile:
file_str = myfile.read().replace(' ', '').split('\n')
tp_list = []
for i, x in enumerate(file_str):
x = x.strip()
try:
key = x[:x.index(':')].strip()
value = x[x.index(':')+1:]
if key == 'testpoint':
pass
else:
tp_dict[key] = value.strip().split(',')
except ValueError,e:
pass
if i % 4 == 0 and i != 0:
tp_list.append(tp_dict.copy())
return tp_list
a = test_config('test.txt')
Answer: Change `from collections import OrderedDict` to `import collections`.
|
What is wrong with this python calculator program? (tkinter)
Question: The error reads as:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/__init__.py", line 1533, in __call__
return self.func(*args)
File "/Users/JackPottage/Documents/PythonProjects/Calculator/Calculator.py", line 76, in equals
while num1[g] is not "+" or "-" or "*" or "/":
IndexError: string index out of range
The code is:
import sys
from tkinter import *
root=Tk()
root.title("Calculator")
frame=Frame(root)
frame.pack()
topframe=Frame(root)
topframe.pack()
s=1
def clear():
txtDisplay.delete(0,END)
return
def one():
global s
txtDisplay.insert(s,"1")
s+=1
def two():
global s
txtDisplay.insert(s,"2")
s+=1
def three():
global s
txtDisplay.insert(s,"3")
s+=1
def four():
global s
txtDisplay.insert(s,"4")
s+=1
def five():
global s
txtDisplay.insert(s,"5")
s+=1
def six():
global s
txtDisplay.insert(s,"6")
s+=1
def seven():
global s
txtDisplay.insert(s,"7")
s+=1
def eight():
global s
txtDisplay.insert(s,"8")
s+=1
def nine():
global s
txtDisplay.insert(s,"9")
s+=1
def zero():
global s
txtDisplay.insert(s,"0")
s+=1
def plus():
global s
txtDisplay.insert(s,"+")
s+=1
def minus():
global s
txtDisplay.insert(s,"-")
s+=1
def times():
global s
txtDisplay.insert(s,"*")
s+=1
def divide():
global s
txtDisplay.insert(s,"/")
s+=1
def equals():
global num1
print(num1)
g=0
number1=str("")
while num1[g] is not "+" or "-" or "*" or "/":
number1=str(number1)+str(num1[g])
print(number1)
g=+1
One= Button(topframe, bd=8, text="1", bg="green", command=one)
One.grid(row=1, column=0)
Two= Button(topframe, bd=8, text="2", bg="green", command=two)
Two.grid(row=1, column=1)
Three= Button(topframe, bd=8, text="3", bg="green", command=three)
Three.grid(row=1, column=2)
Four= Button(topframe, bd=8, text="4", bg="green", command=four)
Four.grid(row=2, column=0)
Five= Button(topframe, bd=8, text="5", bg="green", command=five)
Five.grid(row=2, column=1)
Six= Button(topframe, bd=8, text="6", bg="green", command=six)
Six.grid(row=2, column=2)
Seven= Button(topframe, bd=8, text="7", bg="green", command=seven)
Seven.grid(row=3, column=0)
Eight= Button(topframe, bd=8, text="8", bg="green", command=eight)
Eight.grid(row=3, column=1)
Nine= Button(topframe, bd=8, text="9", bg="green", command=nine)
Nine.grid(row=3, column=2)
Zero= Button(topframe, bd=8, text="0", bg="green", command=zero)
Zero.grid(row=4, column=0)
num1=""
txtDisplay=Entry(frame, textvariable=num1, insertwidth=1, font=30, bg="Dark Orange")
txtDisplay.grid(columnspan=3)
Equals= Button(topframe, bd=8, text="=", bg="green", command=equals)
Equals.grid(row=4, column=2)
Clear= Button(topframe, bd=8, text="C", bg="green", command=clear)
Clear.grid(row=4, column=1)
Plus= Button(topframe, bd=8, text="+", bg="green", command=plus)
Plus.grid(row=1, column=3)
Minus= Button(topframe, bd=8, text="-", bg="green", command=minus)
Minus.grid(row=2, column=3)
Times= Button(topframe, bd=8, text="*", bg="green", command=times)
Times.grid(row=3, column=3)
Divide= Button(topframe, bd=8, text="/", bg="green", command=divide)
Divide.grid(row=4, column=3)
root.mainloop()
My main question would be not only what errors exist in my code, but what is
meant by: string index out of range.
Any help would be appreciated, as I am still rather new to programming. Thanks
in advance.
It is worth noting the program is by no means finished.
Answer: The first time you initialize `num1`, it's set to `""` and never changes,
therefore raising an error when trying to access the index 0. But that's not
the only problem, see Martijn's comments for more.
|
In Python, How can I get the next and previous key:value of a particular key in a dictionary?
Question: Okay, so this is a little hard to explain, but here goes:
I have a dictionary, which I'm adding content to. The content is a hashed
username (key) with an IP address (value). I was putting the hashes into an
order by running them against base 16, and then using Collection.orderedDict.
So, the dictionary looked a little like this:
d = {'1234': '8.8.8.8', '2345':'0.0.0.0', '3213':'4.4.4.4', '4523':'1.1.1.1', '7654':'1.3.3.7', '9999':'127.0.0.1'}
What I needed was a mechanism that would allow me to pick one of those keys,
and get the key/value item one higher and one lower. So, for example, If I
were to pick 2345, the code would return the key:value combinations
'1234:8.8.8.8' and '3213:4.4.4.4'
So, something like:
for i in d:
while i < len(d)
if i == '2345':
print i.nextItem
print i.previousItem
break()
Answer: As seen in the [`OrderedDict` source
code](https://hg.python.org/cpython/file/2.7/Lib/collections.py#l69), if you
have a key and you want to find the next and prev in O(1) here's how you do
that.
>>> from collections import OrderedDict
>>> d = OrderedDict([('aaaa', 'a',), ('bbbb', 'b'), ('cccc', 'c'), ('dddd', 'd'), ('eeee', 'e'), ('ffff', 'f')])
>>> i = 'eeee'
>>> link_prev, link_next, key = d._OrderedDict__map['eeee']
>>> print 'nextKey: ', link_next[2], 'prevKey: ', link_prev[2]
nextKey: ffff prevKey: dddd
This will give you next and prev by insertion order. If you add items in
random order then just keep track of your items in sorted order.
|
My python in virtual-env is 2.7 but the Django debug screen shows the system's 2.6.6
Question: So inside of my virtual env, if I activate it and type `python`, version 2.7
is opened, as it should.
When an error arises in Django, it shows version 2.6 which is the system
default. Here is what my Apache configuration looks like:
<VirtualHost *:80>
ServerName www.mysite.com
ErrorLog /var/www/virtualenv-2.7/django-error-log
Alias /static/ /var/www/virtualenv-2.7/mysite/mainapp/static/
WSGIDaemonProcess mysite python-path=/var/www/virtualenv-2.7/mysite:/var/www/virtualenv-2.7/lib/python2.7/site-packages
WSGIProcessGroup mysite
WSGIScriptAlias / /var/www/virtualenv-2.7/mysite/mysite/wsgi.py
<Directory /var/www/virtualenv-2.7>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
WSGISocketPrefix /var/run/wsgi
WSGIPythonPath /var/www/virtualenv-2.7/mysite:var/www/virutalenv-2.7/lib/python2.7/site-packages
My wsgi.py:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
When I `service httpd restart`, this is what is put in the apache error logs:
[Mon Jan 19 20:19:03 2015] [notice] caught SIGTERM, shutting down
[Mon Jan 19 20:19:04 2015] [notice] SELinux policy enabled; httpd running as context unconfined_u:system_r:httpd_t:s0
[Mon Jan 19 20:19:04 2015] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Mon Jan 19 20:19:04 2015] [notice] Digest: generating secret for digest authentication ...
[Mon Jan 19 20:19:04 2015] [notice] Digest: done
[Mon Jan 19 20:19:04 2015] [notice] Apache/2.2.15 (Unix) DAV/2 mod_wsgi/3.2 Python/2.6.6 configured -- resuming normal operations
Any idea why Django does not use 2.7 found in the virtual env?
Answer: The `mod_wsgi` module is compiled against the system version of Python; the
clue is in the startup message:
mod_wsgi library version
vvvvvvvvvvvv
Apache/2.2.15 (Unix) DAV/2 mod_wsgi/3.2 Python/2.6.6 configured
^^^^^^^^^^^^
Python version
To fix this, you can either compile mod_wsgi against the version of Python you
need, or use the
[`WSGIPythonHome`](https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPythonHome)
configuration directive:
> Used to indicate to Python when it is initialised where its library files
> are installed. This should be defined where the Python executable is not in
> the PATH of the user that Apache runs as, or where a system has multiple
> versions of Python installed in different locations in the file system,
> especially different installations of the same major/minor version, and the
> installation that Apache finds in its PATH is not the desired one.
>
> **This directive can also be used to indicate a Python virtual environment
> created using a tool such as virtualenv, to be used for the whole of
> mod_wsgi.**
In your Apache configuration, add the following and then reload the server:
WSGIPythonHome /var/www/virtualenv-2.7/lib/python2.7
|
Python & Tkinter - Interface freezes by clicking on a button
Question: I'm working on a project where I must create a Mastermind game interface using
Python language, so I use Tkinter.
The program itself seems to work fine: you can choose the length of the color
code to find and the number of turns you have to find the good color code,
using the Option Menu, and when you click on "Start" the game launch at the
very first turn (you have a line of buttons who changes their color by
clicking on them, and an "OK" button to go to the next turn).
And here's the problem: a very few times the game runs correctly, but almost
always, the game "freezes" when you click on the "OK" button : nothing
happens, you can't interact no more with the game and you can't even close it
by clicking on the close button.
So here is the code:
import RPi.GPIO as GPIO
import time
import smbus
import my_lcd_lib
import os
#import mpg321
from Tkinter import *
from random import randint
# creation de l'interface -------------------------------
class Menu(Frame):
def __init__(self, fenetre, **kwargs):
Frame.__init__(self, fenetre, width=768, height=568, **kwargs)
self.pack(fill=BOTH)
self.message = Label(self, text="Menu")
self.message.pack()
self.Longcode = 5
self.Nbtours = 10
self.Tour = 1
self.Couleurs = ['red', 'yellow', 'green', 'blue', 'pink','purple', 'brown', 'gray', 'black', 'white', "red"]
self.bouton_demarrer = Button(self, text="Start",command=self.Play)
self.bouton_demarrer.pack()
self.bouton_options = Button(self, text="Options",command=self.Options)
self.bouton_options.pack()
self.bouton_quitter = Button(self, text="Quitter", command=self.quit)
self.bouton_quitter.pack()
def Options(self):
Frame.__init__(self, fenetre, width=768, height=568)
self.pack(fill=BOTH)
self.message = Label(self, text="Options")
self.message.place(x = '200', y = '0')
#ligne pour modifier la longueur du code
self.texte1 = Label(self, text="Longueur du code")
self.texte1.place(x = '0', y = '20')
self.plus1 = Button(self, text="+", command=self.AugLongcode)
self.plus1.place(x = '460', y = '20')
self.montrer1 = Label(self, text=self.Longcode)
self.montrer1.place(x = '430', y = '20')
self.moins1 = Button(self, text="-", command=self.DimLongcode)
self.moins1.place(x = '380', y = '20')
#ligne pour modifier le nombre de tours
self.texte2 = Label(self, text="Nombre de tours")
self.texte2.place(x = '0', y = '80')
self.plus2 = Button(self, text="+", command=self.AugNbtours)
self.plus2.place(x = '460', y = '80')
self.montrer2 = Label(self, text=self.Nbtours)
self.montrer2.place(x = '430', y = '80')
self.moins2 = Button(self, text="-", command=self.DimNbtours)
self.moins2.place(x = '380', y = '80')
#bouton pour revenir au Menu
self.bouton_quitter = Button(self, text="Retour", command=self.Retour)
self.bouton_quitter.place(x = '200', y = '250')
def DimLongcode(self):
if self.Longcode > 4:
self.Longcode -= 1
self.montrer1["text"] = self.Longcode
def AugLongcode(self):
if self.Longcode < 8:
self.Longcode += 1
self.montrer1["text"] = self.Longcode
def DimNbtours(self):
if self.Nbtours > 1:
self.Nbtours -= 1
self.montrer2["text"] = self.Nbtours
def AugNbtours(self):
if self.Nbtours < 15:
self.Nbtours += 1
self.montrer2["text"] = self.Nbtours
def Retour(self): #bouton pour revenir au Menu
Frame.__init__(self, fenetre, width=768, height=568)
self.pack(fill=BOTH)
self.message = Label(self, text="Menu")
self.message.pack()
self.bouton_demarrer = Button(self, text="Start",command=self.Play)
self.bouton_demarrer.pack()
self.bouton_options = Button(self, text="Options",command=self.Options)
self.bouton_options.pack()
self.bouton_quitter = Button(self, text="Quitter", command=self.quit)
self.bouton_quitter.pack()
#----------------------------OK Button command-------------------------------------------------
def Play(self):
Frame.__init__(self, fenetre, width=768, height=568)
self.pack(fill=BOTH)
#self.IA = ["" ,"" ,"" ,"" ,"" ,"" ,"" , ""]
self.IA = []
self.r = 0
while self.r < self.Longcode: #boucle pour eviter les doublons
temp = randint(0, 9)
verif = 0
while verif == 0: #etat 0 : les valeurs sont differentes (initialisation)
if self.r != 0:
a = 0
for a in range(0, self.r):
if self.Couleurs[temp] == self.IA[a]:
verif = 1 #etat 1 : une valeur egale (doublon)
if (a == self.r - 1 and verif == 0):
verif = 2 #etat 2 : aucune valeur egale
if (a == self.r - 1):
a += 1
else:
if self.r == 1:
if self.Couleurs[temp] == self.IA[a]:
verif = 1 #etat 1 : une valeur egale (doublon)
if (a == self.r - 1 and verif == 0):
verif = 2 #etat 2 : aucune valeur egale
else:
verif = 2
if verif == 2:
self.IA.append(self.Couleurs[temp])
self.r += 1
print self.IA
divid = 500/(self.Longcode + 1)
val = 0
self.bouton_test = ['0', '1', '2', '3', '4', '5', '6', '7', '8']
self.colors = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
self.bouton_valid = []
for n in range(0,self.Longcode):
self.colors[n] = self.Couleurs[n]
self.bouton_test[n] = Button(self, bg = self.colors[n], text=n+1, command =lambda n=n: self.Colorchange(n, self.bouton_test[n]["bg"]))
self.bouton_test[n].place(x=val, y = '460')
val = val + divid
self.bouton_valid.append(Button(self, text="OK", command = self.Fintour))
self.bouton_valid[0].place(x=val, y = '460')
def Fintour(self): #bug lors de l'appel de la fonction par une deuxieme fonction. Idee : deplacer le premier bouton et rajoutter des parametres d'entree
self.combinaison = []
self.Blanc = 0
self.Noir = 0
for c in range(0, self.Longcode): #boucle pour ranger la combinaison
tempo = int(c + self.Longcode*(self.Tour - 1))
self.combinaison.append(self.bouton_test[tempo]["bg"])
print self.combinaison
for d in range(0, self.Longcode): #boucle pour determiner le nombre de couleurs correcte if self.combinaison[d+ (self.Longcode*(self.Tour - 1))] == self.IA[d]:
self.Blanc += 1
self.compa = []
for e in range(0, self.Longcode): #boucle pour determiner le nombre de couleurs mal placees
for f in range(0, self.Longcode):
if self.combinaison[e+ (self.Longcode*(self.Tour - 1))] == self.IA[f]:
if e == 0:
self.compa.append(self.IA[f])
self.Noir += 1
else:
verif = 0
while verif == 0:
for g in range(0, len(self.compa)):
if self.IA[f] == self.compa[g]:
verif = 1
f = self.Longcode
if (verif == 0 and g == len(self.compa) - 1):
g +=1
verif = 2
if verif == 2:
self.compa.append(self.IA[f])
self.Noir +=1
for h in range(0, self.Longcode): #empeche les anciens boutons de changer de couleur
self.bouton_test[h+ (self.Longcode*(self.Tour - 1))]["state"] = 'disabled'
self.bouton_valid[self.Tour- 1].destroy()
divid2 = 460/(self.Nbtours + 1)
self.NHauteur = (460 - ((self.Tour) * divid2))
divid = 500/(self.Longcode + 1)
val = 0
for i in range(0 ,self.Longcode):
self.colors.append(self.bouton_test[i]["bg"])
self.colors[i] = self.Couleurs[i]
self.bouton_test[i] = Button(self, bg = self.colors[i], text=i+1, command =lambda i=i: self.Colorchange(i, self.bouton_test[i]["bg"]))
self.bouton_test[i].place(x=val, y = self.NHauteur)
val = val + divid
self.bouton_valid.append(Button(self, text="OK", command = self.Fintour))
self.bouton_valid[self.Tour].place(x=val, y = self.NHauteur)
self.blanc = Label(self, text="Bonnes couleurs :")
self.blanc.place(x=val, y = (460 - ((self.Tour - 1) * divid2)))
self.blanc = Label(self, text="Couleurs mal placées :")
self.Tour += 1
#-----------------------------------------------------------------------------------------------
def Colorchange(self, ind, color):
for z in range(0,10):
if self.Couleurs[z] == color:
self.var = z
if self.var == 9:
self.bouton_test[ind].config(bg = self.Couleurs[0])
else:
self.bouton_test[ind].config(bg = self.Couleurs[self.var + 1])
return
def quit(self):
fenetre.destroy()
fenetre = Tk()
fenetre.title("BananaMind v0.1") ##Titre de la fenetre
fenetre.geometry("500x500") ##taille de la fenetre
interface = Menu(fenetre)
interface.mainloop()
#interface.destroy()
I putted the full code in case the error could be from another command (even
if the program only freezes with the "OK" button). This is an old version of
the code with maybe some other errors, but I want to focus on the main problem
please :)
Answer: Okay so,
It was just an error in the index, using the function len (I forgot a list
starts at 0, so to have the good index I must put len(list) - 1
The problem is solved, I don't have any infinite loop anymore
Thanks :)
|
Python import warning
Question: Let's say I want to use scipy in my program, giving it the alias sp. I also
want to use the linalg module from scipy. Unlike what happens with numpy, the
module is not automatically imported. So I have to write:
import scipy as sp
import scipy.linalg
This achieves the desired result: I can now write `sp.linalg.inv(...)`.
The problem is that the line `import scipy.linalg` also imports scipy. And
given that all my calls to scipy are made using the alias sp, **spyder** gives
me the warning _'scipy' imported but unused_ in the second line.
What would be the right way of doing this? Or is mine the right way and the
problem is just spyder's?
I could do:
import scipy.linalg
sp = scipy
But that doesn't look really pythonic..
Answer: If you use
from scipy import linalg
then `scipy` will not be added to the global namespace, though this will add
`linalg` to the global namespace.
* * *
As a technical note, it _is_ possible to define `sp.linspace` without adding
`scipy` or `linspace` to globals:
import importlib
import scipy as sp
sp.linalg = importlib.import_module('scipy.linalg')
Note only `sp` is in `globals()`:
print(globals().keys())
# ['__builtins__', '__file__', 'sp', '__package__', '__name__', '__doc__']
Or, alternatively,
import scipy as sp
sp.linalg = __import__('scipy.linalg', fromlist=['linalg'])
|
How to check how many emails were sent between dates?
Question: I want to count how many emails were sent between certain dates. The date
header looks like this:
Date: Tue, 20 Jan 2015 15:00:37 +0000
When counting other things, I code like this which adds one to the count:
if msg['From'] == '[email protected]':
count+=1
However it gets difficult when I have to count how many emails were sent
between certain dates. Would it be something like:
date1= Tue, 18 Jan 2015 15:00:37 date2= Wed, 23 Jan 2015 15:00:37
if msg['Date'] < date2 and msg['Date'] > date1:
count+=1
I Don't think python will recognize it being dates. Therefore the `>` or `<`
operators will not work?
Answer: You can use dateutil or datetime to parse the strings as datetime objects and
compare:
from dateutil import parser
date1= "Tue, 18 Jan 2015 15:00:37"
date2="Wed, 23 Jan 2015 15:00:37"
date1 = parser.parse(date1)
date2 = parser.parse(date2)
msg = {"Date": "Tue, 19 Jan 2015 15:00:37 +0000"}
if date2 >= parser.parse(msg['Date']).replace(tzinfo=None) > date1:
print msg['Date']
You will need to `pip install python-dateutil` as it is not in the standard
lib.
Your Date string seems to include the timezone but date1 and 2 don't so you
cannot compare offset-aware and offset-naive datetimes.
|
Memory overflows when streaming data using Bokeh push_notebook()
Question: It seems that there is a memory leak when calling push_notebook() for
streaming data to a Bokeh plot in an IPython notebook. You can reproduce it
with the following code in an IPython notebook cell:
from bokeh.plotting import *
import numpy as np
output_notebook()
x = np.linspace(0., 1000., 1000)
p = figure()
hold()
p.line(x = x, y = np.sin(x), name = 'y')
def update():
renderer = p.select(dict(name='y'))
ds = renderer[0].data_source
ds.data['y'] = np.sin(a * x)
ds.push_notebook()
show(p)
a = 1.
while True:
update()
a *= 1.1
Not sure if it's supposed to be used that way though.
Answer: There is a bug listed here for this issue.
<https://github.com/bokeh/bokeh/issues/1732>
|
Python: how to install a pass-through copy/deepcopy hook
Question: I have a library which stores additional data for foreign user objects in a
WeakKeyDictionary:
extra_stuff = weakref.WeakKeyDictionary()
def get_extra_stuff_for_obj(o):
return extra_stuff[o]
When user object is copied, I want the copy to have the same extra stuff.
However, I have limited control over the user object. I would like to define a
class decorator for user object classes which will be used in this manner:
def has_extra_stuff(klass):
def copy_with_hook(self):
new = magic_goes_here(self)
extra_stuff[new] = extra_stuff[self]
klass.__copy__ = copy_with_hook
return klass
This is easy if klass already defines `__copy__`, because I can close
`copy_with_hook` over the original and call it. However, typically it's not
defined. What to call here? This obviously can't be `copy.copy`, because that
would result in infinite recursion.
I found [this question](http://stackoverflow.com/questions/3253439/python-
copy-how-to-inherit-the-default-copying-behaviour) which appears to ask the
exact same question, but afaict the answer is wrong because this results in a
deepcopy, not a copy. I would also be unable to do this, as I need to install
hooks for both deepcopy and copy. (Incidentally, I would have continued the
discussion in that question, but having no reputation I am not able to do
this.)
I looked at what the copy module does, which is a bunch of voodoo involving
`__reduce_ex()`. I can obviously cut/paste this into my code, or call its
private methods directly, but I would consider this an absolute last resort.
This seems like such a simple thing, I'm convinced I'm missing a simple
solution.
Answer: Essentially, you need to (A) copy and preserve the original `__copy__` if
present (and delegate to it), otherwise (B) trick `copy.copy` into **not**
using your newly-added `__copy__` (and delegate to `copy,copy`).
So, for example...:
import copy
import threading
copylock = threading.RLock()
def has_extra_stuff(klass):
def simple_copy_with_hook(self):
with copylock:
new = original_copy(self)
extra_stuff[new] = extra_stuff[self]
def tricky_case(self):
with copylock:
try:
klass.__copy__ = None
new = copy.copy(self)
finally:
klass.__copy__ = tricky_case
extra_stuff[new] = extra_stuff[self]
original_copy = getattr(klass, '__copy__', None)
if original_copy is None:
klass.__copy__ = tricky_case
else:
klass.__copy__ = simple_copy_with_hook
return klass
Not the most elegant code ever written, but at least it just plays around with
`klass`, without monkey-patching nor copy-and-pasting `copy.py` itself:-)
Added: since the OP mentioned in a comment he can't use this solution because
the app is multi-threaded, added appropriate locking to make it actually
usable. Using a single global re-entrant lock to ensure against deadlocks due
to out-of-order acquires of multiple locks among multiple threads, and perhaps
over-locked "just in case" although I suspect the simple case and the dict
assignent in the tricky case probably don't need the lock... but, when
threading threatens, better safe than sorry:-)
|
Can't Open Python IDLE
Question: Getting the following message after the program opening 9 separate screens.
Any ideas? Tried uninstalling and reinstalling but no luck:
try:
import idlelib.PyShell
except ImportError:
# IDLE is not installed, but maybe PyShell is on sys.path:
try:
from . import PyShell
except ImportError:
raise
else:
import os
idledir = os.path.dirname(os.path.abspath(PyShell.__file__))
if idledir != os.getcwd():
# We're not in the IDLE directory, help the subprocess find run.py
pypath = os.environ.get('PYTHONPATH', '')
if pypath:
os.environ['PYTHONPATH'] = pypath + ':' + idledir
else:
os.environ['PYTHONPATH'] = idledir
PyShell.main()
else:
idlelib.PyShell.main()
Answer: I am an Idle maintainer and it is very unclear how you tried to open Idle,
what you mean by '9 screens', and what you 're-installed', and on what system
and version of Python.
The easiest way to start Idle with installed Python is to use the Start menu
icon (on Windows) or the equivalent on other systems. On a command line, use
`python -m idlelib`, where `python` starts some version of installed 3.x. For
uninstalled 3.x or 2.x, use `idlelib.idle`. From within Python, `import
idlelib.idle` starts Idle.
If you have python 2.7 or 3.4 properly installed and running, so that `python
-m test.regrtest` runs and passes (`.regrtest` is only needed for 2.x), I
would be very surprised if Idle did not run with the methods above.
The code you posted is idlelib/idle.pyw. It is used by idlelib/idle.bat and
may have other specialized uses, such as running Idle with a subprocess call.
I suspect that it is partially obsolete. In any case, I doubt it will be
helpful to you.
|
error on installation of opencv does not make sense
Question: when I run `brew install opencv` I get the following error:
Error: undefined local variable or method `which_python' for #<Formula opencv (stable) /usr/local/Library/Formula/opencv.rb>
naturally I went to check this out by opening up
`/usr/local/Library/Formula/opencv.rb`. That showed the following ruby
declaration:
def which_python
"python" + `python -c 'import sys;print(sys.version[:3])'`.strip
end
so `which_python` is clearly defined. Just to check and make sure that works,
I opened up ruby to see if there was something wrong:
1.9.3-p194 :005 > def which_python
1.9.3-p194 :006?> "python" + `python -c 'import sys;print(sys.version[:3])'`.strip
1.9.3-p194 :007?> end
=> nil
1.9.3-p194 :008 > which_python
=> "python2.7"
This verifies that `which_python` is defined correctly. Can somebody please
explain why this error is occurring and what I can do to get around this.
Answer: I resolved this with:
rm /usr/local/Library/Formula/opencv.rb
brew update
brew doctor
brew install opencv
I'm not sure if removing opencv.rb is needed.
|
python convert unicode into it's "print" form
Question: I grabbed this paragraph in a webpage:
> It doesn’t look like a controversial new case management system is going
> anywhere. So the city plans to spend the next few months helping local
> social assistance workers learn to live with it.
and in my downloaded html data in python unicode it looks like this:
mystr = u'It doesn\u2019t look lake a controversial new case management system is going anywhere. So\xa0the city plans to spend the next few months helping local social assistance workers learn to live with it.'
my plan is to be able to use something like `mystr.find("doesn't")` to find
the location of the word. Currently, the `mystr.find("doesn't")` will return
`-1` as it is actually `doesn\u2019t` in `mystr`
Is there a fast way to convert `mystr` to exactly what the paragraph looked
like above, so that all unicode 'characters' are replaced by 'normal'
characters so that I can use `str.find()`?
The best posts I've found on the webpage so far is to replace the `u'\u2019'`
with `"'"` and then replace `u'\xa0'` with `' '`. Is there are more convenient
method so that I don't have to really write a method and build a conversion
dictionary?
ps:
I've also tried unicodedata.normalizing and stuff like that, doesn't seem to
work.
EDIT: I forgot to mention, the python version is 2.7
Answer: You already have what the webpage contains. `\u2019` is [U+2019 RIGHT SINGLE
QUOTATION MARK](http://codepoints.net/U+2019), a _fancy_ single quote, but you
are using a simple ASCII single quote instead, e.g. the lowly [U+0027
APOSTROPHE](http://codepoints.net/U+0027).
If you print the value, you'll see it produces something that looks a lot like
it has a singe quote in it, but slightly _curved_ :
>>> mystr = u'It doesn\u2019t look lake a controversial new case management system is going anywhere. So\xa0the city plans to spend the next few months helping local social assistance workers learn to live with it.'
>>> print mystr
It doesn’t look lake a controversial new case management system is going anywhere. So the city plans to spend the next few months helping local social assistance workers learn to live with it.
All Python did was echo the _representation_ of the string, which replaces
anything non-printable and non-ASCII with escape sequences that make the value
_reproducible_ ; you can copy and paste the value into any Python interpreter
or script and it'll produce the same value. Because the default source
encoding for Python is ASCII only ASCII characters are used to describe the
value.
You could look for that text instead:
>>> u'doesn\u2019t' in mystr
True
or you could use a library like
[`unidecode`](http://pypi.python.org/pypi/unidecode) to replace non-ASCII
codepoints with ASCII 'lookalikes'; it'll replace the fancy quote with a plain
ASCII quote:
>>> from unidecode import unidecode
>>> unidecode(mystr)
"It doesn't look lake a controversial new case management system is going anywhere. So the city plans to spend the next few months helping local social assistance workers learn to live with it."
>>> "doesn't" in unidecode(mystr)
True
|
cross domain call using using python and make ajax call to the python to read data
Question: I am trying to make an ajax request to a python script running in the same
webserver. The call happens fine. I am using python to make the cross domain
call to return some data back. with .success() i get back all the content of
the script file. I could do this PHP quite easily but I am trying to use
python for the sake of learning it.
My python looks like this
import urllib.request
def main():
r = urllib.request.urlopen("http://some url").read()
print(r)
main();
My ajax looks like this
$('div_something').on('click', function(){
$.ajax({
type: "POST",
dataType: 'html',
url: "getproduct.py",
}).done(function(data){
$('div').html(data);
});
});
Answer: I'd suggest using [requests](http://docs.python-requests.org/en/latest/),
Python's native support for this isn't friendly.
Edit: I missed the part about success(). Is this what you meant?
>>> import requests
>>> response = requests.post("http://some url")
>>> if response.status_code == requests.codes.ok:
print(response.text)
>>> elif response.status_code == 404:
handle_error()
|
cannot solve my flask bluprint assertion error
Question: I'm trying to split my app with using Bluprint in flask, but i got
AssertionError though there's no funtions having same names. i thought if the
function name is different, the default endpoint will be different too. I've
searched for it, but still i couldent get so far. please help ;(
this is my controllers.py
import flask
from flask import render_template, request, redirect, url_for, flash, make_response, g, session, jsonify
from apps import app, db
from apps.models import *
from apps.controllers2 import app2
#Set application.debug=true to enable tracebacks on Beanstalk log output.
#Make sure to remove this line before deploying to production.
app.debug=True
app.register_blueprint(app2)
@app.route('/', methods=['GET', 'POST'])
@app.route('/intro', methods=['GET', 'POST'])
def hmp_showIntro():
return render_template('intro.html')
if __name__ == '__main__':
app.run(host='0.0.0.0')
and this is separated controller, controller2.py
from flask import render_template, request, redirect, url_for, flash, make_response, g, session, jsonify
from flask import Blueprint
from apps import app, db
app2 = Blueprint('app2', __name__)
@app2.route('/main')
def hmp_showMain():
return render_template('main.html')
and here is what i've got
mod_wsgi (pid=15429): Exception occurred processing WSGI script '/opt/python/current/app/apps/controllers.py'.
Traceback (most recent call last):
File "/opt/python/current/app/apps/controllers.py", line 17, in <module>
@app.route('/intro', methods=['GET', 'POST'])
File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 1013, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 62, in wrapper_func
return f(self, *args, **kwargs)
File "/opt/python/run/venv/lib/python2.7/site-packages/flask/app.py", line 984, in add_url_rule
'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint function: hmp_showIntro
Answer: Your app already has route to view with `hmp_showIntro` name. Search project
for that function. Or you can do double import of controllers.py.
|
Attempt at Infinite Monkey theorem using Python
Question: So , I've been trying to implement the infinite monkey theorem using
python.The problem statement is something like this.
The theorem states that a monkey hitting keys at random on a typewriter
keyboard for an infinite amount of time will almost surely type a given text,
such as the complete works of William Shakespeare. Well, suppose we replace a
monkey with a Python function. The sentence is: “methinks it is like a weasel”
The way we’ll simulate this is to write a function that generates a string
that is 27 characters long by choosing random letters from the 26 letters in
the alphabet plus the space. We’ll write another function that will score each
generated string by comparing the randomly generated string to the goal.
A third function will repeatedly call generate and score, then if 100% of the
letters are correct we are done. If the letters are not correct then we will
generate a whole new string.
import random,string
shakespeare = 'methinks it is a weasel'
def generate():
char = string.ascii_lowercase+' '
randchars = ''.join(random.choice(char) for _ in range(27))
return randchars
def score():
scorenum = 0
randchars = generate()
print randchars
shake = shakespeare.split()
randlist = randchars.split()
for i,j in zip(shake,randlist):
if i==j:
scorenum = scorenum+1
scorecount = (scorenum/27)*100
return scorecount
def main():
run = 0
while not(score()==100):
score()
run = run + 1
print run
if run ==1000:
print score()
if __name__ == '__main__':
main()
So, the program is running fine, but I can see the randomized string appearing
twice when I print it, and I've reached 3 million mark without reaching any
success in terms of matching. I believe I've written the main function
wrongly, but I'm not sure of the problem yet.
Thanks in advance if you can help me fix this. :)
Answer: Each time you call score(), you will generate a new statement, which means
within this loop...
while not(score()==100):
score()
run = run + 1
print run
if run ==1000:
print score()
... you are generating the statement at least twice, and sometimes three
times.
You could replace it with something like:
while not(score()==100):
run = run + 1
print run
The number of potential combinations is vast - the chances of you being able
to run this for long enough to see anything close to a readable sentence,
never mind one that matches the exact sentence you're looking for, are really
remote!
Here's an example that generates matches (I've seen several 33% matches on a 3
character quote):
import random,string
# shakespeare = 'methinks it is a weasel'
shakespeare = 'abc'
quoteLen = len(shakespeare)
def generate():
char = string.ascii_lowercase+' '
randchars = ''.join(random.choice(char) for _ in range(quoteLen))
return randchars
def score():
scorenum = 0
randchars = generate()
shake = shakespeare.split()
randlist = randchars.split()
for i,j in zip(shake,randlist):
if i==j:
scorenum = scorenum+1
scorecount = (scorenum / quoteLen) * 100
return scorecount
def main():
run = 0
curScore = 0
while not(curScore==100):
curScore = score()
if (curScore != 0):
print(run, " = ", curScore)
run = run + 1;
if __name__ == '__main__':
main()
Example output:
2246 = 33.33333333333333
56731 = 33.33333333333333
83249 = 33.33333333333333
88370 = 33.33333333333333
92611 = 33.33333333333333
97535 = 33.33333333333333
|
How do I extract all the numbers (integers) from a text file using python?
Question: How do I extract all the numbers (integers) from a text file using python? I
am only using them in the def part to make a function of a button. I should be
able to calculate them after extracting them.
Answer: You could use `re.findall` function.
re.findall(r'\d+', string)
That is,
with open('path/file') as file:
x = file.read()
print(re.findall(r'\d+', x))
**OR**
import re
l = []
with open('/path/file') as file:
for line in file:
for i in re.findall(r'\d+', line):
l.append(i)
print(l)
`\d+` matches one or more digits.
|
scikit-learn: Get selected features for prediction data
Question: I have a training set of data. The python script for creating the model also
calculates the attributes into a numpy array (It's a bit vector). I then want
to use `VarianceThreshold` to eliminate all features that have 0 variance (eg.
all 0 or 1). I then run `get_support(indices=True)` to get the indices of the
select columns.
My issue now is how to get only the selected features for the data I want to
predict. I first calculate all features and then use array indexing but it
does not work:
x_predict_all = getAllFeatures(suppl_predict)
x_predict = x_predict_all[indices] #only selected features
indices is a numpy array.
The returned array `x_predict` has the correct length `len(x_predict)` but
wrong shape `x_predict.shape[1]` which is still the original length. My
classifier then throws an error due to wrong shape
prediction = gbc.predict(x_predict)
File "C:\Python27\lib\site-packages\sklearn\ensemble\gradient_boosting.py", li
ne 1032, in _init_decision_function
self.n_features, X.shape[1]))
ValueError: X.shape[1] should be 1855, not 2090.
How can I solve this issue?
Answer: You can do it like this:
**Test data**
from sklearn.feature_selection import VarianceThreshold
X = np.array([[0, 2, 0, 3],
[0, 1, 4, 3],
[0, 1, 1, 3]])
selector = VarianceThreshold()
**Alternative 1**
>>> selector.fit(X)
>>> idxs = selector.get_support(indices=True)
>>> X[:, idxs]
array([[2, 0],
[1, 4],
[1, 1]])
**Alternative 2**
>>> selector.fit_transform(X)
array([[2, 0],
[1, 4],
[1, 1]])
|
How to return value for different layers of (x,y) levels
Question: My problem is the following. I a functional requirement where the user can
choose between 3 or 5 levels and a value will be returned according to which
level (x,y) belong.
for example in 3 levels we have
def f(x,y):
if (0 <= x <= 0.3 and 0 <= y <= 1) or (0.3 <= x <= 1 and 0 <= y <= 0.3):
return 1
elif (0.3 < x <= 0.6 and 0.3 < y <= 1) or (0.6 <= x <= 1 and 0.3 < y <= 0.6):
return 2
else:
return 3
for 5 levels we would have 5 if branches and so on.
I was wondering which is the best way(or a good) to do that in Python with the
DRY principle. My mind is short of short circuited right now.
Answer: So first, we can recognize that we can rewrite your program as:
def f(x, y):
if min(x, y) <= 0.3:
return 1
elif min(x, y) <= 0.6:
return 2
else:
return 3
We can then format this into a for loop fairly easily:
from __future__ import division
def f(x, y, n=3):
for i in range(1, n+1):
if min(x, y) <= i/n:
return i
else:
return n
We could also write a math equation for this and drop the for loop:
def f(x, y, n=3):
return int(min(x, y) * n) + 1
This last equation will fail when `x == 1` or `y == 1`. You should probably
just either make a special case for that, or also perform a
`max(result_so_far, n)` as well.
|
Int vs Double on Python
Question: I'm in stats class right now and I wanted to know if it makes a difference if
you generate a number each digit at a time vs every digit at once, so I wrote
some code...
from random import randint
import math
total1 = 0
total2 = 0
for i in range(100000):
temp = 0
for j in range(7):
temp += randint(0,9)*math.pow(10,j)
total1 += temp
total2 += randint(0,9999999)
print "avg1 = ", total1/100000
print "avg2 = ", total2/100000
When I ran the code, avg1 was always a decimal and avg2 was always a whole
number. I don't understand why total1 is being considered as a double since I
only ever added integers to it...
Answer: According to the python documentation, the math.pow function returns a
floating point number. This is going to implicitly cast the temp variable to
be a float as well:
<https://docs.python.org/2/library/math.html>
Because total1 is implicitly cast as a float, while total2 is consistently
used as an int, total1 will return a decimal and total2 will return a whole
number.
|
How does variable scoping work with python imports
Question: I am having difficulty understanding how global variables from a module are
actually imported in another module. Suppose we have a module mod1.py coded as
below:
#mod1.py
var1 = None
def test():
global var1
var1=1
* * *
and, another module mod2.py that intends to use mod1.py, as below:
* * *
#mod2.py
from mod1 import * #This may not be a good coding practice, but it's relevant to my question
print "var1="+str(var1)
test()
print "var1="+str(var1)
* * *
When executing mod2, the print statements print:
var1=None
var1=None
* * *
which means that the value of var1 that was imported as a result of "from mod1
import *" did not bear any change in mod2 by calling test(). On the other
hand, if I code mod2 as below:
* * *
#mod2.py
import mod1
print "var1="+str(mod1.var1)
mod1.test()
print "var1="+str(mod1.var1)
* * *
The first and second print statements print:
var1=None
var1=1
* * *
which means that the value of var1 was changed by a call to mod1.test().
Why is that so?
Answer: One common analogy for this is to think of strings tied to balloons. Think of
every assignment statement as tying a string to a balloon. e.g.
a = 1 # tie a string "a" to the `1` balloon
b = a # tie a string to the same balloon that "a" is tied to.
Assigning a new thing to an existing variable is akin to cutting the current
string and tying it to something else:
a = 2 # cut string tying "a" to 1 and tie it to the `2` balloon
In the first version (`from mod1 import *`) you basically do a whole bunch of
assignment statements:
var1 = mod1.var1
...
Now, you have 2 strings tied to the 1 balloon -- `mod1.var1` and `mod2.var1`.
After you call the `test` function, you cut the string of `mod1.var1` and tie
it to the "2" balloon.
In the second example (`import mod1`), you have a string (`mod2.mod1`) tied to
the `mod1` _module_ , but no explicit string tied to `mod1.var1`. So now when
you re-tie the `mod1.var1` string, you can still look it up the same way --
The string tied to `mod1` hasn't change, only the string from `mod1` to
`mod1.var1`.
|
In python module troposphere I am getting an error "AttributeError: 'module' object has no attribute 'EBSBlockDeviceMapping'"
Question: I'm following the example of some other code that has been written. The code
in question looks like this:
if virtualname == "ebs":
if deviceSize == None:
deviceSize = 8
if delOnTerminate == None or delOnTerminate == "true":
DOT = "true"
else:
DOT = "false"
lc.BlockDeviceMappings.append(ec2.EBSBlockDeviceMapping(
DeviceName=blockname,
Ebs=ec2.EBSBlockDevice(VolumeSize=deviceSize,
DeleteOnTermination=DOT)))
else:
lc.BlockDeviceMappings.append(ec2.BlockDeviceMapping(DeviceName=blockname,
VirtualName=virtualname))
Answer: The `AttributeError` happens only when you have a class (in this case a
module) and refer to an attribute that doesn't exist. It is like a `NameError`
but for attributes of objects.
You have imported a module like `import ... as ec2`. The module marked `...`
does not have a function called `EBSBlockDeviceMapping`, so when you call it
in your code, it gives an `AttributeError`.
|
How to change the value of a local variable (python) each time the code loops?
Question: I have to create an ATM style program wherein the code looks something like
this:
import sys
def ATM():
bank = 0
coins = int (input ("Enter coins: "))
bank = coins+bank
o = input("would you like to take out 20p? Y or N")
if o == "Y":
bank = bank - 20
else:
print ("your balance is {0}".format(bank))
op = input ("would you like to enter more coins? Y or N")
if op == "Y":
ATM()
else:
print ("goodbye")
sys.exit()
ATM()
Is there a way to make the local variable bank keep it's value from the end of
the program? what would I have to switch bank = 0 for? EDIT: Found a solution,
thank you all who offered some suggestions
Answer: You can use [pickle](https://docs.python.org/2/library/pickle.html) or you can
save your data in to a .txt file;
#codes
....
with open("my_database.txt","a+") as f:
f.write(str(bank))
So you could keep your `bank` data in a file. As you see we open the file in
`a+` mode which is not overwriting your file.
|
Gap Filling Contours / Lines
Question: I have the following image:

and I would like to fill in its contours (i.e. I would like to gap fill the
lines in this image).
I have tried a morphological closing, but using a rectangular kernel of size
`3x3` with `10` iterations does not fill in the entire border. I have also
tried a `21x21` kernel with `1` iteration and also not had luck.
**UPDATE:**
I have tried this in OpenCV (Python) using:
cv2.morphologyEx(img, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (21,21)))
and
cv2.morphologyEx(img, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (3,3)), iterations=10)
and [scikit-image](http://scikit-
image.org/docs/dev/auto_examples/applications/plot_morphology.html):
closing(img, square(21))
My end goal is to a have a filled version of that entire image without
distorting the area covered.
Answer: In the following snippet I calculate the distance map of the inverse image. I
threshold it to obtain a large outline of the current object, which I then
skeletonize to get the central line. This may already be enough for your
purposes. But to make it consistent with the line thickness given, I dilate
the skeleton and add it to the original, thereby closing any gaps. I also
remove the one remaining object touching the boundary.

from skimage import io, morphology, img_as_bool, segmentation
from scipy import ndimage as ndi
import matplotlib.pyplot as plt
image = img_as_bool(io.imread('/tmp/gaps.png'))
out = ndi.distance_transform_edt(~image)
out = out < 0.05 * out.max()
out = morphology.skeletonize(out)
out = morphology.binary_dilation(out, morphology.selem.disk(1))
out = segmentation.clear_border(out)
out = out | image
plt.imshow(out, cmap='gray')
plt.imsave('/tmp/gaps_filled.png', out, cmap='gray')
plt.show()
|
How to write two python dictionaries to a single csv?
Question: Can anyone please tell me how to write two `dict`s to a single csv? I tried
with one dict:
import csv
my_dict = {"test": 1, "testing": 2}
with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x
w = csv.DictWriter(f, my_dict.keys())
w.writeheader()
w.writerow(my_dict)
But when I tried with two `dict`:
import csv
my_dict1 = {"test": 1, "testing": 2}
my_dict2 = {"test": 3, "testing": 4}
my_dict =my_dict1,my_dict2
with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x
w = csv.DictWriter(f, my_dict1.keys())
w.writeheader()
w.writerow(my_dict)
That doesn't work :(
Thanks in advance
Answer: Just invoke `writerow` multiple times assuming they have the same keys.
import csv
my_dict1 = {"test": 1, "testing": 2}
my_dict2 = {"test": 3, "testing": 4}
with open('mycsvfile.csv', 'wb') as f: # Just use 'w' mode in 3.x
w = csv.DictWriter(f, my_dict1.keys())
w.writeheader()
w.writerow(my_dict1)
w.writerow(my_dict2)
|
Python - Printing an HTML page give empty response for some sites
Question: I want to print a html page from a site (whoscored.com). I can print, but if I
try a sub-domain, gives an empty response:
import urllib2
htmlfile =urllib2.urlopen("http://whoscored.com/Matches/829663/Live/")
html = htmlfile.read()
print html
Answer: First of all, yes, the page you've provided _does not exist_.
Also, you need to _provide the`User-Agent` header_ to get and see the actual
404 HTML response. Example using [`requests` library](http://docs.python-
requests.org/en/latest/):
>>> import requests
>>>
>>> headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36'}
>>> response = requests.get("http://whoscored.com/829652/Live/", headers=headers)
>>> print response.content
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en" />
<title>WhoScored.com</title>
</head>
<body style="padding: 20px; font-family:Arial,Helvetica,sans-serif; background-color:#222222;">
<div style="margin:0 auto; padding: 40px 20px; width:560px; background-color:#fff;">
The page you requested does not exist in <a href="http://www.whoscored.com">WhoScored.com</a>
</div>
</body>
</html>
|
Python - How to pass global variable to multiprocessing.Process?
Question: I need to terminate some processes after a while, so I've used sleeping
another process for the waiting. But the new process doesn't have access to
global variables from the main process I guess. How could I solve it please?
Code:
import os
from subprocess import Popen, PIPE
import time
import multiprocessing
log_file = open('stdout.log', 'a')
log_file.flush()
err_file = open('stderr.log', 'a')
err_file.flush()
processes = []
def processing():
print "processing"
global processes
global log_file
global err_file
for i in range(0, 5):
p = Popen(['java', '-jar', 'C:\\Users\\two\\Documents\\test.jar'], stdout=log_file, stderr=err_file) # something long running
processes.append(p)
print len(processes) # returns 5
def waiting_service():
name = multiprocessing.current_process().name
print name, 'Starting'
global processes
print len(processes) # returns 0
time.sleep(2)
for i in range(0, 5):
processes[i].terminate()
print name, 'Exiting'
if __name__ == '__main__':
processing()
service = multiprocessing.Process(name='waiting_service', target=waiting_service)
service.start()
Answer: You should be using [synchronization
primitives](https://docs.python.org/2/library/multiprocessing.html#synchronization-
primitives).
Possibly you want to set an
[`Event`](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Event)
that's triggered after a while by the main (parent) process.
You may also want to wait for the processes to actually complete and `join`
them (like you would a thread).
If you have many similar tasks, you can use a processing pool like
[`multiprocessing.Pool`](https://docs.python.org/2/library/multiprocessing.html#module-
multiprocessing.pool).
Here is a small example of how it's done:
import multiprocessing
import time
kill_event = multiprocessing.Event()
def work(_id):
while not kill_event.is_set():
print "%d is doing stuff" % _id
time.sleep(1)
print "%d quit" % _id
def spawn_processes():
processes = []
# spawn 10 processes
for i in xrange(10):
# spawn process
process = multiprocessing.Process(target=work, args=(i,))
processes.append(process)
process.start()
time.sleep(1)
# kill all processes by setting the kill event
kill_event.set()
# wait for all processes to complete
for process in processes:
process.join()
print "done!"
spawn_processes()
|
Tornado. How get raw request.body?
Question: guys. I can't get raw body data with Tornado. I do request `curl -i
localhost:8888 -d '{"a":12}'` and expect to get a string `'{"a":12}'` in
request.body, but received `'{a:12}'`. Source code:
import tornado.web
import tornado.ioloop
class MainHandler(tornado.web.RequestHandler):
def post(self):
self.write(self.request.body)
if __name__ == "__main__":
app = tornado.web.Application({
(r"/", MainHandler)
})
app.listen(3000)
tornado.ioloop.IOLoop.instance().start()
curl result:
$ curl 127.0.0.1:3000 -i -d {"a":12}
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Server: TornadoServer/4.0.2
Content-Length: 6
Date: Thu, 22 Jan 2015 14:00:19 GMT
{a:12}
Python version is 3.4.2, Tornado version is 4.0.2
Answer: This is a shell quoting issue: the shell is removing the quotes in the command
`curl 127.0.0.1:3000 -i -d {"a":12}`. If you quote the argument to `-d` (which
you did in the body of your question: `curl -i localhost:8888 -d '{"a":12}'`,
you should get the results you expect.
|
Adding filename variable into HTML string in Python
Question: I've searched and can't find a solution to this. I'm trying to have the python
code loop through a directory for .mht files. Upon finding files it will write
an iframe html code to a file pointing to the .mht's. I'm having trouble
defining the iframe code to be written and include the filename variables in
the src.
>
> htmlframe = '''<iframe src="'%s.mht'" class="iframe" scrolling="no"
> frameborder="0" style="width:100%"></iframe><br>''' % os.path.basename
>
The error I get is below:
>
> Traceback (most recent call last):File "move.py", line 52, in <module>
> htmlframe = '''<iframe src="'%s.mht'" class="iframe" scrolling="no"
> frameborder="0" style="width:100%"></iframe><br>''' % os.path.basename
> TypeError: not enough arguments for format string
>
Thank you in advance for any assistance.
Answer: For rather complex string replacement operations, you should look at template
engines. With such an engine it is usually much easier to keep the overview
and to make modifications later on. A very simple one is built into the
standard library: <https://docs.python.org/2/library/string.html#template-
strings>
Is suffices most of the time!
Example:
from string import Template
s = """<iframe src="$filename" class="iframe" scrolling="no"></iframe>"""
t = Template(s)
print t.substitute(filename="foobar.mht")
Test:
python template.py
<iframe src="foobar.mht" class="iframe" scrolling="no"></iframe>
|
Python - drawing randomly n numbers integer from range
Question: I would like get the same effect as when I use `getn`, but it should be
integers numer from interval `[1...100]`
Answer:
from random import randint
randint(1, 100) # => 86
If you want a bunch of numbers,
def getn_rand(n):
return [randint(1, 100) for _ in range(n)]
or if the numbers have to be distinct (no duplicates),
from random import sample
def getn_rand_distinct(n):
return sample(range(1, 101), n)
|
Using Windbg PyKD Python Extension to Print/Break at Only Call Instructions
Question: Using WinDBG's python extension I want to print only call instructions in
console. [A kind of one step debugging ]
**My Code:**
from pykd import *
pid = raw_input ('pid >>> ')
id=attachProcess(int(pid))
print id
while 1:
trace()
r_o = dbgCommand('r')
line = r_o.split('\n')[-2]
sp_line = line.split()
addr = int(sp_line[0],16)
ins = sp_line[2]
if ins == "call":
print line
I tried above code and got below result.
**Output :**
C:\Program Files (x86)\Debugging Tools for Windows (x86)\winext>db.py
[+] Starting...
pid >>> 3516
0
76ec000d c3 ret
76f4f926 eb07 jmp ntdll!DbgUiRemoteBreakin+0x45 (76f4f92f)
76f4f92f c745fcfeffffff mov dword ptr [ebp-4],0FFFFFFFEh ss:002b:0029ff84=00000000
76f4f936 6a00 push 0
76f4f938 e8df86fbff call ntdll!RtlExitUserThread (76f0801c)
76ed0096 83c404 add esp,4
Here the problem seems to be, after the debugger breaks into the process, the
debug thread gets initiated and the debug thread is getting terminated after
sometime, because its the current thread [We can see last call is made to
ntdll!RtlExitUserThread]. Hence even if the debugee app runs I don't see any
thing in command line.
I've seen a script which uses winappdbg and does the similar operation. Here
is the script :
<https://github.com/MarioVilas/winappdbg/blob/master/tools/ptrace.py>
And I want to build something similar.
Answer: not a pykd answer but windbgs inbuilt pc/tc (step / trace to next call) will
print out all the calls
0:000> .printf "%y\n" , @eip
multithread!wmain (00411430)
0:000> $ iam at start of winmain and i have disabled all output except disassembly via .prompt_allow
0:000> $ i have set a breakpoint on winmains exit
0:000> $ code for demo is exact copy paste of msdn sample code for createthread documentation
0:000> $lets roll and log all call instructions
**0:000> tc 1000000**
0041147c ff1530824100 call dword ptr [multithread!_imp__GetProcessHeap (00418230)]
00411484 e8e9fcffff call multithread!ILT+365(__RTC_CheckEsp) (00411172)
0041148a ff152c824100 call dword ptr [multithread!_imp__HeapAlloc (0041822c)]
7c955264 e827ffffff call ntdll!LdrpTagAllocateHeap (7c955190)
7c9551b0 e80faffbff call ntdll!RtlAllocateHeap (7c9100c4)
7c9100ce e8f8e7ffff call ntdll!_SEH_prolog (7c90e8cb)
removed =====================
7c923b25 e80b000000 call ntdll!LdrShutdownProcess+0x1e0 (7c923b35)
7c923b3a e8a1d5fdff call ntdll!RtlLeaveCriticalSection (7c9010e0)
7c923b2a e8d7adfeff call ntdll!_SEH_epilog (7c90e906)
7c81cac3 ff153410807c call dword ptr [kernel32!_imp__CsrClientCallServer (7c801034)]
7c912de3 e8f6acffff call ntdll!NtRequestWaitReplyPort (7c90dade)
7c90dae8 ff12 call dword ptr [edx]
7c90e512 0f34 sysenter
7c81cacc ffd6 call esi
7c90de78 ff12 call dword ptr [edx]
7c90e512 0f34 sysenter
7c90e514 c3 ret
if you are following the code in the msdn sample and would want to trace the
thread calls a breakpoint ( hack but will work in most situations) can be used
`.prompt_allow` to disable everything except dis-assembly
set a `conditional break-point` on `CreateThread`
condition being `setting another break point on poi(@esp+c)`
`LpThreadStartRoutine` and `continuing`
the `next three pc 1000000` are step until next calls and `one quit`
we `know we have three threads` in the sample so we automated pc 10000000
three times `if you don't know` how many threads prior to execution manually
`enter pc 1000000 manually on each thread exit` .
**:cdb -c ".prompt_allow -src -reg -sym -ea ;g wmain;bp kernel32!CreateThread \"ba e1 poi( @esp+c) \\\"? $tid ;pc 100000 \\\";gc\";pc 100000;pc 1000000;pc 1000000 ;pc 1000000;pc 10000000;pc 1000000; pc 10000000;q" multithread.exe | grep -iE "W rite|Eval"**
Evaluate expression: 2148 = 00000864
004011c6 ff1520204000 call dword ptr [multithread!_imp__WriteConsoleW (004
02020)]
Evaluate expression: 2780 = 00000adc
004011c6 ff1520204000 call dword ptr [multithread!_imp__WriteConsoleW (004
02020)]
Evaluate expression: 3440 = 00000d70
004011c6 ff1520204000 call dword ptr [multithread!_imp__WriteConsoleW (004
02020)]
|
multiprocessing : why are my processes not running in parallel?
Question: I am having a little bit of trouble understanding what is going on here. I
want to run some subprocess calls in parallel using the multiprocessing
module.
My simple example is basically calling a function that waits for 5 seconds,
prints an output then waits for another 5 seconds before terminating.
I want the function to be locked until it prints out a line of code (anything
really) and then allow other processes to continue working as well.
Here is an illustration:
import time
import subprocess
import multiprocessing as mp
def main(l):
l.acquire()
#Lock process while it is run
proc = subprocess.Popen("python script_test.py", stdout=subprocess.PIPE)
#Wait until one byte is read then release
proc.stdout.read(1)
l.release()
#Terminate process when it has completed
proc.poll()
if __name__ == "__main__":
#Initialize lockiing mechanism
manager = mp.Manager()
lock = manager.Lock()
#Split up subprocess calls
ncpu = mp.cpu_count()
p = mp.Pool(ncpu)
p.map(main, [lock]*ncpu)
print "Run time = {0}s using {1} processes on {2}.".format(time.time()-start, ncpu, ncpu)
Where the contents of `script_test.py` is as follows:
import time
#Do some work up until the point of the print statement
time.sleep(5)
print "Okay 5 seconds has passed!"
#Continue doing work while allowing other processes to proceed
time.sleep(5)
It seems like this is not running in parallel. The total time takes 40.7s for
me with `ncpu` equal to 4, but there should only be about `5*ncpu + 5*2 = 25`
plus overhead since the first 5 seconds are locked and the last 5 should not
for each process.
I am running the `script_test.py` as an example, but in practice this will be
an executable file.
My questions are:
1. How can I utilize locks properly to accomplish the above?
2. I am running the script from a command prompt but I don't see any output. How would I print the output of the subprocess from within the child processes launched by the multiprocessing module?
Answer: 1. Because you have a single shared lock being used incorrectly, you've turned your code into a serial execution. What happened is that one of your processes got the lock, and the other three are waiting on that first process to execute. Once the first process is done, the next one grabs the lock and runs the script while the other two wait (and so on and so forth). So, you're creating four processes, but you're only running them one at time the way your are using your lock. From your code, I don't think you really need the lock anyway. The processes are not really sharing data, because each subprocess.Popen call is it's own instance.
2. The subprocess spins off yet another process to execute your script, and you'll need to use subprocess methods to read the "stdout" of the script and then print that out again. Use calls like "check_output" instead of calling Popen for example, save them to a variable and print.
EDIT - Question 1 has changed - new answer:
1. You have to look at your current problem at a more fundamental level. If I'm understanding your comments correctly, it sounds like your processes are operating on the same text file that is both modified and read. You can't operate on it in parallel (at least not very well), since you'll constantly be locking around it. If you can make separate text files like separate output names of some sort, then you can start to make things operate in parallel. I don't know what your executable is doing exactly, so it will be hard to say. You'll need to also call your lock acquisition in separate areas around the modify and the read sections of your code, so that may entail you importing this test script into your multiprocessing script. If the modify and write action is bound up in the executable (and can't create separate text files), then you're going to have a tough time with this problem.
|
wxPython fails to quit
Question: My wxPython GUI either quits with a Segmentation Fault or fails to quit at all
using the standard options. The only successful quit option (no errors) is
wx.Exit, which I understand is not a great practice. I've traced the issues
down to a few factors, but I'm scratching my head as to why they are having
this effect.
Using the wxPython inspector (wx.lib.inspection.InspectionTool()), I've been
able to determine that a FigureFrameWxAgg is being created when I run certain
pylab functions (pylab.xticks() is the function that creates it here, but I
haven't tracked down every single function that has this effect). I don't know
what this window is for. It's invisible and doesn't appear to do anything.
However, this window totally messes up the shutdown of my GUI. If I use
self.Destroy, Python doesn't shut down fully. If I use sys.exit, I get a
Segmentation fault. I need to catch the wx.EVT_CLOSE so that I can prompt the
user to save his/her work.
Here is the code for a simplified version of the GUI:
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas
import wx
import wx.grid
import wx.lib.scrolledpanel
import wx.lib.inspection
import sys
import pylab
class my_frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Many Rows')
self.InitUI()
def InitUI(self):
self.panel = wx.Window(self, size=(200, 200))
hbox_all= wx.BoxSizer(wx.HORIZONTAL)
self.create_menubar()
self.fig1 = pylab.Figure((5, 5), dpi=100)
self.canvas1 = FigCanvas(self.panel, -1, self.fig1)
self.fig1.text(0.01,0.98,"Arai plot",{'family':'Arial', 'fontsize':10, 'style':'normal','va':'center', 'ha':'left' })
self.araiplot = self.fig1.add_axes([0.1,0.1,0.8,0.8])
self.araiplot.clear()
self.araiplot.plot(range(5),range(5),lw=0.75,clip_on=False)
xt = pylab.xticks()
grid = wx.grid.Grid(self.panel)
grid.ClearGrid()
grid.CreateGrid(100, 100)
grid.AutoSize()
hbox_all.AddSpacer(self.canvas1)
hbox_all.AddSpacer(20)
hbox_all.AddSpacer(grid)
hbox_all.AddSpacer(20)
self.panel.SetSizer(hbox_all)
hbox_all.Fit(self)
self.Centre()
self.Show()
def create_menubar(self):
"""
Create menu bar
"""
self.menubar = wx.MenuBar()
menu_file = wx.Menu()
menu_file.AppendSeparator()
m_exit = menu_file.Append(wx.ID_EXIT, "Quit", "Quit application")
self.Bind(wx.EVT_CLOSE, self.on_menu_exit)
self.menubar.Append(menu_file, "&File")
self.SetMenuBar(self.menubar)
def on_menu_exit(self, event):
self.Destroy() # this doesn't quit Python fully, unless I comment out 'matplotlib.use('WXAgg')'
#for w in wx.GetTopLevelWindows():
# if w.Title == 'Figure 1':
# w.Destroy() # if I pre-destroy the FigureFrameWxAgg window, I get a PyDeadObjectError when I run self.Destroy
# self.Destroy() #
# wx.Exit() # forces the program to exit, with no clean up. works, but not an ideal solution
#sys.exit() # program closes, but with segmentation error
#self.Close() # creates infinite recursion error, because we have a binding to wx.EVT_CLOSE
if __name__ == '__main__':
app = wx.PySimpleApp(redirect=False)
app.frame = my_frame()
if '-i' in sys.argv:
wx.lib.inspection.InspectionTool().Show()
app.MainLoop()
To add one more level of complexity, the Segmentation Fault with sys.exit()
only happens with my brew installed Python. Sys.exit() works fine with Canopy
Python.
My questions are: how can I fix this error? And, is using wx.Exit() really so
bad?
Answer: There are several issues with your example:
1. Do not use `pylab` in GUI applications, because is brings its own mainloop (which will not quit when the wxPython mainloop quits). You had to kill pylab.
# both not required
# matplotlib.use('WXAgg')
# import pylab
# use instead
from matplotlib.figure import Figure
...
def __init__(# ...
...
self.fig1 = Figure((5, 5), dpi=100)
2. Your menu item "Close" does not work (at least not on Windows). `wx.ID_EXIT` is meant for buttons in dialogs. Do not ask me which predefined IDs are meant for menus.
ID_QUIT = wx.NewId()
menu_file.Append(ID_QUIT , "Quit", "Quit application")
#
self.Bind(wx.EVT_MENU, self.on_quit, id=ID_QUIT)
def on_quit(self, evt):
self.Close()
3. In this case it is not necessary to bind to `wx.EVT_CLOSE`. If you want to do something on the close event, you have to skip it. When you skip it, wxPython will deal with it on its own.
self.Bind(wx.EVT_CLOSE, self.on_close)
...
def on_close(self, evt):
# you can veto the close here or perform cleanup
evt.Skip()
If you change your code accordingly, wxPython will close everything properly.
|
Adding up a value after matching a line using append from a text file using python 3.x
Question: I have a text file which contains lines as followed
Data_1 (2): 01 sec
Data_1 (1): 01 sec
Data_1 (1): 02 secs
Data_2 (2): 04 secs
Data_1 (3, 1, 2): 2 hrs 40 mins 02 secs
Data_2 (1): 03 secs
Data_1 (3, 1, 2): 20 secs
Data_3 (1): 02 secs
Data_3 (2): 23 secs
I want my output to be like:
Data_1 (2): 01 sec
Data_1 (1): 03 secs
Data_2 (2): 04 secs
Data_1 (3, 1, 2): 2 hrs 40 mins 22 secs
Just adding up the seconds if values in each line till ":" matches with each
other the seconds values should be summed up irrespective of the position they
are located.
Code till now:
with open("folder/file_1", "r") as total_timing:
variable_number = len(variable_name)
evaluated_variables = []
timing = 0
for val, line in zip(range(0,variable_number),total_timing):
if variable_name[val] in line:
value = int((line.split(":")[1]).split()[0])
timing = value + timing
if variable_name[val] not in evaluated_variables:
print(" > " + variable_name[val] + " " + str(timing))
evaluated_variables.append(variable_name[val])
I have got `variable_name` from another loop where I retrieve the variables.
But this code doesn't provide what I require. Any help would really great...!
Answer: I think the easiest approach is to split each line into a name string and a
time integer. Then you can store the cumulative values in an ordered dict and
output them once they're all added up.
from collections import OrderedDict
d = OrderedDict()
with open("folder/file_1") as file:
for line in file:
name, _, raw_time = line.rpartition(":")
time = int(raw_time.strip("sec \n"))
d[name] = d.get(name,0) + time
for name, time in d.items():
print("{}: {:02} {}".format(name, time, "sec" if time == 1 else "secs"))
Result:
Data_1 (2): 01 sec
Data_1 (1): 03 secs
Data_2 (2): 04 secs
Data_1 (3, 1, 2): 04 secs
Data_2 (1): 03 secs
Data_3 (1): 02 secs
Data_3 (2): 23 secs
|
Run SimpleOBEXClient/Server LightAquaBlue on OS X Yosemite 10.10
Question: I have managed to install LightAquaBlue 0.4
(<http://lightblue.sourceforge.net/LightAquaBlue/>) through the command
python setup.py install
However, I have tried to build with Xcode 6.0 both projects
SimpleOBEXClient/Server contained in the folder /example.
The error is:
BBBluetoothOBEXClient.d Dtrace Error: expected predicate and/or actions following the probe
The details are:
VALID_ARCHS: i386 x86-64
How can I fix this issue?
Thank you!
Answer: I successfully managed to fix the issue deleting the framework "LightAquaBlue"
from the Tab General --> Linked Frameworks and Libraries and then re-
installing the same framework by doing:
--> Click "+" below in the left corner;
--> Click "Add other";
--> Go to "/Library/Frameworks";
If you have successfully managed to install light blue 0.4 you should have the
framework called "LightAquaBlue.framework".
--> Add this framework and go to the SimpleOBEXClient/Server.m;
--> Re-type the #import <LightAquaBlue/LightAquaBlue.h> line again.
|
Write a for loop in Abaqus Macro (Python)
Question: I've been using Abaqus for a while but I'm new to macros and python script.
I'm sorry if this kind of question has already been asked, I did search on
google to see if there was a similar problem but nothing works..
My problem is the following :
I have a model in Abaqus, I've ran an analysis with 2 steps and I created a
path in it and I'd like to extract the value of the Von Mises stress along
this path for each frame of each step. Ideally I'd love to save it into an
Excel or a .txt file for easy further analysis (e.g in Matlab).
**Edit :** I solved part of the problem, my macro works and all my data is
correctly saved in the XY-Data manager.
Now I'd like to save all the "Y" data in an excel or text file and I have no
clue on how to do that. I'll keep digging but if anyone has an idea I'll take
it !
Here's the code from the abaqusMacros.py file :
# -*- coding: mbcs -*-
# Do not delete the following import lines
from abaqus import *
from abaqusConstants import *
import __main__
def VonMises():
import section
import regionToolset
import displayGroupMdbToolset as dgm
import part
import material
import assembly
import step
import interaction
import load
import mesh
import optimization
import job
import sketch
import visualization
import xyPlot
import displayGroupOdbToolset as dgo
import connectorBehavior
odbFile = session.openOdb(name='C:/Temp/Job-1.odb')
stepsName = odbFile.steps.keys()
for stepId in range(len(stepsName)):
numberOfFrames = len(odbFile.steps.values()[stepId].frames)
for frameId in range(numberOfFrames):
session.viewports['Viewport: 1'].odbDisplay.setPrimaryVariable(
variableLabel='S', outputPosition=INTEGRATION_POINT, refinement=(
INVARIANT, 'Mises'))
session.viewports['Viewport: 1'].odbDisplay.setFrame(step=stepId, frame=frameId)
pth = session.paths['Path-1']
session.XYDataFromPath(name='Step_'+str(stepId)+'_'+str(frameId), path=pth, includeIntersections=False,
projectOntoMesh=False, pathStyle=PATH_POINTS, numIntervals=10,
projectionTolerance=0, shape=DEFORMED, labelType=TRUE_DISTANCE)
Answer: First of all, your function `VonMises` contains only import statements, other
parts of the code are not properly indented, so they are outside of the
function.
Second of all, the function is never called. If you run your script using
'File > Run script', then you should call the function at the end of your
file.
There two thing seem like obvious errors, but there are some other bad things
as well.
Also, I don't see the point of writing `import __name__` at the top of your
file because I really doubt you have a module name `__name__`; Python
environment used by Abaqus probably doesn't either.
There are some other things that might be improved as well, but you should try
to fix the errors first.
If you got an actual error message from Abaqus (either in the window or in
abaqus.rpy file), it would be helpful if you posted it here.
|
Python with selenium: rerun on pre-existing browser
Question: I'm using Python with Selenium 2.44. When the test fails, I can't just
uncomment all the code before the failure when debugging it, because the
driver will not be declared for the browser. Therefore, whenever I try fixing
something, I always have to open a new browser in the test case. This is
rather... slow since I have to login, which adds an additional 30 seconds (not
devastating, but annoying). I want to know if there's a way for me to just
continue a session, or do something that allows me to start the test midway
through (so if I have the webpage open already, I can just immediately start
clicking things rather than opening a new browser). Is this possible?
For example, if I had something along the lines of:
driver = webdriver.Firefox()
driver.get("google.com")
driver.find_element_by_xpath("//input[@id='gbqfq']").send_keys("cats" + Keys.RETURN)
This should open Firefox, go to google, and search for cats. Pretend like
there's a ton of stuff you have to do before you can actually make it to the
google page, though. Now if it were to fail on the search for cats, the only
way I would be able to test to see if I fixed the code would be to rerun the
test (`webdriver.Firefox()` would open a new browser). Rather than that,
assuming I'd still have google open, I'd like the selenium test to just start
off on the previous browser and google page (therefore saying the first step
in the code would be the `send_keys("cats")`). Is this possible?
I think that this was a similar question, but it didn't get checked off as
answered: [How to resume browser session or use existing browser window with
Selenium-Python?](http://stackoverflow.com/questions/11233225/how-to-resume-
browser-session-or-use-existing-browser-window-with-selenium-pytho)
This one also seems similar, only pertaining to Java: [How do I rerun Selenium
2.0 (webdriver) tests on the same
browser?](http://stackoverflow.com/questions/5383958/how-do-i-rerun-
selenium-2-0-webdriver-tests-on-the-same-browser)
Thanks.
Answer: Look into pdb: <https://docs.python.org/2/library/pdb.html>
Placing this in your code will stop the progression of the test as is until
you tell it to continue in your shell.
Using your code snippit:
from pdb import set_trace
driver = webdriver.Firefox()
driver.get("google.com")
set_trace()
driver.find_element_by_xpath("//input[@id='gbqfq']").send_keys("cats" + Keys.RETURN)
will stop your execution after getting the url, allow you to tinker, and then
continue from where the test left off.
Alternatively, while debugging, you can just remove the driver.quit()
statement, wherever it happens to be, which will keep the browser open
wherever your assertion failed. But if you're using a framework like Django
with the LiveTestServer Client, you won't have access to browse the site
further. pdb will allow you to keep the test server active.
|
Statsmodel multivariate OLS error "matrices are not aligned"
Question: I am trying to solve multivariate regression. Here is the code attached for
the regression. The model builds fine, but when I try to retrieve the summary,
it gives following error
**ValueError: matrices are not aligned**
Here is the traceback:
Traceback (most recent call last):
File "/Users/mikhilraj/Desktop/try2.py", line 23, in <module>
print mod.summary()
File "/Library/Python/2.7/site-packages/statsmodels-0.7.0-py2.7-macosx-10.10-intel.egg/statsmodels/regression/linear_model.py", line 1967, in summary
top_right = [('R-squared:', ["%#8.3f" % self.rsquared]),
File "/Library/Python/2.7/site-packages/statsmodels-0.7.0-py2.7-macosx-10.10-intel.egg/statsmodels/tools/decorators.py", line 97, in __get__
_cachedval = self.fget(obj)
File "/Library/Python/2.7/site-packages/statsmodels-0.7.0-py2.7-macosx-10.10-intel.egg/statsmodels/regression/linear_model.py", line 1181, in rsquared
return 1 - self.ssr/self.centered_tss
File "/Library/Python/2.7/site-packages/statsmodels-0.7.0-py2.7-macosx-10.10-intel.egg/statsmodels/tools/decorators.py", line 97, in __get__
_cachedval = self.fget(obj)
File "/Library/Python/2.7/site-packages/statsmodels-0.7.0-py2.7-macosx-10.10-intel.egg/statsmodels/regression/linear_model.py", line 1153, in ssr
return np.dot(wresid, wresid)
ValueError: matrices are not aligned
**Code:**
import numpy as np
import statsmodels.api as sm
np.random.seed(12345)
N = 30
X = np.random.uniform(-20, 20, size=(N,10))
beta = np.random.randn(11)
X = sm.add_constant(X)
weights = np.random.uniform(1, 20, size=(N,))
weights = weights/weights.sum()
y = np.dot(X, beta) + weights*np.random.uniform(-100, 100, size=(N,))
Y = np.c_[y,y,y]
mod = sm.OLS(Y, X).fit()
print mod.summary()
Answer: The `endog` parameter should be a 1D vector of the dependent variable.
Changing the parameter `Y` in your model to `y` (for example) allows the code
to run without error.
<http://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.OLS.html>
|
bad zip file error in POS tagging in NLTK in python
Question: I am new to python and NLTK ..I want to do word tokenization and POS Tagging
in this.I installed Nltk 3.0 in my Ubuntu 14.04 having a default python
2.7.6.First I tried to do tokenization of a simple sentence.But I am getting
an error,telling that "BadZipfile: File is not a zip file".How to solve
this????
..One more doubt..i.e. i gave path as "/usr/share/nltk_data" when i installed
Nltk data (using command line).Some of the pakages couldnt be installed due to
some errors.But it shows other paths when i cheked using command
"nltk.data.path" and the other paths are invalid actually.. why???
I have got 1000 text files.How to code a program for tokenization and POS
tagging for this much files together as a input in python..i dont know..
Please help me...
The way I used commands in python interpretter, is given below in the same
order below
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> import nltk
>>> nltk.data.path
['/home/ubuntu/nltk_data', '/usr/share/nltk_data', '/usr/local/share/nltk_data', '/usr/lib/nltk_data', '/usr/local/lib/nltk_data']
>>> from nltk import pos_tag, word_tokenize
>>> sentence = "Hello my name is Derek. I live in Salt Lake city."
>>> sentence
'Hello my name is Derek. I live in Salt Lake city.'
>>> word_tokenize(sentence)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
word_tokenize(sentence)
File "/usr/local/lib/python2.7/dist-packages/nltk/tokenize/__init__.py", line 93, in word_tokenize
return [token for sent in sent_tokenize(text)
File "/usr/local/lib/python2.7/dist-packages/nltk/tokenize/__init__.py", line 81, in sent_tokenize
tokenizer = load('tokenizers/punkt/english.pickle')
File "/usr/local/lib/python2.7/dist-packages/nltk/data.py", line 774, in load
opened_resource = _open(resource_url)
File "/usr/local/lib/python2.7/dist-packages/nltk/data.py", line 888, in _open
return find(path_, path + ['']).open()
File "/usr/local/lib/python2.7/dist-packages/nltk/data.py", line 605, in find
return find(modified_name, paths)
File "/usr/local/lib/python2.7/dist-packages/nltk/data.py", line 592, in find
return ZipFilePathPointer(p, zipentry)
File "/usr/local/lib/python2.7/dist-packages/nltk/compat.py", line 380, in _decorator
return init_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/nltk/data.py", line 449, in __init__
zipfile = OpenOnDemandZipFile(os.path.abspath(zipfile))
File "/usr/local/lib/python2.7/dist-packages/nltk/compat.py", line 380, in _decorator
return init_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/nltk/data.py", line 946, in __init__
zipfile.ZipFile.__init__(self, filename)
File "/usr/lib/python2.7/zipfile.py", line 770, in __init__
self._RealGetContents()
File "/usr/lib/python2.7/zipfile.py", line 811, in _RealGetContents
raise BadZipfile, "File is not a zip file"
BadZipfile: File is not a zip file
>>>
Thanks in advance.....
Answer: You apparently did not yet run `download_corpora.py` (successfully).
|
ImportError: cannot import name pynestkernel
Question: So I spend last night trying to install nest (and pynest) to use with PyNN,
and I am currently stuck. When I try to import nest I get:
>>> import nest
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nest/__init__.py", line 52, in <module>
from . import pynestkernel as _kernel
ImportError: cannot import name pynestkernel
However, when I make the make installcheck it passes all the pynest tests. I
am using OS x Yosemite, and I did a new install of python 2.7.9 using macport.
Tried:
easy_install python-nest
Now I am getting a new error.
Getting:
>>> import pyNN.nest as sim
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import pyNN.nest as sim
File "/Library/Python/2.7/site-packages/pyNN/nest/__init__.py", line 13, in <module>
from pyNN.nest import simulator
File "/Library/Python/2.7/site-packages/pyNN/nest/simulator.py", line 500, in <module>
state = _State() # a Singleton, so only a single instance ever exists
File "/Library/Python/2.7/site-packages/pyNN/nest/simulator.py", line 60, in __init__
self._cache_num_processes = nest.GetKernelStatus()['num_processes'] # avoids blocking if only some nodes call num_processes
AttributeError: 'module' object has no attribute 'GetKernelStatus'
Answer: Try using `setuptools` to install `nest` with `easy_install python-nest`.
|
BeanShell command line interpreter features
Question: I'm trying to test BeanShell's command line interpreter in how it processes
basic Java commands and syntax on my machine, and see if I can customise its
behavior in any way. I've installed version 2.0b4 on my machine running OS X
10.10.1 (the JAR file is in `/Library/Java/Extensions` as per the
instructions).
It's the closest thing to what I've been looking for, an interactive Java
interpreter, but it doesn't have some standard features which a good
interpreter should have.
1. I'd like to be able to use the Up arrow key to reuse a previous command, but at the moment it doesn't recognise it, it just shows a control sequence. Is there a way to customise this for BeanShell?
2. Is there a way to get BeanShell to print out the value of a variable if I've created it beforehand, just by naming it, like
String s = new String( "Hello World!" ); s; Hello World!.
This is possible in Python for example.
3. According to the documentation on importing Java classes `which(<java class>);` should return the classpath location of the specified Java class. But `which( java.lang.String );` does not work for me, I get a `NullPointerException`:
bsh % which(java.lang.String);
Start ClassPath Mapping Mapping: Directory /Users/srm // Error: // Uncaught
Exception: Method Invocation cp.getClassSource : at Line: 42 : in file:
/bsh/commands/which.bsh : cp .getClassSource ( className )
Called from method: which : at Line: 8 : in file: : which ( java .lang .String
) Target exception: java.lang.NullPointerException
java.lang.NullPointerException
Any pointers or help would be appreciated.
Answer: 1. Run beanshell with jline.
Download jline jar from <http://jline.sourceforge.net/index.html> and then you
can do:
java -cp jline-1.0.jar:bsh-2.0b4.jar jline.ConsoleRunner bsh.Interpreter
Line editing capability will be provided by jline. I found this hint
[here](https://code.google.com/p/beanshell2/issues/detail?id=52).
There are issues running with [jline2](https://github.com/jline/jline2).
First, you'll get:
$ java -cp jline-2.12.jar:bsh-2.0b4.jar jline.ConsoleRunner bsh.Interpreter
Exception in thread "main" java.lang.NoClassDefFoundError: jline/ConsoleRunner
Due to [this](https://github.com/jline/jline2/issues/21) issue which is fixed.
But then, use the new class and you still get:
$ java -cp jline-2.12.jar:bsh-2.0b4.jar jline.console.internal.ConsoleRunner bsh.Interpreter
Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
due to [this](https://github.com/jline/jline2/issues/157) issue which is not
fixed yet.
2. Use show() command which will trigger showing of value.
>
> bsh % show();
> bsh % String s = new String("Hello World");
> bsh % s;
> <Hello World>
> bsh %
>
It is mentioned in the **[Useful BeanShell
Commands](http://www.beanshell.org/manual/quickstart.html#Useful_BeanShell_Commands)**
section of the documentation.
3. Doesn't work for me either
It doesn't fail in my case, but it didn't find it either.
>
> bsh % which(java.lang.String);
> Start ClassPath Mapping
> Mapping: Archive: file:/Users/me/beanshell/jline-1.0.jar
> Mapping: Archive: file:/Users/me/beanshell/bsh-2.0b4.jar
> Mapping: Archive:
> file:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar
> End ClassPath Mapping
> null
> bsh %
>
|
Python sqlite3.OperationalError: no such table:
Question: I am trying to store data about pupils at a school. I've done a few tables
before, such as one for passwords and Teachers which I will later bring
together in one program.
I have pretty much copied the create table function from one of these and
changed the values to for the Pupil's information. It works fine on the other
programs but I keep getting:
sqlite3.OperationalError: no such table: PupilPremiumTable
when I try to add a pupil to the table, it occurs on the line:
cursor.execute("select MAX(RecordID) from PupilPremiumTable")
I look in the folder and there is a file called `PupilPremiumTable.db` and the
table has already been created before, so I don't know why it isn't working.
Here is some of my code, if you need more feel free to tell me so, as I said
it worked before so I have no clue why it isn't working or even what isn't
working:
with sqlite3.connect("PupilPremiumTable.db") as db:
cursor = db.cursor()
cursor.execute("select MAX(RecordID) from PupilPremiumTable")
Value = cursor.fetchone()
Value = str('.'.join(str(x) for x in Value))
if Value == "None":
Value = int(0)
else:
Value = int('.'.join(str(x) for x in Value))
if Value == 'None,':
Value = 0
TeacherID = Value + 1
print("This RecordID is: ",RecordID)
Answer: You are assuming that the current working directory is the same as the
directory your script lives in. It is not an assumption you can make. Your
script is opening a _new_ database in a different directory, one that is
empty.
Use an absolute path for your database file. You can base it on the absolute
path of your script:
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "PupilPremiumTable.db")
with sqlite3.connect(db_path) as db:
You can verify what the current working directory is with
[`os.getcwd()`](https://docs.python.org/2/library/os.html#os.getcwd) if you
want to figure out where instead you are opening the new database file; you
probably want to clean up the extra file you created there.
|
Python Django json serialise
Question: I have a mysql objects.filter that I was trying to serialise to json. My
fields are `domain, generated_on, id, priority_mx, record, record_points_to,
ttl`
However, after I serialise the data like
from getdata.models import record_search
query_data = record_search.objects.filter(**filter_kwargs).only("domain", "record", "record_points_to", "priority_mx", "ttl", "generated_on")
data = serializers.serialize(lang, query_data)
my data has one additional field
model: "getdata.record_search"
I tried to remove it, by trying to select the fields as
data = serializers.serialize(lang, query_data, fields=('domain','record_points_to'))
but `model: "getdata.record_search"` still remains in my serialised json data.
What is the best way to exclude this?
As of now, since the serializers.serialize() returns a string, I am doing it
as
return re.sub('\"model\"\:\s+?\"getdata\.record_search\"\,', "", data)
But I am sure this is an ugly way to do this. What is the pythonic best way to
achieve this?
Answer: Serialization is used for serializing/unserializing of **models**. Django is
unable to unserialize model without this "model" field.
Why you use serialization at all? Why not use standard json library?
import json
from getdata.models import record_search
query_data = record_search.objects.filter(**filter_kwargs) \
.values("id", "domain", "record", "record_points_to",
"priority_mx", "ttl", "generated_on")
data = json.dumps(list(query_data))
|
CGI with Python
Question: I'm beginning to use CGI with Python.
After running the following piece of code:
#!c:\python34\python.exe
import cgi
print("Content-type: text/html\n\n") #important
def getData():
formData = cgi.FieldStorage()
InputUN = formData.getvalue('username')
InputPC = formData.getvalue('passcode')
TF = open("TempFile.txt", "w")
TF.write(InputUN)
TF.write(InputPC)
TF.close()
if __name__ =="__main__":
LoginInput = getData()
print("cgi worked")
The following error occurs:
Traceback (most recent call last):
File "C:\xampp\htdocs\actual\loginvalues.cgi", line 21, in <module>
LoginInput = getData()
File "C:\xampp\htdocs\actual\loginvalues.cgi", line 16, in getData
TF.write(InputUN)
TypeError: must be str, not None
>>>
I'm trying to write the values, inputted in html, to a text file.
Any help would be appreciated :)
Answer: Your calls to `getValue()` are returning `None`, meaning the form either
didn't contain them, had them set to an empty string, or had them set by name
only. Python's CGI module ignores inputs that aren't set to a non-null string.
Works for Python CGI:
* `mysite.com/loginvalues.cgi?username=myname&pass=mypass`
Doesn't work for Python CGI:
* `mysite.com/loginvalues.cgi?username=&pass=` (null value(s))
* `mysite.com/loginvalues.cgi?username&pass` (Python requires the `=` part.)
To account for this, introduce a default value for when a form element is
missing, or handle the None case manually:
TF.write('anonymous' if InputUN is None else InputUN)
TF.write('password' if InputPC is None else InputUN)
As a note, passwords and other private login credentials should never be used
in a URL. **URLs are not encrypted**. Even in HTTPS, the URL is sent in plain
text that anyone on the network(s) between you and your users can read.
The only time a URL is ever encrypted is over a tunneled SSH port or an
encrypted VPN, but you can't control that, so never bank on it.
|
Using functions as input
Question: I've written a program (A) that takes, as input, the names of functions I
wrote in a separate program (B). I want to use these functions in program (A),
so I am trying to run (A) by doing this: A(f1, f2, f3, f4)
At the top of (A), I imported program (B) using import B. In (A) there is just
one function (excluding main) that accepts four inputs (f1, f2, f3, f4), and
then uses them, like this:
for i in range(x, y):
z = B.f1(i)
u = B.f2(i)
...
...
The trouble is, when I try to run A(f1, f2, f3, f4), I get the error
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
A(f1, f2, f3, f4)
NameError: name 'f1' is not defined
I see that python is not recognizing the functions in (B) as input in (A), but
I don't know why or how else I can connect the two programs.
Update: Program A
def A(f1, f2, f3, f4) :
x = 0
y = 10
for i in range(x, y):
x = B.f1(i) //returns float
plt.plot(i, x)
...
Answer: Based on a literal reading of your question, if you imported B via
import B
then every reference to functions, variables, classes etc defined in B must be
done in the form `B.func1` etc.
Your error message clearly says that you're trying to do `A(f1, f2, f3, f4)`.
This should be `A(B.f1, B.f2, B.f3, B.f4)`
**EDIT** Judging from your updated question, I'm guessing you want something
like:
import B
def A(input_function1, input_function2, input_function3, input_function4) :
x = 0
y = 10
for i in range(x, y): #btw, you don't need the x value here if it's 0
x = input_function1(i) //returns float #I removed the 'B.'
plt.plot(i, x)
# Other stuff here
if __name__=='__main__':
A(B.f1, B.f2, B.f3, B.f4)
# or alternatively A(B.f78, B.f21, B.f1, B.f90) or whatever
Or alternatively:
from B import f1, f2, f3, f4
def A(f1, f2, f3, f4) :
# Stuff here
if __name__=='__main__':
A(f1, f2, f3, f4) # Explicit imports mean that the 'B.' prefix is unnecessary
|
List being altered while working on copy in Python 2.7
Question: I made a copy of a list in python so that I could analyze the old matrix
without affecting it during calculation, however the original list is being
altered, as shown by my output. Here is my code:
def golevolve():
global world
print world
world2 = world[:]
for y in xrange(1,ymax-1):
for x in xrange(1,xmax-1):
total = 0
for i in xrange(y-1,y+2):
for j in xrange(x-1,x+2):
if not(i == y and j == x):
if world[i][j] == 1:
total += world[i][j]
if world[y][x] == 1:
if (total >= 2) and (total <= 3):
world2[y][x] = 1
else:
world2[y][x] = 0
if world[y][x] == 0:
if total == 3:
world2[y][x] = 1
else:
world2[y][x] = 0
print world
world = world2[:]
print world
return
this is the output
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, **1** , 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, **1** , 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1** , **1** , **1** , 0], [0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0]]
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, **1** , 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1** , **1** , 0], [0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, **1** , 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1** , **1** , 0], [0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
NOTICE THAT output 2 and 3 are the same, output 2 is before
world = world2[:]
Answer: You're using a **shallow** copy -- sharing the same items. You may prefer a
**deep** copy -- with independent items; in lieu of
world2 = world[:]
use
import copy
world2 = copy.deepcopy(world)
|
When I'm plotting a colorbar in python using matplotlib I'm getting an error
Question: I am using python 2.7 and want to make a simple colorbar. What I'm doing is
this:
import matplotlib.pylab as plt
import matplotlib as mpl
redgreendict = {'red':[(0.0, 1.0, 1.0), (0.5, 1.0, 1.0) ,(1.0, 0.0, 0.0)],
'green':[(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)],
'blue':[(0.0, 0.2, 0.0), (0.5, 1.0, 1.0), (1.0, 0.2, 0.0)]}
fig = plt.figure()
ax1 = fig.add_axes([0.05, 0.08, 0.9, 0.08])
cmap = mpl.colors.LinearSegmentedColormap('redgreen', redgreendict, 1000)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap, orientation='vhorizontal')
And I get this error message:
File "figutils_used_one.py", line 1208, in make_europe_graph
cb1 = matplotlib.colorbar.ColorbarBase(ax1, cmap, orientation='vhorizontal')
File "C:\Anaconda\lib\site-packages\matplotlib\colorbar.py", line 320, in __init__
self.config_axis()
File "C:\Anaconda\lib\site-packages\matplotlib\colorbar.py", line 360, in config_axis
ax.xaxis.set_label_position(self.ticklocation)
File "C:\Anaconda\lib\site-packages\matplotlib\axis.py", line 1728, in set_label_position
assert position == 'top' or position == 'bottom'
AssertionError
I suppose that the problem lays in the orientation part of the
matplotlib.colorbar.ColorbarBase. I have been looking around and maybe it
could be a version-of-Pyhton problem. Instead of of `vhorizontal` i tried to
put `vertical`, `v`, `h` in the argument for orientation but anyway nothing
happens.
Answer: This code works for me:
import matplotlib.pylab as plt
import matplotlib as mpl
min_val = -1
max_val = 1
redgreendict = {'red':[(0.0, 1.0, 1.0), (0.5, 1.0, 1.0) ,(1.0, 0.0, 0.0)],
'green':[(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)],
'blue':[(0.0, 0.2, 0.0), (0.5, 1.0, 1.0), (1.0, 0.2, 0.0)]}
cmap = mpl.colors.LinearSegmentedColormap('redgreen', redgreendict, 1000)
norm = mpl.colors.Normalize(min_val, max_val)
fig = plt.figure()
ax1 = fig.add_axes([0.05, 0.08, 0.9, 0.08])
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap, norm=norm, orientation='horizontal')
This is the result:

|
django os.path.dirname(__file__)
Question: I am doing exercises from book:
<http://www.tangowithdjango.com/book17/chapters/templates_static.html>
and I have problem with this code:
import os
print __file__
print os.path.dirname(__file__)
print os.path.dirname(os.path.dirname(__file__))
It shold print dir names. Instead of that it prints first line ( filename) but
2nd and 3rd line are also printed but empty.
I get this behavior with Python 2.7 on Windows 7 and Ubuntu 14.04
EDIT: with this code i get absolute path with `os.path.dirname(__file__)`:
import os
import django
import settings
print settings.BASE_DIR
What is the difference if the same code is imporeted from settings.py and
coded directly?
Answer: The `__file__` value in the _main script_ can be relative to the current
working directory. Use
[`os.path.abspath()`](https://docs.python.org/2/library/os.path.html#os.path.abspath)
to make it absolute first:
print os.path.abspath(__file__)
print os.path.dirname(os.path.abspath(__file__))
print os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
How to define/install Scala facet in IntelliJ IDEA 14.0.x?
Question: In [How to fix IntelliJ IDEA's SDK after it got "corrupted" that leads to
"{class} cannot be found"?](http://stackoverflow.com/q/28132765/1305344) I
found screenshots with Scala facet (and Python one). I don't have it nor can I
define one myself.

How can I define or install a Scala facet in IntelliJ IDEA 14.0.2 or the
latest 14.0.3 EAP with the latest respective version of the Scala plugin?

My usual approach to work with sbt/Scala projects in IDEA is to import a
sbt/Scala project after it's created using Typesafe Activator.
Answer: **tl;dr** [There's no Scala facet in IntelliJ IDEA
14.](http://blog.jetbrains.com/scala/2014/10/30/scala-plugin-update-for-
intellij-idea-14-rc-is-out/)
[As @PermaFrost correctly pointed out in the
comment](http://stackoverflow.com/questions/28137320/how-to-define-install-
scala-facet-in-intellij-idea-14-0-x?noredirect=1#comment44648360_28137320),
IntelliJ IDEA 14 has introduced ["Rethinking the project configuration
model"](http://blog.jetbrains.com/scala/2014/10/30/scala-plugin-update-for-
intellij-idea-14-rc-is-out/), i.e.:
> Another change is that we’ve finally decided to get rid of the Scala facet
> and replace it with so called Scala SDK library that, in addition to the
> standard Scala libraries, has a classpath to Scala compiler
|
Type Error when Comparing Two Dictionaries Using Cosine Similarity in Python
Question: I have received a type error while comparing two dictionaries using the cosine
similarity. I have tried to search around but still not able to solve it, and
would really appreciate if anyone could shed some light for me.
My dictionaries look as like below.
dict1 = {'a': 1, 'b': 0, 'c': 1}
dict2 = {'a': 1, 'b': 1, 'c': 0}
I have also looked around in stack overflow, and indeed there are members who
also compared the values of dictionaries using cosine similarity. And I
thought it should be very similar to my case. This is the url where I
referenced to: [Python: calculate cosine similarity of two dicts
faster](http://stackoverflow.com/questions/22381939/python-calculate-cosine-
similarity-of-two-dicts-faster)
This is the function as provided by @Davidmh (with slight modifications to
it):
import numpy as np
def cos(v1, v2):
up = 0
for key in set(v1).intersection(v2):
v1_value = v1[key]
v2_value = v2[key]
up += v1_value * v2_value
if up == 0:
return 0
return up / (np.sqrt(np.dot(v1.values(), v1.values())) * np.sqrt(np.dot(v2.values(), v2.values())))
So the next thing I did is to call the function:
print(cos(dict1, dict2))
And below is the type error message that I received.
File "C:/Users/Yoshiaki/TextProcessing/compute.py", line 157, in cos
return up / (np.sqrt(np.dot(v1.values(), v1.values())) * np.sqrt(np.dot(v2.values(), v2.values())))
TypeError: unsupported operand type(s) for *: 'dict_values' and 'dict_values'
I have googled on the type error that appeared, but it doesn't gives me much
explanation nor result. And it seems to do with set operations...? I also
tried even without using the set operation (intersection), it will also give
me the same error message...
Could anyone please advice to me of how I could solve this problem?
Thanks.
Answer: Could you try changing them to lists via list(v1.values())? dict_values is a
type, so converting it to a list may solve the issue.
return up / (np.sqrt(np.dot(list(v1.values()), list(v1.values()))) * np.sqrt(np.dot(list(v2.values()), list(v2.values()))))
Reference: [Python: simplest way to get list of values from
dict?](http://stackoverflow.com/questions/16228248/python-simplest-way-to-get-
list-of-values-from-dict)
|
Some ttk styles not accessible from within python script
Question: I am trying to use a ttk style for my Tkinter gui.
When I run on the command line
>>> from ttk import *
>>> print Style().theme_names()
('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative')
which appears fine, as I want the `vista` style. However, when running a
script with the following lines:
from ttk import *
print Style().theme_names()
the output is:
('clam', 'alt', 'default', 'classic')
and so when I try:
from ttk import *
Style().theme_use("vista")
I get:
File "test.py", line 2, in <module>
Style().theme_use("vista")
File "/usr/lib/python2.7/lib-tk/ttk.py", line 534, in theme_use
self.tk.call("ttk::setTheme", themename)
_tkinter.TclError: can't find package ttk::theme::vista
Not sure what it could be and I've not had much luck googling.
I'm running from within Console2 under cygwin if that makes any difference.
Thanks!
Answer: Some of the ttk themes are supported on only one platform. xpnative,
winnative, and vista, for example, only work on windows. The "aqua" theme only
works on OSX. The others, I think, run on any platform.
If you're running via cygwin, the version of python you're running was
probably configured differently at compile time so that it think it is running
on linux rather than windows. Therefore, it doesn't have access to windows
themes.
|
Can Pandas read and modify a single Excel file worksheet (tab) without modifying the rest of the file?
Question: Many spreadsheets have formulas and formatting that Python tools for reading
and writing Excel files cannot faithfully reproduce. That means that any file
I want to create programmatically must be something I basically create from
scratch, and then other Excel files (with the aforementioned sophistication)
have to refer to that file (which creates a variety of other dependency
issues).
My understanding of Excel file 'tabs' is that they're actually just a
collection of XML files. Well, is it possible to use pandas (or one of the
underlying read/write engines such as xlsxwriter or openpyxl to modify just
one of the tabs, leaving other tabs (with more wicked stuff in there) intact?
EDIT: I'll try to further articulate the problem with an example.
* Excel Sheet test.xlsx has four tabs (aka worksheets): Sheet1, Sheet2, Sheet3, Sheet4
* I read Sheet3 into a DataFrame (let's call it df) using pandas.read_excel()
* Sheet1 and Sheet2 contain formulas, graphs, and various formatting that neither openpyxl nor xlrd can successfully parse, and Sheet4 contains other data. I don't want to touch those tabs at all.
* Sheet2 actually has some references to cells on Sheet3
* I make some edits to df and now want to write it back to sheet3, leaving the other sheets untouched (and the references to it from other worksheets in the workbook intact)
Can I do that and, if so, how?
Answer: I had a similar question regarding the interaction between excel and python
(in particular, pandas), and I was referred to this question.
Thanks to some pointers by stackoverflow community, I found a package called
[xlwings](http://docs.xlwings.org/quickstart.html#interact-with-excel-from-
python) that seems to cover a lot of the functionalities HaPsantran required.
To use the OP's example:
Working with an existing excel file, you can drop an anchor in the data block
(Sheet3) you want to import to pandas by naming it in excel and do:
# opened an existing excel file
`wb = Workbook(Existing_file)`
# Find in the excel file a named cell and reach the boundary of the cell block (boundary defined by empty column / row) and read the cell
`df = Range(Anchor).table.value`
# import pandas and manipulate the data block
df = pd.DataFrame(df) # into Pandas DataFrame <br>
df['sum'] = df.sum(axis= 1)
# write back to Sheet3
Range(Anchor).value = df.values
# tested that this implementation didn't temper existing formula in the excel
file
Let me know if this solves your problem and if there's anything I can help.
Big kudos to the developer of xlwings, they made this possible.
|
Install .whl error
Question: I want to use `curses` module in windows.So I found
[python celery - ImportError: No module named _curses - while attempting to
run manage.py celeryev](http://stackoverflow.com/questions/10488826/python-
celery-importerror-no-module-named-curses-while-attempting-to-run-m)
And when I want to install, I am getting an error.
I am running
pip install curses-2.2-cp34-none-win32.whl
pip install curses-2.2-cp34-none-win_amd64.whl
pip install --use-wheel curses-2.2-cp34-none-win32.whl
pip install --use-wheel curses-2.2-cp34-none-win_amd64.whl
All it does is display this error:
> curses-2.2-cp34-none-*.whl is not a supported wheel on this platform.
Why? How can I solve it?
Answer: You probably want the cp27 wheel (cp34 is for CPython 3.4)
|
Plotting planet speed in Python using matplotlib and quantities: RuntimeError
Question: I am writting a program in python to plot planet's distances to the Sun vs
orbital velocity. No problem with that. Then I have to plot in the same graph,
a line with the function: v = GMsun/r, where v is orbital speed, G is Newton's
Gravitational constant, Msun the mass of the Sun and r is distance. I use
quantities library to keep dimensional consistency between units. When I try
to plot that function, I get this error. Could you tell me where is the error?
import numpy as np
import matplotlib.pyplot as plt
import quantities as pq
#orbital velocity (km/s)
velocity= np.array([47.8725, 35.021, 29.7859, 24.130, 13.0697, 9.6724, 6.8352, 5.4778])
#Distance (UA)
distance = np.array([0.38709893, 0.72333199, 1., 1.52366231, 5.20336301, 9.53707032, 19.19126393, 30.06896348])
#Normalize so distance to Earth = 1
velocity2 = velocity / (29.7859)
#Calculate the equation:
Msun = 1.9891e30 * pq.kg #Sun mass
G = 1 * pq.constants.G #Gravitational constant
r = np.arange(0.1,34,0.1) * pq.au #Distance to Sun in Astronomical Units
Vc = np.sqrt(G*Msun/ r) #equation
Vc2 = Vc.rescale(pq.km / pq.s) / 29.7859 #convert to km/s and normalize to Earth's speed.
#Plotting:
fig = plt.figure()
plt.plot(distance, velocity2, 'ro')
plt.plot(r, Vc2, 'b-')
plt.ylabel(r'Orbital Velocity (km/s)', fontsize = 18)
plt.xlabel(r'Distance to Sun (AU)', fontsize = 18)
plt.show()
The error doesn't show if I coment the line plt.plot(r, Vc2, 'b-'). the error
is this, the first line repeats a lot, so I only show irt once:
File "/usr/lib64/python2.7/site-packages/matplotlib/units.py", line 148, in get_converter
converter = self.get_converter(xravel[0])
File "/usr/lib/python2.7/site-packages/quantities/quantity.py", line 352, in __getitem__
return Quantity(ret, self._dimensionality)
File "/usr/lib/python2.7/site-packages/quantities/quantity.py", line 126, in __new__
ret = np.array(data, dtype=dtype, copy=copy).view(cls)
File "/usr/lib/python2.7/site-packages/quantities/quantity.py", line 215, in __array_finalize__
self._dimensionality = getattr(obj, 'dimensionality', Dimensionality())
RuntimeError: maximum recursion depth exceeded while calling a Python object
[Finished in 8.6s with exit code 1]
Thanks so much.
Answer: OK SOLVED: just removed and reinstalled pyplot, and everything runs fine now.
Thanks.
|
Unable to parse Url with python urlparse
Question: I am trying to write a small script that will take url as input and will parse
it.
Following is my script
#! /usr/bin/env python
import sys
from urlparse import urlsplit
url = sys.argv[1]
parseUrl = urlsplit(url)
print 'scheme :', parseUrl.scheme
print 'netloc :', parseUrl.netloc
But when I execute this script with `./myscript http://www.example.com`
it shows following error.
AttributeError: 'tuple' object has no attribute 'scheme'
I am new to `python/scripting`, where am I doing wrong?
**Edit:** Python version that I am using is `Python 2.7.5`
Answer: You don't want scheme. Instead in this case you want to access the `0` index
of the tuple and the `1` index of the tuple.
print 'scheme :', parseUrl[0]
print 'netloc :', parseUrl[1]
`urlparse` uses the `.scheme` and `.netloc` notation, [`urlsplit` instead uses
a tuple (refer to the appropriate index
number):](https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit)
> This is similar to urlparse(), but does not split the params from the URL.
> This should generally be used instead of urlparse() if the more recent URL
> syntax allowing parameters to be applied to each segment of the path portion
> of the URL (see RFC 2396) is wanted. A separate function is needed to
> separate the path segments and parameters. This function returns a 5-tuple:
> (addressing scheme, network location, path, query, fragment identifier).
>
> The return value is actually an instance of a subclass of tuple. This class
> has the following additional read-only convenience attributes:
>
>
> Attribute Index Value Value if not
> present
> scheme 0 URL scheme specifier empty string
> netloc 1 Network location part empty string
> path 2 Hierarchical path empty string
> query 3 Query component empty string
> fragment 4 Fragment identifier empty string
> username User name None
> password Password None
> hostname Host name (lower case) None
> port Port number as integer, if present None
>
|
wxPython conditionally display and hide
Question: I am new to wxPython and would like to use it to build a simple dynamic UI
which conditionally show and hide some drop-down boxes, which can be done
easily in jQuery.
So from my first level combo-box, if a user choose 'Op1_1', a second level
combo-box A will appear. On the other hand, if 'Op1_2' is selected, at the
same location, a different second level combo-box B will be generated.
1. Question 1: I am able to add a second level combo-box box on the fly, but its location is not correct. From the attached figure, you can see it always goes to the top left. Is there a way to re-position this?
2. Question 2: If the first second combo-box A is generated, then the user chooses 'Op1_2', theoretically, combo-box B will replace combo-box A. But I ran into an error `wxGridBagSizer::Add(): An item is already at that position`. How to destroy a previously built box?
3. Question 3: Is there a way to integrate wxPython and jQuery, which could make my life easier....

import wx
class landing_frame(wx.Frame):
def __init__(self, parent, title):
super(landing_frame, self).__init__(parent, title=title,
size=(450, 350))
self.font1 = wx.Font(18, wx.DECORATIVE, wx.ITALIC, wx.BOLD)
self.InitUI()
self.Centre()
self.Show()
def InitUI(self):
self.panel = wx.Panel(self)
self.sizer = wx.GridBagSizer(5, 5)
self.text1 = wx.StaticText(self.panel, label="Welcome!")
self.sizer.Add(self.text1, pos=(0, 0), flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=15)
line = wx.StaticLine(self.panel)
self.sizer.Add(line, pos=(1, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=10)
self.text2 = wx.StaticText(self.panel, label="First Level Dropdown")
self.sizer.Add(self.text2, pos=(2, 0), flag=wx.LEFT, border=10)
self.sampleList = ['Op1_1', 'Op1_2']
self.combo = wx.ComboBox(self.panel, 30, choices=self.sampleList)
self.combo.Bind(wx.EVT_COMBOBOX, self.EvtComboBox)
self.sizer.Add(self.combo, pos=(2, 1), span=(1, 2), flag=wx.TOP|wx.EXPAND, border=5)
self.panel.SetSizer(self.sizer)
def EvtComboBox(self, event):
self.user_choice = event.GetString()
if self.user_choice == "Op1_1":
self.sampleList_ss1 = ['Op2_1_1', 'Op2_1_2', 'Op2_1_3']
self.combo_ss1 = wx.ComboBox(self.panel, 31, choices=self.sampleList_ss1)
self.combo_ss1.Bind(wx.EVT_COMBOBOX, self.EvtComboBox)
self.sizer.Add(self.combo_ss1, pos=(3, 1), span=(1, 2), flag=wx.TOP|wx.EXPAND, border=5)
self.panel.SetSizer(self.sizer)
if self.user_choice == "Op1_2":
self.sampleList_ss2 = ['Op2_2_1', 'Op2_2_2', 'Op2_2_3']
self.combo_ss2 = wx.ComboBox(self.panel, 31, choices=self.sampleList_ss2)
self.combo_ss2.Bind(wx.EVT_COMBOBOX, self.EvtComboBox)
self.sizer.Add(self.combo_ss2, pos=(3, 1), span=(1, 2), flag=wx.TOP|wx.EXPAND, border=5)
self.panel.SetSizer(self.sizer)
if __name__ == '__main__':
app = wx.App(redirect=False, filename="mylogfile.txt")
landing_frame(None, title="Test")
app.MainLoop()
Answer: 1. Try calling self.panel.Layout(). There is no need to do self.panel.SetSizer(self.sizer) again.
2. You can call wx.Sizer.Remove(window). wx.Sizer also has a replace function, but I am not sure how it works with a GridBagSizer. You could also create all your combo boxes, hide or disable those you do not need, and change their contents as needed (wx.ComboBox derives from wx.ControlWithItems, and has member functions Clear, Delete, Append, Insert). If you decide to delete the combo boxes, then, first Remove it from the sizer, and call Destroy.
3. No.
|
Writing the Content-Length header to the client from the server in Tornado
Question: I have a tornado server, that simply prints the headers that the client sent.
server.py :
import tornado.httpserver
import tornado.ioloop
import tornado.httputil as hutil
def handle_request(request):
message = ""
try :
message = request.headers['Content-Length']
except KeyError :
message = request.headers
request.connection.write_headers(
tornado.httputil.ResponseStartLine('HTTP/1.1', 200, 'OK'),
tornado.httputil.HTTPHeaders
({"Content-Length": str(len(message))}))
request.connection.finish()
print(request.headers)
http_server = tornado.httpserver.HTTPServer(handle_request)
http_server.listen(8888, address='127.0.0.1')
tornado.ioloop.IOLoop.instance().start()
When I send request to this server using curl, I get the following traceback.
ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/http1connection.py", line 234, in _read_message
delegate.finish()
File "/usr/local/lib/python2.7/dist-packages/tornado/httpserver.py", line 280, in finish
self.server.request_callback(self.request)
File "Tests/tornado_server.py", line 17, in handle_request
request.connection.finish()
File "/usr/local/lib/python2.7/dist-packages/tornado/http1connection.py", line 430, in finish
self._expected_content_remaining)
HTTPOutputError: Tried to write 5 bytes less than Content-Length
The headers that I sent from Curl :
{'Host': '127.0.0.1:8888', 'Accept': '*/*', 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537.36'}
Is it necessary that I should write back the same amount of data as Content-
Length ? If so why and how should that be done ? Thanks in advance.
Answer: You need to write back the same number of bytes as you say you will. You
returned a `Content-Length` header for the _response_. That means your
response _body_ needs to contain that many bytes.
By the looks of it you don't write _anything_ back for a response body; if you
are stating that you are sending `len(str(message))` bytes, you probably
wanted to send `str(message)` too:
request.connection.write(str(message))
This is _separate_ from the `Content-Length` in the _request_ , which denotes
how many bytes the request body contains.
|
I cannot get the restart button to work on my stopwatch. Using Pythonista on iPhone
Question:
import ui
from time import *
start = int(time())
def stop_time(sender):
finish = int(time())
total_time = int(finish - start)
button1 = str("Your time is %i seconds." % (total_time))
sender.title = None
sender.title = str(button1)
# How do I allow the restart button to change the start variable?
def restart_time(sender):
start = int(time())
button2 = str("Stopwatch restarted.")
sender.title = None
sender.title = str(button2)
ui.load_view('stop_time').present('sheet')
Answer: By default, when you assign to an identifier for the first time in a function
it creates a local variable, even if there's a global one with the same name.
Try this:
def restart_time(sender):
global start
start = int(time())
button2 = str("Stopwatch restarted.")
sender.title = None
sender.title = str(button2)
From [the relevant entry in the Python
FAQ](https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-
local-and-global-variables-in-python):
> In Python, variables that are only referenced inside a function are
> implicitly global. If a variable is assigned a new value anywhere within the
> function’s body, it’s assumed to be a local. If a variable is ever assigned
> a new value inside the function, the variable is implicitly local, and you
> need to explicitly declare it as ‘global’.
|
Extracting text following a specific a-tag
Question: i have a problem extracting text from a html-code with python. The code looks
as followed:
<div class="...">
<br/><a href="link1.html" title="title1">anchor1</a>text1
<br/><a href="link2.html" title="title2">anchor2</a>important text to extract
<br/><a href="link3.html" title="title3">anchor3</a>text3
...
</div>
I want to extract only the text that follows one specific link. I know some
words in the anchor2. Therefor it is not a problem extracting what is
inbetween the a-tags with beautiful soup 4. But after searching around quite a
bit, I found no solution to only extracting the text that follows my important
a-tag.
I hope somebody has an idea.
Answer: Find the link, for example, by title and get the
[`next_sibling`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-
sibling-and-previous-sibling):
from bs4 import BeautifulSoup
data = """
<div class="...">
<br/><a href="link1.html" title="title1">anchor1</a>text1
<br/><a href="link2.html" title="title2">anchor2</a>important text to extract
<br/><a href="link3.html" title="title3">anchor3</a>text3
...
</div>
"""
soup = BeautifulSoup(data)
print soup.find('a', title='title2').next_sibling
Prints:
important text to extract
|
How to add a colorbar properly in python 2.7.2?
Question: I am affraid this sounds like a noobish question, but I am in trouble coding a
colorbar around my figures.
I took some time reading the documentation and these kind of examples :
colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)
and I can not understand what is required to make it work. Mostly I obtain
this error : AttributeError: 'AxesSubplot' object has no attribute
'autoscale_None'
Lets think about details later on. What is the easiet/more simple way to pop a
colorbar along my fig which would auto scale I guess ( if it is the easiet
way). Or maybe should I previously determine the min and max of my values ?
Thanks for your help !
Here is the code (Only the figure 1 matters to me) and I am aware it is poorly
designed. The beginning is here to load data from previous files :
from pylab import *
import matplotlib.animation as animation
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
with load(filename) as data:
XYslice = data['XYslice']
XZslice = data['XZslice']
target = data['target']
Over = data['Over']
wvl=data['wvl']
NA = data['NA']
Dt = data['t']
dz = data['dz']
Ntime,N,Nplans=shape(XZslice)
dxy=wvl/(2.0*NA)/Over
thebigone=max(XYslice[:,N/2,N/2])
XZslice[0,0,0]=thebigone
XYslice[0,0,0]=thebigone
fig=figure(1,figsize=(12,6))
ax1=fig.add_subplot(1,2,1)
xlabel(r"$x (\mu m)$")
ylabel(r"$y (\mu m)$")
ax2=fig.add_subplot(1,2,2)
xlabel(r"$x (\mu m)$")
ylabel(r"$z (\mu m)$")
I=zeros(shape(Dt))
dI=zeros(shape(Dt))
im1=ax1.imshow(XYslice[0,:,:],interpolation='none')#,extent=[-N*dxy/2.0,N*dxy/2.0,-N*dxy/2.0,N*dxy/2.0],cmap='hot')
im2=ax2.imshow(XZslice[0,:,:],interpolation='none')#,extent=[-N*dxy/2.0,N*dxy/2.0,-Nplans*dz/2.0,Nplans*dz/2.0],cmap='hot')
for ii in range(len(Dt)):
zedata=float64(((XYslice[ii,:,:]**2)[where(target==1)]).reshape(-1))
dI[ii]=(sqrt(var(zedata)))
I[ii]=(mean(zedata))
figure(2)
subplot(121)
plot(Dt,array(I),'o',Dt,array(dI))
grid('on')
subplot(122)
#plot(Dt,array(dI)/array(I))
xlabel('Dt ($\mu m^ 2$)')
grid('on')
#
def init():
im1.set_data(XYslice[0,:,:])
im2.set_data(XZslice[0,:,:])
return([im1,im2])
def animate(t):
im1.set_data(XYslice[t,:,:])
im2.set_data(XZslice[t,:,:])
return [im1,im2]
ani = animation.FuncAnimation(fig, animate, np.arange(len(Dt)),interval=250,
blit=True,init_func=init,repeat=True)
show()
Answer: Ok I find out how to do it ... It was really easy. I had to add
`colorbar(im2)` right after the definition of im2 ...
Have a good day !
|
Writing and reading namedtuple into a file in python
Question: I need to write a datastructure stored as namedtuple to file and read it back
as a namedtuple in python.
Solutions here suggest using Json.load/s or pickle which write the variable as
json key-value pair in the form of strings.However, all my field
accesses/dereferences are of the form struct.key and not struct ["key"] which
is the way to access json values.and it is unfeasible to correct this in the
whole code.
I want to store this to a file because the struct is huge and takes a lot of
time to generate.
Answer: Since the standard JSON modules in Python generally use `dict` to work with
JSON objects, you need to convert to and from a `dict`.
For a little setup, let's say I've created this `namedtuple`:
>>> from collections import namedtuple
>>> import json
>>> X = namedtuple('X', ['x', 'y', 'z'])
>>> x = X(1,2,3)
>>> x
X(x=1, y=2, z=3)
1) Use `_asdict()` to convert to a `dict` that you can dump as JSON:
>>> j = json.dumps(x._asdict())
>>> j
'{"x": 1, "y": 2, "z": 3}'
Now you have a JSON representation.
2) To get it back into an object, use `**` to convert a `dict` into keyword
arguments:
>>> x2 = X(**json.loads(j))
>>> x2
X(x=1, y=2, z=3)
Done. You can of course read/write that JSON out to a file any way you wish.
(For example, the JSON modules have methods that work with files directly.)
|
Using Regex to Change Filenames with Python
Question: I'm trying to use change a bunch of filenames using regex groups but can't
seem to get it to work (despite writing what regexr.com tells me should be a
valid regex statement). The 93,000 files I currently have all look something
like this:
Mr. McCONNELL.2012-07-31.2014sep19_at_182325.txt
Mrs. HAGAN.2012-12-06.2014sep19_at_182321.txt
Ms. MURRAY.2012-06-18.2014sep19_at_182246.tx
And I want them to look like this:
20120731McCONNELL2014sep19_at_182325.txt
But every time I run the script below, I get the following error:
Traceback (most recent call last):
File "changefilenames.py", line 11, in <module>
date = m.group(2)
AttributeError: 'NoneType' object has no attribute 'group'
Thanks so much for your help. My apologies if this is a silly question. I'm
just starting with RegEx and Python and can't seem to figure this one out.
import os
import re
from dateutil.parser import parse
for filename in os.listdir("."):
if filename.startswith("Mr."):
m = re.match("Mr.\s(\w*).(\d*-\d*-\d*).(\w*).txt", filename)
date = m.group(2)
name = m.group(1)
timestamp = m.group(3)
dt = parse(date)
new_filename = "{dt.year}{dt.month}{dt.day}".format(dt=dt) + name + timestamp + ".txt"
os.rename(filename, new_filename)
print new_filename
print "All done with the Mr"
if filename.startswith("Mrs."):
m = re.match("Ms.\s(\w*).(\d*-\d*-\d*).(\w*).txt", filename)
date = m.group(2)
name = m.group(1)
timestamp = m.group(3)
dt = parse(date)
new_filename = "{dt.year}{dt.month}{dt.day}".format(dt=dt) + name + timestamp + ".txt"
os.rename(filename, new_filename)
print new_filename
print "All done with the Mrs"
if filename.startswith("Ms."):
m = re.match("Mrs.\s(\w*).(\d*-\d*-\d*).(\w*).txt", filename)
date = m.group(2)
name = m.group(1)
timestamp = m.group(3)
dt = parse(date)
new_filename = "{dt.year}{dt.month}{dt.day}".format(dt=dt) + name + timestamp + ".txt"
os.rename(filename, new_filename)
print new_filename
print "All done with the Mrs"
EDIT I changed the script based on the suggestions below but am still getting
the exact same errors. Here's the new script:
for filename in os.listdir("."):
m = re.search("(Mr|Mrs|Ms)\.\s(\w*)\.(\d*\-\d*\-\d*)\.(\w*)\.txt", filename)
date = m.group(2)
name = m.group(1)
timestamp = m.group(3)
dt = parse(date)
new_filename = "{dt.year}{dt.month}{dt.day}".format(dt=dt) + name + timestamp + ".txt"
os.rename(filename, new_filename)
print new_filename
Answer: You must use `re.search` instead `re.match` , for more detail read [`search()
vs. match()`](https://docs.python.org/2/library/re.html#search-vs-match):
>>> s="Mr. McCONNELL.2012-07-31.2014sep19_at_182325.txt "
>>> import re
>>> m = re.search("Mr.\s(\w*).(\d*-\d*-\d*).(\w*).txt", s)
>>> date = m.group(2)
>>> date
'2012-07-31'
>>> name = m.group(1)
>>> name
'McCONNELL'
>>> timestamp = m.group(3)
>>> timestamp
'2014sep19_at_182325'
|
working with NMEA data sent to URL/IP
Question: i have a bunch of devices that send NMEA sentences to a URL/ip. that look like
this
"$GPGGA,200130.0,3447.854659,N,11014.636735,W,1,11,0.8,41.4,M,-24.0,M,,*53"
i want to read this data in, parse it and upload the key parts to a database.
i know how to parse it and upload it to the DB but i am at a complete loss on
how to "read"/accept/get the data into a python program so that i can parse
and upload.
my first thought was to point it at a Django page and then have Djanog parse
it and upload to the database (data will be accessed from Django site) but its
a NMEA sentence not a HTTP request so Django rejects it as "message Bad
request syntax"
what is the best (python) way to read NMEA sentences sent to a url/IP?
thanks
Answer: I assume you have some hardware that has an ethernet connection, and it pipes
out the NMEA string over its ethernet connection. this probably defaults to
having some random 192.168.0.x ip address and spitting out data over port
12002 or something
you would typically create a socket to listen for this incomming data
**server.py**
import socket
host = "" #Localhost
port = 12002
PACKET_SIZE=1024 # how many characters to read at a time
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((host,port))
sock.listen(5) # we should never have more than one client
def work_thread(client):
while True: #continuously read and handle data
data = client.recv(PACKET_SIZE)
if not data:
break # done with this client
processData(data)
while True:
client,addr = sock.accept() # your script will block here waiting for a connection
t = threading.Thread(target=work_thread,args=(client,))
t.start()
sometimes however you need to ping the device to get the data
**client.py**
import socket
host = "192.168.0.204" #Device IP
port = 12002
PACKET_SIZE=1024 # how many characters to read at a time
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((host,port)) #connect to the device
while True: #continuously read and handle data
data = sock.recv(PACKET_SIZE)
processData(data)
|
Read output and input each line separately - Python/SecureCRT
Question: I am trying to get a Python script to read the output of a command, then to
run multiple commands based on the list it receives. I don't generally write
VBS or Python, so I'm getting stuck. (it's ugly)
def Main():
objTab = crt.GetScriptTab()
objTab.Screen.Synchronous = True
objTab.Screen.IgnoreEscape = True
objTab.Screen.Send("scsi i dev select 1" + chr(13))
objTab.Screen.WaitForString("============")
szPrompt = ">"
szResult = objTab.Screen.ReadString(szPrompt)
crt.Dialog.MessageBox(szResult)
crt.Screen.Send("scsi i gen" + (szResult) + "w 0 100 1 0")
Main()
The input is working (albeit, I wish it would ignore the beginning of the >
text (`sn200028` in this case). It's not important that it does though.

The next 2 parts I am stuck on, namely:
Part 1. How to get it to send the correct output. The correct output should
be:
scsi i gen X w 0 100 1 0
where `X` is one of the numbers in this list.
Part 2. I need it to actually send this command for each item in the list. Not
the whole list as `X`.
Any help is appreciated. Right now we have to copy and paste the lists, then
awk them into another list, which is then cut and pasted. It would be much
more beneficial to just run this from SecureCRT.
Answer: Solved
def Main():
objTab = crt.GetScriptTab()
objTab.Screen.Synchronous = True
objTab.Screen.IgnoreEscape = True
objTab.Screen.Send("scsi i dev select 1" + chr(13))
objTab.Screen.WaitForString("============")
objTab.Screen.Send(chr(13))
szPrompt = "s"
szResult = objTab.Screen.ReadString(szPrompt)
result = crt.Dialog.MessageBox('Press OK to erase the first 100 blocks of the following devices: \n' + (szResult) , 'Run?' , ICON_QUESTION | BUTTON_YESNO | DEFBUTTON2)
if result == IDNO:
return
if result == IDYES:
vList = szResult.splitlines()
for strString in vList:
crt.Dialog.MessageBox('scsi i gen' + (strString) + ' w 0 100 1 0' + chr(13))
Main()
I was able to use str.splitlines in order to split each line then add it to
the messagebox.
|
Python Numpy mask NaN not working
Question: I'm simply trying to use a masked array to filter out some `nan`entries.
import numpy as np
# x = [nan, -0.35, nan]
x = np.ma.masked_equal(x, np.nan)
print x
This outputs the following:
masked_array(data = [ nan -0.33557216 nan],
mask = False,
fill_value = nan)
Calling `np.isnan()` on `x` returns the correct boolean array, but the mask
just doesn't seem to work. Why would my mask not be working as I expect?
Answer: You can use
[`np.ma.masked_invalid`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.masked_invalid.html):
import numpy as np
x = [np.nan, 3.14, np.nan]
mx = np.ma.masked_invalid(x)
print(repr(mx))
# masked_array(data = [-- 3.14 --],
# mask = [ True False True],
# fill_value = 1e+20)
Alternatively, use `np.isnan(x)` as the `mask=` parameter to
`np.ma.masked_array`:
print(repr(np.ma.masked_array(x, np.isnan(x))))
# masked_array(data = [-- 3.14 --],
# mask = [ True False True],
# fill_value = 1e+20)
Why doesn't your original approach work? Because, rather counterintuitively,
`NaN` is not equal to `NaN`!
print(np.nan == np.nan)
# False
This is actually [part of the IEEE-754 definition of
`NaN`](http://stackoverflow.com/a/1573715/1461210)
|
how do i take unlimited sys.argv[] arguments?
Question: To elaborate, I am interested in learning how to code out in python a
sys.argv[] function that allows the user to supply as many arguments as the
user wants. I am unsure on if there is a better way to do this or if it can be
done at all.
The point to this is to develop a similarity tool between text docs of various
size and quantity. the use case in this situation takes as little as argv[1]
and as many as argv[unlimited].
Any input, sources, or advice is welcome.
Answer: `sys.argv` is just a regular Python list, so you can just ask `len(sys.argv)`
for example, or you can just enumerate the contents directly (using a `for ...
in` loop) as with any other iterable.
Note that `sys.argv[0]` is the name of the program, so you need to skip the
first item. (It then follows that `(len(sys.argv) - 1)` is the number of
arguments supplied by the caller.)
import sys
for arg in sys.argv[1:]:
print arg
Example invocation:
$ python test.py a b c
a
b
c
In your case you would replace `print arg` with whatever processing you wanted
to do on the argument.
This will work up to any operating-system-imposed limits. (Some OSes limit the
number of arguments you can pass to a program. For example, on Linux you can
see these limits with `xargs --show-limits`.)
|
Python multiple read on stdin cause it to block
Question: I am a student in programming school and need to complete a project playing
with financial stock's data.
I chose to do it in Python as it's the only language I played few days with
which is not taught in my school, I must be able to read on the standard input
and I am able to it once but not the second time, the program indefinitely
wait and I must stop it using ctrl+c raising an KeyboardInterrupt
Here is the code I get :
#!/usr/bin/python
from __future__ import print_function
import sys
if __name__ == "__main__":
capital = int(sys.stdin.readline())
days = int(sys.stdin.readline())
initial = int(sys.stdin.readline())
for day in range(days - 1):
print("wait")
try:
value = int(sys.stdin.readline())
except ValueError:
break
Here is few hint about the input format I am getting.
First I get three numbers in three different lines at once. Then I get as many
input as the second number of the first input so I am looping on it.
As soon as I reach the
sys.stdin.readline()
in the try/catch the program block and I have actually no idea about why this
is happening.
Answer: Instead of
sys.stdin.readline()
use, in Python 2 (which I imagine you're using given the future-import)
raw_input()
or, in Python 3,
input()
I believe you may be running into buffering problems given your description of
your problems, and the `raw_input` and `input` built-in functions take all the
measures needed to avoid buffering problems, so you don't have to dig in at a
low level to fix things yourself.
|
Python - sum an array imported from a CSV file
Question: I am trying to sum up the values from a csv file after being placed into a
list, i want to add them all together. The list as it goes:
'50', '51', '53', '55', '56', '56', '56', '61', '64', '67', '68', '71', '79', '81', '86', '86', '87', '94', '96', '98', '99' 'Score'
The code gets these values from the csv and places the vales into a list
import csv
f=open('IT_Programming_data.csv')
csv_f = csv.reader(f)
score = []
for row in csv_f:"score"
score.append(row[1])
a = score
b = sum(a)
print (b)
f.close()
When i attempt to sum up the list i get the error:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
sum works when you do:
a = [1,3,4]
b = sum(a)
print (b)
Which returns '8'
How do i make it work with a list imported from the csv, i have no idea
Answer: You try to add a string and a number which will raise a ValueError, try this
code to deal with the Exception:
import csv
f = open('IT_Programming_data.csv')
csv_f = csv.reader(f)
score = []
for row in csv_f:
try:
num = int(row[1].strip()) # try to switch type
score.append(num)
except Exception,error: # fail to switch, print error
print(error)
b = sum(score)
print(b)
f.close()
|
Compiling .pyx to .so using setup.py
Question: I have a module that contains .pyx and their equivalent .cpp.
When I run, `python setup.py develop`, only the `.cpp` files get converted to
`.so`. However, since only the `.pyx` file are readable enough for me to
change them, I would like them to be converted to `.so` instead. This module
is large, so compiling the `.pyx` files individually could be hectic.
Ideally, I would like `python setup.py develop` to convert the `.pyx` files
directly to `.so`.
This is the setup file,
#! /usr/bin/env python
#
# Copyright (C) 2012 Mathieu Blondel
import sys
import os
DISTNAME = 'lightning'
DESCRIPTION = "Large-scale sparse linear classification, " + \
"regression and ranking in Python"
LONG_DESCRIPTION = open('README.rst').read()
MAINTAINER = 'Mathieu Blondel'
MAINTAINER_EMAIL = '[email protected]'
URL = 'https://github.com/mblondel/lightning'
LICENSE = 'new BSD'
DOWNLOAD_URL = 'https://github.com/mblondel/lightning'
VERSION = '0.1-git'
import setuptools # we are using a setuptools namespace
from numpy.distutils.core import setup
def configuration(parent_package='', top_path=None):
if os.path.exists('MANIFEST'):
os.remove('MANIFEST')
from numpy.distutils.misc_util import Configuration
config = Configuration(None, parent_package, top_path)
config.add_subpackage('lightning')
return config
if __name__ == "__main__":
old_path = os.getcwd()
local_path = os.path.dirname(os.path.abspath(sys.argv[0]))
os.chdir(local_path)
sys.path.insert(0, local_path)
setup(configuration=configuration,
name=DISTNAME,
maintainer=MAINTAINER,
include_package_data=True,
scripts=["bin/lightning_train",
"bin/lightning_predict"],
maintainer_email=MAINTAINER_EMAIL,
description=DESCRIPTION,
license=LICENSE,
url=URL,
version=VERSION,
download_url=DOWNLOAD_URL,
long_description=LONG_DESCRIPTION,
zip_safe=False, # the package can run out of an .egg file
classifiers=[
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'License :: OSI Approved',
'Programming Language :: C',
'Programming Language :: Python',
'Topic :: Software Development',
'Topic :: Scientific/Engineering',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Operating System :: Unix',
'Operating System :: MacOS'
]
)
And this is the Make File,
PYTHON ?= python
CYTHON ?= cython
NOSETESTS ?= nosetests
DATADIR=$(HOME)/lightning_data
# Compilation...
CYTHONSRC= $(wildcard lightning/impl/*.pyx lightning/impl/randomkit/*.pyx)
CSRC= $(CYTHONSRC:.pyx=.cpp)
inplace:
$(PYTHON) setup.py build_ext -i
all: cython inplace
cython: $(CSRC)
clean:
rm -f lightning/impl/*.c lightning/impl/*.html
rm -f `find lightning -name "*.pyc"`
rm -f `find lightning -name "*.so"`
%.cpp: %.pyx
$(CYTHON) --cplus $<
# Tests...
#
test-code: in
$(NOSETESTS) -s lightning
test-coverage:
$(NOSETESTS) -s --with-coverage --cover-html --cover-html-dir=coverage \
--cover-package=lightning lightning
test: test-code test-doc
# Datasets...
#
datadir:
mkdir -p $(DATADIR)
# regression
download-abalone: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/abalone_scale
mv abalone_scale $(DATADIR)
download-cadata: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/cadata
mv cadata $(DATADIR)
download-cpusmall: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/cpusmall_scale
mv cpusmall_scale $(DATADIR)
download-space_ga: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/space_ga_scale
mv space_ga_scale $(DATADIR)
download-YearPredictionMSD: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/YearPredictionMSD.bz2
bunzip2 YearPredictionMSD.bz2
mv YearPredictionMSD $(DATADIR)
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/YearPredictionMSD.t.bz2
bunzip2 YearPredictionMSD.t.bz2
mv YearPredictionMSD.t $(DATADIR)
# binary classification
download-adult: datadir
./download.sh http://leon.bottou.org/_media/papers/lasvm-adult.tar.bz2
tar xvfj lasvm-adult.tar.bz2
mv adult $(DATADIR)
rm lasvm-adult.tar.bz2
download-banana: datadir
./download.sh http://leon.bottou.org/_media/papers/lasvm-banana.tar.bz2
tar xvfj lasvm-banana.tar.bz2
mv banana $(DATADIR)
rm lasvm-banana.tar.bz2
download-covtype: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/covtype.libsvm.binary.scale.bz2
bunzip2 covtype.libsvm.binary.scale.bz2
mv covtype.libsvm.binary.scale $(DATADIR)
download-ijcnn: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/ijcnn1.tr.bz2
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/ijcnn1.t.bz2
bunzip2 ijcnn1.tr.bz2
bunzip2 ijcnn1.t.bz2
mv ijcnn1* $(DATADIR)
download-real-sim: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/real-sim.bz2
bunzip2 real-sim.bz2
mv real-sim $(DATADIR)/realsim
download-reuters: datadir
./download.sh http://leon.bottou.org/_media/papers/lasvm-reuters.tar.bz2
tar xvfj lasvm-reuters.tar.bz2
mv reuters $(DATADIR)
rm lasvm-reuters.tar.bz2
download-url: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/url_combined.bz2
bunzip2 url_combined.bz2
mv url_combined $(DATADIR)
download-waveform: datadir
./download.sh http://leon.bottou.org/_media/papers/lasvm-waveform.tar.bz2
tar xvfj lasvm-waveform.tar.bz2
mv waveform $(DATADIR)
rm lasvm-waveform.tar.bz2
download-webspam: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/webspam_wc_normalized_unigram.svm.bz2
bunzip2 webspam_wc_normalized_unigram.svm.bz2
mv webspam_wc_normalized_unigram.svm $(DATADIR)/webspam
# multi-class
download-dna: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/dna.scale.tr
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/dna.scale.t
mv dna* $(DATADIR)
download-letter: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/letter.scale.tr
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/letter.scale.t
mv letter* $(DATADIR)
download-mnist: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/mnist.scale.bz2
bunzip2 mnist.scale.bz2
mv mnist.scale $(DATADIR)
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/mnist.scale.t.bz2
bunzip2 mnist.scale.t.bz2
mv mnist.scale.t $(DATADIR)
download-news20: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/news20.scale.bz2
bunzip2 news20.scale.bz2
mv news20.scale $(DATADIR)
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/news20.t.scale.bz2
bunzip2 news20.t.scale.bz2
mv news20.t.scale $(DATADIR)
download-pendigits: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/pendigits
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/pendigits.t
mv pendigits* $(DATADIR)
download-protein: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/protein.tr.bz2
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/protein.t.bz2
bunzip2 protein.tr.bz2
bunzip2 protein.t.bz2
mv protein* $(DATADIR)
download-rcv1: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/rcv1_train.multiclass.bz2
bunzip2 rcv1_train.multiclass.bz2
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/rcv1_test.multiclass.bz2
bunzip2 rcv1_test.multiclass.bz2
mv rcv1* $(DATADIR)
download-satimage: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/satimage.scale.tr
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/satimage.scale.t
mv satimage* $(DATADIR)
download-sector: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/sector/sector.scale.bz2
bunzip2 sector.scale.bz2
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/sector/sector.t.scale.bz2
bunzip2 sector.t.scale.bz2
mv sector* $(DATADIR)
download-usps: datadir
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/usps.bz2
bunzip2 usps.bz2
mv usps $(DATADIR)
./download.sh http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/usps.t.bz2
bunzip2 usps.t.bz2
mv usps.t $(DATADIR)
And during compilation, I get this output,
compile options: '-I/home/is/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/is/lightning/lightning/impl/randomkit -I/home/is/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/is/anaconda/include/python2.7 -c'
c++: svrg_fast.cpp
I would rather have the setup compile the `.c` code as I can easily convert
`.pyx` to `.c`. Or is it possible to convert .pyx to C++ ?
Thanks in advance!
Answer: Just found a way to do it.
Let's say I am making changes to `file.pyx`, I can compile it to `.cpp` by
running,
`cython --cplus file.pyx`
Then, I simply re-build the module by running,
`sudo python setup.py develop`
Hope this helps!
|
Serial communication with Tkinter
Question: I'm writing some code in Python to make a GUI that controls an electronic
board. I put buttons on the GUI and send commands by clicking on it. This part
works. But I need to receive information that comes from the board to change
some stuff in the GUI. It is this part that I don't succeed to do. I found
some tips in [this
question](http://stackoverflow.com/questions/24618802/interrupting-a-for-loop-
while-receiving-data-from-a-serial-port/28165317#28165317), that allows me to
read the COM port without the GUI. When I try to add a window with an entry
box and refresh it with the incoming values i dont see anything.
Here is my code :
import serial
import threading
from time import sleep
from Tkinter import*
import sys
wind=Tk()
global var
var=StringVar(wind)
var.set("value 1")
entry_COM=Entry(wind,textvariable=var)
entry_COM.place(x=0,y=0,width=100,height=50)
ser = serial.Serial(port='COM1',baudrate=115200,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=0)
global thread
thread= None
stop_task = threading.Event()
def do_task():
global var
var.set("value 2")
for i in xrange(1):
if stop_task.is_set():
break
print(i)
sleep(1)
while True:
byte = ser.read(1) # No need for a loop here, read(1) returns a length 1 string
character = byte # I'm not familiar with the serial module, but I think this isn't needed
if character == 'S':
# We check that we are not executing the task already, and if so we handle it accordingly
if thread:
print('Error: a task is already running!')
continue
# Start the task in a thread
stop_task.clear()
thread = threading.Thread(target=do_task)
thread.start()
elif character == 'K':
print('K received -> BREAK FROM TASK')
if thread:
stop_task.set()
thread = None
elif character == 'E':
ser.close()
print "closed"
try:
wind.destroy()
except:
pass
sys.exit()
wind.mainloop()
When I run it, the window doesn't open but the rest works fine. Do you have
any tips for me?
Answer: Actually I succeeded in doing a script that reads what I send and allow me to
write a chain when I push a button from serial import * from Tkinter import *
class serial_test(object):
def __init__(self):
self.serialPort = "COM1"
self.baudRate = 9600
self.ser = Serial(self.serialPort , self.baudRate, timeout=0, writeTimeout=0) #ensure non-blocking
#make a TkInter Window
self.root = Tk()
self.root.wm_title("Reading Serial")
# make a scrollbar
self.scrollbar = Scrollbar(self.root)
self.scrollbar.pack(side=RIGHT, fill=Y)
# make a text box to put the serial output
self.log = Text ( self.root, width=30, height=30, takefocus=0)
self.log.pack()
# attach text box to scrollbar
self.log.config(yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.log.yview)
#make our own buffer
self.buff=0
self.bou=Button(self.root,text='Valid',command=self.writeSerial)
self.bou.pack()
self.root.after(100, self.readSerial)
self.root.protocol("WM_DELETE_WINDOW", self.Intercept)
self.root.mainloop()
def Intercept(self):
try :
self.ser.close()
except:
pass
self.root.destroy()
def writeSerial(self):
self.ser.write("Testing")
def readSerial(self):
while True:
self.c = self.ser.read() # attempt to read a character from Serial
#was anything read?
if len(self.c) == 0:
break
# get the buffer from outside of this function
self.log.insert(END, self.c)
self.buff=self.buff+1
if self.c == '\r':
for i in range(30-self.buff):
self.log.insert(END, ' ')
self.buff=0
if self.buff==30:
self.buff=0
self.root.after(10, self.readSerial) # check serial again soon
serial_test()
|
Can version control tool deal with rich text document?
Question: Here the "rich text" may be a regular Word document, or a notebook of
Mathematica.
By now, I use git to control my Matlab code and a few python code. But it
looks like the rich text file cannot be control by git.
Is there a solution to accomplish this task?
Thanks a lot!
Answer: To provide a short answer to your question, version control systems can
version virtually any time of file, including rich text documents. Your
ability to effectively inspect the diff depends on the internal representation
of the document in the versioned file.
"Rich Text" documents can be versioned in Git, like any other file. The right
question is probably "how easy is to visually inspect the diff between two
versions".
The answer depends on how the file is encoded and stored. If it's a plain
binary file, such as an executable, then git will be able to store the
different revisions, but the diff view will be meaningless.
In order to take advantage of text diffs, the files must be stored as some
kind of text file. It's important to keep in mind that using a text file
doesn't necessary mean you are limited to provide "Rich Text". After all, the
HTML markup is a good demonstration.
As far as I remember, the latest Office versions adopt a storage format (docx)
that in reality is a Zip package. If you unzip the content, part of the
information are stored in XML files (I may be wrong, it has been a while since
I used one of these files).
|
Plotting second figure with matplotlib while first is still open
Question: K here's a more precise example of what I am trying to do. I am using
WXBuilder for Python as my user interface with multiple plotting functionality
i.e. the user must be able to plot a graph based on their chosen parameters.
After a graph is plotted I want the user to be able to plot a second without
closing the first figure. This is for comparison purposes. Below is an
oversimplified example of what I am looking to do.
import matplotlib as plt
def OnPlotClick1(self, event):
plt.plot(self.DateArray1, self.kVAArray2) plt.show()
def OnPlotClick2(self, event):
plt.plot(self.DateArray1, self.kVAArray2) plt.show()
Now I am assuming my problem is arising due plotting and showing() the graph,
and therefore the program somehow is blocked from functionality until the
first figure or plot window is closed.
I hope this explains my problem better.
Answer: You can also draw 2 or more than 2 plotters in the same figure
import matplotlib.pyplot as plt
def my_plotter(ax, data1, data2, param_dict):
out = ax.plot(data1, data2, **param_dict)
return out
fig, (ax1, ax2) = plt.subplots(1, 2)
#here you put your data
data1=[0,1,2,3,8]
data2=[0,1,2,3,8]
data3=[0,1,2,3,8]
data4=[0,1,2,3,8]
my_plotter(ax1, data1, data2, {'marker':'x'})
my_plotter(ax2, data3, data4, {'marker':'o'})
plt.show()
|
Why aren't my consumers consuming?
Question: **EDIT: I have tracked down the problem to be the part of my program where I
download the Zip file and parse it. If I comment that out and replace it with
a default line, it parses 10,000 times with no problem.**
Not sure how much of this question should be edited to reflect that finding.
I've written a python program which downloads a zip file which contains a
single log file of about 10,000 lines. It then parses this file, line by line,
and puts the data into a database.
Eventually my script will run through 200 servers/zip files and process about
100,000 lines. (Not all servers have the needed file)
However, currently when I run the script with 1 consumer, I only get about 13
lines processed into the database. If I run 2 consumers, I get 24. If I run 10
consumers I get 100, and if I run 20 consumers I get 240.
Sometimes, the result of running the script is "Consumer Finished" with said
number of entries in the database (far short of the 10K-30K I'm expecting) But
other times, I get an error message:
> Traceback (most recent call last): File
> "C:\Python27\lib\multiprocessing\queues.py", line 262, in _feed
> send(obj) IOError: [Errno 232] The pipe is being closed
What can be causing this problem? Attached is a modified version of my code to
remove sensitive data:
import urllib, urlparse
import sys
import os
import datetime
from calculon import Calculon
import random
import pprint
import time
import random
import urllib, urlparse
import traceback
import psycopg2
import psycopg2.extras
from datetime import date, datetime, time, timedelta
import os.path
import requests
import io
import urllib2, cStringIO, zipfile
import re
import httplib
import urlparse
def daterange(start_date, end_date):
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(n)
def producer(args):
print "Producing!"
logdt_start = args["logdt_start"]
logdt_end = args["logdt_end"]
for single_date in daterange(logdt_start, logdt_end):
logdt = single_date + timedelta(days=1)
print "Reading log file..."
for x in range(1,2):
servername = "server-{0}".format("%02d" % (x,))
filename = "zipped_log.log{0}".format(logdt.date().isoformat())
url = "http://url.to.zip.file/{0}/{1}".format(servername, filename)
zip_path = 'path/to/file/within/zip/{0}/{1}'.format(servername, filename)
if httpExists(url):
try:
request = urllib2.urlopen(url)
zipinmemory = cStringIO.StringIO(request.read())
with zipfile.ZipFile(zipinmemory) as archive:
with archive.open(zip_path) as log:
print "File Found! Reading %s..." % filename
for line in log:
args["_queue"].put(line)
print "Queue has approximatly {0} items".format(args["_queue"].qsize())
except:
print "exception could not load %s" % url
traceback.print_exc()
return True
def httpExists(url):
host, path = urlparse.urlsplit(url)[1:3]
found = 0
try:
connection = httplib.HTTPConnection(host) ## Make HTTPConnection Object
connection.request("HEAD", path)
responseOb = connection.getresponse() ## Grab HTTPResponse Object
if responseOb.status == 200:
found = 1
#else:
#print "Status %d %s : %s" % (responseOb.status, responseOb.reason, url)
except Exception, e:
print e.__class__, e, url
return found
def parse_log(line):
if len(line) < 10 or line[0] != '[':
return {}
mod_line = line
mod_line = mod_line.replace(' ', ' ') #whats this for?
query_dict = {}
match = re.search('([\d:\/\s]+)\sUTC', mod_line)
s = match.start()
e = match.end() - 5
query_dict['date_ts'] = datetime.strptime(mod_line[s:e], '%d/%m/%Y %H:%M:%S:%f')
e = e+2
mod_line = mod_line[e:]
match = re.search('(\w+)\sLogger:\s', mod_line)
e = match.end()
query_dict['status'] = match.group(1)
mod_line = mod_line[e:]
for key_value in re.split(',', mod_line):
keypair = re.search('(\w+)=(\w+)', key_value)
key = keypair.group(1)
value = keypair.group(2)
query_dict[key] = value
return query_dict
def consumer(args):
global consumed
consumed += 1
print "Consumed : {0}".format(consumed)
try:
db = args["db"]
cname = args["cname"]
arg_value = args["_value"]
cur = db.cursor()
error_count = 0
if arg_value is None:
print "Consumer Finished!"
return False
line = arg_value
qdict = parse_log(line)
if len(qdict) == 0:
print "No data to consumer %s" % cname
return None
query = """
INSERT INTO my_db(date_ts,
status, cmd, creativeString, environment_id, client_type_id, platform_id, sn_type_id, user_id,
device_id, invoker_sn_id, invoker_type, poster_sn_id, origin, event_type, creative_id, ch,
src, afp, cmp, p1, p2,p3)
VALUES (%(date_ts)s,%(status)s,%(cmd)s,%(creativeString)s,%(environment_id)s,%(client_type_id)s,%(platform_id)s,
%(sn_type_id)s,%(user_id)s,%(device_id)s,%(invoker_sn_id)s,%(invoker_type)s,%(poster_sn_id)s,%(origin)s,
%(event_type)s,%(creative_id)s,%(ch)s, %(src)s, %(afp)s, %(cmp)s,
%(p1)s, %(p2)s, %(p3)s);
"""
try:
cur.execute(cur.mogrify(query, qdict))
db.commit()
global processed
processed += 1
print "processed : {0}".format(processed)
except:
error_count = error_count + 1
print "ERROR in insert {0}".format(error_count)
traceback.print_exc()
print qdict
sys.exit(2)
except:
print "Error in parsing: " + val
tracback.print_exc()
sys.exit(12)
def main():
log_start = datetime(2015,1,19);
log_end = datetime(2015,1,20);
consumer_args_list = []
noOfConsumers = 1;
for x in range(0, noOfConsumers):
print "Creating Consumer {0}".format(x)
print "Connecting to logs db..."
db_name = 'mydb'
connString = "dbname={0} host={1} port={2} user={3} password={4}".format(db_name, 'localhost', 5433, 'postgres', 'pword')
db = psycopg2.connect(connString)
consumer_args = {"cname": "CONSUMER_{0}".format(x), "db":db}
consumer_args_list.append(consumer_args)
calculon = Calculon( producer,
[{"logdt_start": log_start,
"logdt_end": log_end}],
True,
consumer,
consumer_args_list,
True)
result = calculon.start()
consumed = 0
processed = 0
if __name__ == "__main__":
main()
The output looks like this:
> Creating Consumer 0
Connecting to logs db...
Producing!
Reading log file...
File Found! Reading log2015-01-20...
Queue has approximatly 9549 items
Consumed : 1
processed : 1
Consumed : 2
processed : 2
Consumed : 3
processed : 3
Consumed : 4
processed : 4
Consumed : 5
processed : 5
Consumed : 6
processed : 6
Consumed : 7
processed : 7
Consumed : 8
processed : 8
Consumed : 9
processed : 9
Consumed : 10
processed : 10
Consumed : 11
processed : 11
Consumed : 12
processed : 12
Consumed : 13
Traceback (most recent call last):
File "C:\Python27\lib\multiprocessing\queues.py", line 262, in _feed
send(obj)
IOError: [Errno 232] The pipe is being closed
Answer: The error turned out to be a bad line in the input file, which broke the
regular expression.
For example: One of the values of the comma seperated list was: `foobar=2,
foo=Something here, is ,a really, poor value, bar=2`
I was able to fix the problem by adding the following code within the consumer
method:
try:
qdict = parse_adx_client_log(line)
except:
qdict = {}
print "BAD LINE {0}".format(line)
if len(qdict) == 0:
print "No data to consumer %s" % cname
return None
|
ImportError: No module named 'paramiko'
Question: I have done through the other questions online here, and I feel that mine is
different enough to warrant a new question.
So I have a `Centos 6 box`, which is running a small website for me, acts as
an office git server and I am trying to configure `Python3` on it.
So I followed the following [these
steps](https://www.digitalocean.com/community/tutorials/how-to-set-up-
python-2-7-6-and-3-3-3-on-centos-6-4) to set up `python3` on the server.
However it seems that I cannot import paramiko into my script.
I downloaded the paramiko rpm however I get this message:
When I try to import paramiko I get:
[root@GIT Python-3.4.2]# rpm -ivh /usr/lib/Python-3.4.2/Modules/python-paramiko-1.7.5-2.1.el6.noarch.rpm
Preparing... ########################################### [100%]
package python-paramiko-1.7.5-2.1.el6.noarch is already installed
When I run python3 directly:
[root@GIT inserv_health_check]# python3
Python 3.4.2 (default, Jan 21 2015, 06:28:04)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'paramiko'
>>>
I am sure there is a simple solution to this problem perhaps the path is
wrong, or I should have put a symbolic link in somewhere. Any help would be
appreciated :)
Before anyone asks, which python output:
[root@GIT Python-3.4.2]# which python
/usr/bin/python
[root@GIT Python-3.4.2]# which pytho~n3
/usr/bin/which: no pytho~n3 in (/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin)
[root@GIT Python-3.4.2]# which python3
/usr/local/bin/python3
Thanks
Answer: You need to do `pip install paramiko` so that python sees that module. If you
work on a virtual environment, you need to `workon <env_name>` first and then
`pip install` the desired module.
|
IOError: [Errno Input overflowed] -9981
Question: I am trying to execute a PyAudio python capturing program on Rasbian in my
RaspberryPi model B board, but getting error:
Traceback (most recent call last):
File "/home/pi/pythonsound/record.py", line 35, in <module>
data = stream.read(CHUNK)
File "/usr/local/lib/python2.7/dist-packages/pyaudio.py", line 605, in read
return pa.read_stream(self._stream, num_frames)
IOError: [Errno Input overflowed] -9981
There are some other suggestions available but not effective Here is what I've
tried, This is the code
import pyaudio
import wave
import sys
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
This is my USB Audio Card device info,
{'defaultSampleRate': 44100.0,
'defaultLowOutputLatency': 0.011609977324263039,
'defaultLowInputLatency': 0.011609977324263039,
'maxInputChannels': 1L,
'structVersion': 2L,
'hostApi': 0L,
'index': 0,
'defaultHighOutputLatency': 0.046439909297052155,
'maxOutputChannels': 2L,
'name': u
'USB PnP Sound Device: USB Audio (hw:0,0)',
'defaultHighInputLatency': 0.046439909297052155}
can you please guide me resolve this problem?
Answer: After reading different users experience and their of correction with just
changing the value of parameters.
As an expert describe above, the actual reason of
IOError: [Errno Input overflowed] -9981
so I also start increasing the value of CHUNK and at last I also get success
over this error. And now my coding after correction is:
import pyaudio, wave, time, sys
from datetime import datetime
CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
current_time = str(datetime.now()) #"Date/Time for File Name"
current_time = "_".join(current_time.split()).replace(":","-")
current_time = current_time[:-7]
WAVE_OUTPUT_FILENAME = 'Audio_'+current_time+'.wav'
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels = CHANNELS, rate = RATE, input = True, input_device_index = 0, frames_per_buffer = CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
print i
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
|
Graph.get_adjacency() is slow and the output is strange
Question: Consider a graph object G in python-igraph 0.7. If I want the adjacency matrix
A of G, I have to write `A=G.get_adjacency()`, but there are two problems:
1. Even if G is sparse with 3000 nodes, A is generated in a long time on my commercial laptop. Is it possible that the creation of the adjacency matrix is so expensive?
2. The output A is a Matrix object, so if I want to operate with the numpy module on A, I have to convert it first in a list and then in a numpy.matrix. Moreover if A is sparse I need a third conversion in a sparse scipy matrix.
Is there in Igraph any way to obtain a scipy.sparse matrix of a sparse graph
in a reasonable time?
Answer: 1. It does not matter whether the graph is sparse or not because igraph will still create a dense matrix so it's an O(n2) operation. (Technically, the matrix itself is created in the C layer where the initialization of the matrix to all zeroes takes O(n2) and then it is filled with ones in O(m) where n is the number of vertices and m is the number of edges -- but then the matrix is forwarded to the Python layer where it is converted into a Matrix object, and the Python layer has no idea that the matrix is essentially sparse so it takes O(n2) to convert it, On my laptop, creating the adjacency matrix for a graph with 3000 nodes is around 500 msec and I think this is probably normal.
2. Yes, there is a way to create a sparse matrix out of an igraph graph straight away, although it's a bit verbose:
from scipy.sparse import coo_matrix
from numpy import hstack, ones
def graph_to_sparse_matrix(graph):
xs, ys = map(array, zip(*graph.get_edgelist()))
if not graph.is_directed():
xs, ys = hstack((xs, ys)).T, hstack((ys, xs)).T
else:
xs, ys = xs.T, ys.T
return coo_matrix((ones(xs.shape), (xs, ys)))
This version converts the same graph to a SciPy sparse matrix in ~26 msec on
my machine.
|
Python syntax error with If/Else statement
Question: hey I need help with a stupid syntax error using the if and else statement.
GNU nano 2.2.6
#!/usr/bin/python
print 'ACTIVATED'
import RPi.GPIO as GPIO ## Import GPIO library
GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
GPIO.setup(40, GPIO.IN) ## Setup GPIO Pin 40 to OUT
GPIO.input(40) ## Turn on GPIO pin 40
for x in xrange(10):
if: GPIO.input(40)
print ('CHEESE')
else:
GPIO.cleanup()
heres the error:
File "./gid.py", line 12
if: GPIO.input(40)
^
Answer: Your `if` needs to have a conditional
if: GPIO.input(40) # wrong placing of semicolon with missing conditional
it has to be
if GPIO.input(40): # correct usage
as `GPIO.input(40)` returns a boolean
(Apart from that your `print` indent has mismatched)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.