title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Very Simple Program Crashing Python 3.5 and spyder | 39,176,831 | <pre><code>xx = 0
n = 4294967295
while xx <= n:
print("xx = ", xx, bin(xx))
xx += 1
</code></pre>
<p>This results in the following traceback:</p>
<pre><code> File "<ipython-input-2-0c9d04ddbbc6>", line 1, in <module>
runfile('C:/Users/Allen/Documents/Python Scripts/crunchy.py', wdir='C:/Users/Allen/Documents/Python Scripts')
File "C:\Users\Allen\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "C:\Users\Allen\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Allen/Documents/Python Scripts/crunchy.py", line 11, in <module>
print("xx = ", xx, bin(xx))
File "C:\Users\Allen\Anaconda3\lib\site-packages\ipykernel\iostream.py", line 317, in write
self._buffer.write(string)
ValueError: I/O operation on closed file
</code></pre>
| 0 | 2016-08-27T02:16:15Z | 39,176,907 | <p>It seems that you are using ipython. </p>
<p>According to this page: <a href="https://github.com/ipython/ipython/issues/9168" rel="nofollow">https://github.com/ipython/ipython/issues/9168</a></p>
<p>you might run into a know issue and will be fixed in the next release. By the way, that program does not crash when I am running it in terminal.</p>
| 0 | 2016-08-27T02:35:18Z | [
"python",
"anaconda",
"spyder"
] |
How to fix python module import errors in jenkins | 39,176,832 | <p>I am having module import errors in Jenkins despite setting my path and python path based on questions here on stack overflow</p>
<p>I have tried this</p>
<p><a href="http://stackoverflow.com/questions/12995809/jenkins-putting-my-python-module-on-the-pythonpath?rq=1">Jenkins: putting my Python module on the PYTHONPATH</a></p>
<p>and this</p>
<p><a href="http://stackoverflow.com/questions/28532467/python-module-import-failure-in-jenkins?rq=1">Python module import failure in Jenkins</a></p>
<p>This same command runs on my local machine without any import issues but fails on Jenkins</p>
<h3>The command</h3>
<pre><code>#!/bin/bash
export PYTHONPATH=$WORKSPACE:$PYTHONPATH
export PATH=$WORKSPACE:$PATH
export DJANGO_SETTINGS_MODULE=myapp.settings.test
echo "Working directory: "
pwd
echo "path: "
echo $PATH
echo "Python path: "
echo $PYTHONPATH
/home/adminuser/.virtualenvs/myapp/bin/python myapp/manage.py jenkins --project-apps-tests --enable-coverage --settings=myapp.settings.test
</code></pre>
<h3>The build error</h3>
<pre><code>Working directory:
/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace
path:
/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace/myapp/apps/:/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
Python path:
/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace/myapp/apps/:/home/adminuser/.virtualenvs/myapp/bin:/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace:
-------- USING TEST SETTINGS ------
Traceback (most recent call last):
......
File "/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace/myapp/apps/accounts/models.py", line 18, in <module>
from apps.registration.tokens.token import GenerateToken
ImportError: No module named registration.tokens.token
</code></pre>
<h3>My file structure</h3>
<p>overview</p>
<pre><code>myapp/
âââ apps
â  âââ __init__.py
â  âââ accounts
â  âââ registration
âââ myapp
â  âââ __init__.py
â  âââ celery.py
â  âââ settings
â  âââ urls.py
â  âââ wsgi.py
âââ manage.py
</code></pre>
<p>view into the module directories</p>
<pre><code>myapp/apps/registration/tokens
âââ __init__.py
âââ token.py
myapp/apps/accounts/
âââ __init__.py
âââ models.py
</code></pre>
<p>I have tried even appending the workspace directory and the virtualenv path to both PATH and PYTHONPATH, i also even added the module directory to the PATH and PYTHONPATH</p>
<p>I get the same error when i run the command on the server itself. Could this be caused by the fact that my virtualenv was created by admin user, but now Jenkins is trying to use it, But all packages load</p>
<p>How do I fix this import error, any assistance is appreciated</p>
| 0 | 2016-08-27T02:16:35Z | 39,180,676 | <p>So finally figured it out</p>
<p>You need to create the virtual env during the test so this is the final command that works</p>
<pre><code>#!/bin/bash
export WORKSPACE=`pwd`
# Create/Activate virtualenv
virtualenv testenv -p /usr/bin/python3
source testenv/bin/activate
# Install requirements
pip install -r requirements/test.txt
# Run them tests
python myapp/manage.py jenkins --project-apps-tests --enable-coverage --settings=myapp.settings.test
</code></pre>
<p>hope this helps someone who gets stuck like i did</p>
| 0 | 2016-08-27T11:34:41Z | [
"python",
"django",
"jenkins"
] |
Django request.user becomes anonymous after redirect | 39,176,844 | <p>In my Django app I create a User from django.contrib.auth.models, and I am using request.user in multiple view functions without a problem. In one of my view functions I change the user password, save the user, and redirect the client to another view function. Once I try to get the user from the request in that function, the user is Anonymous. After using User.set_password() or redirecting, does it take the user out of the session ?</p>
<p>views.py</p>
<pre><code>from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from .models import Profile
from .forms import ProfileForm, PasswordForm
def sign_in(request):
form = AuthenticationForm()
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
if form.user_cache is not None:
user = form.user_cache
if user.is_active:
login(request, user)
return HttpResponseRedirect(
reverse('home') # TODO: go to profile
)
else:
messages.error(
request,
"That user account has been disabled."
)
else:
messages.error(
request,
"Username or password is incorrect."
)
return render(request, 'accounts/sign_in.html', {'form': form})
def sign_up(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(data=request.POST)
if form.is_valid():
form.save()
user = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1']
)
new_profile = Profile.objects.create(user=user)
login(request, user)
messages.success(
request,
"You're now a user! You've been signed in, too."
)
return HttpResponseRedirect(reverse('home')) # TODO: go to profile
return render(request, 'accounts/sign_up.html', {'form': form})
def sign_out(request):
logout(request)
messages.success(request, "You've been signed out. Come back soon!")
return HttpResponseRedirect(reverse('home'))
def profile(request):
user = request.user
try:
account = Profile.objects.get(user=user)
except Profile.DoesNotExist:
account = None
print(account.first_name)
context = {'account': account}
return render(request, 'accounts/profile.html', context)
def edit(request):
account = Profile.objects.get(user=request.user)
form = ProfileForm(instance=account)
if request.method == 'POST':
account = Profile.objects.get(user=request.user)
form = ProfileForm(request.POST, request.FILES)
if form.is_valid():
account.first_name = form.cleaned_data['first_name']
account.last_name = form.cleaned_data['last_name']
account.email = form.cleaned_data['email']
account.bio = form.cleaned_data['bio']
account.avatar = form.cleaned_data['avatar']
account.year_of_birth = form.cleaned_data['year_of_birth']
account.save()
context = {'account': account}
return HttpResponseRedirect('/accounts/profile')
else:
x =form.errors
context = {'form': form, 'errors': form.errors}
return render(request, 'accounts/edit.html', context)
else:
context = {'form': form}
return render(request, 'accounts/edit.html', context)
def change_password(request):
user = request.user
if request.method == 'POST':
form = PasswordForm(request.POST)
if form.is_valid():
cleaned_data = form.cleaned_data
if not user.check_password(cleaned_data['old_password']):
form.add_error('old_password', 'Old password is incorrect')
context = {'form': form}
return render(request, 'accounts/password.html', context)
try:
user.set_password(cleaned_data['new_password'])
user.save()
return HttpResponseRedirect('/accounts/profile')
except Exception as e:
form = PasswordForm()
context = {'form': form}
return render(request, 'accounts/password.html', context)
else:
form = PasswordForm()
context = {'form': form}
return render(request, 'accounts/password.html', context)
</code></pre>
<p>forms.py</p>
<pre><code>class PasswordForm(forms.Form):
old_password = forms.CharField(max_length=200)
new_password = forms.CharField(max_length=200)
confirm_password = forms.CharField(max_length=200)
def clean(self, *args, **kwargs):
cleaned_data = super(PasswordForm, self).clean()
if 'new_password' in cleaned_data:
new_password = cleaned_data['new_password']
else:
new_password = None
if 'confirm_password' in cleaned_data:
confirm_password = cleaned_data['confirm_password']
else:
confirm_password = None
if confirm_password and new_password:
if new_password != confirm_password:
self.add_error('confirm_password', 'Passwords do not match')
</code></pre>
| 1 | 2016-08-27T02:19:37Z | 39,176,996 | <p>Yes. See the documentation about <a href="https://docs.djangoproject.com/en/dev/topics/auth/default/#session-invalidation-on-password-change" rel="nofollow">session invalidation on password change</a>. To fix it, see this bit in particular:</p>
<blockquote>
<p>The default password change views included with Django, <code>PasswordChangeView</code> and the <code>user_change_password</code> view in the <code>django.contrib.auth</code> admin, update the session with the new password hash so that a user changing their own password won't log themselves out. If you have a custom password change view and wish to have similar behavior, use the <code>update_session_auth_hash()</code> function.</p>
</blockquote>
| 1 | 2016-08-27T02:51:50Z | [
"python",
"django",
"redirect",
"user"
] |
Dataframe for HiveContext in spark is not callable | 39,176,864 | <p>I have the below spark script:</p>
<pre><code>from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext, HiveContext
spark_context = SparkContext(conf=SparkConf())
sqlContext = HiveContext(spark_context)
outputPartition=sqlContext.sql("select * from dm_mmx_merge.PLAN_PARTITION ORDER BY PARTITION,ROW_NUM")
outputPartition.printSchema()
outputPartition.filter(outputPartition("partition")==3).show()
</code></pre>
<p>`</p>
<p>I get the output of schema as"</p>
<pre><code>root
|-- seq: integer (nullable = true)
|-- cpo_cpo_id: long (nullable = true)
|-- mo_sesn_yr_cd: string (nullable = true)
|-- prod_prod_cd: string (nullable = true)
|-- cmo_ctry_nm: string (nullable = true)
|-- cmo_cmo_stat_ind: string (nullable = true)
|-- row_num: integer (nullable = true)
|-- partition: long (nullable = true)
</code></pre>
<p>But i also get the error:
<code>Traceback (most recent call last):
File "hiveSparkTest.py", line 18, in <module>
outputPartition.filter(outputPartition(partition)==3).show()
TypeError: 'DataFrame' object is not callable</code></p>
<p>I need the get the output for each partition value and do transformation. Any help would be highly appreciable.</p>
| -1 | 2016-08-27T02:24:37Z | 39,181,086 | <p>In line </p>
<pre><code> outputPartition.filter(outputPartition(partition)==3).show()
</code></pre>
<p>you are trying to use outputPartition as a method.
Use</p>
<pre><code> outputPartition['partition']
</code></pre>
<p>instead of</p>
<pre><code> outputPartition(partition)
</code></pre>
| 2 | 2016-08-27T12:21:04Z | [
"python",
"apache-spark",
"pyspark"
] |
Uploading contents of Django FileField to a remote server | 39,176,878 | <p>In a Django project of mine, users upload video files. Initially, I was uploading them directly to Azure Blob Storage (equivalent to storing it on Amazon S3). I.e. in models.py I had:</p>
<pre><code>class Video(models.Model):
video_file = models.FileField(upload_to=upload_path, storage=OverwriteStorage())
</code></pre>
<p>Where <code>OverwriteStorage</code> overrides <code>Storage</code> in <code>django.core.files.storage</code>, and essentially uploads the file onto Azure. </p>
<p>Now I need to upload this file to a separate Linux server (not the same one that serves my Django web application). In this separate server, I'll perform some operations on the video file (compression, format change), and then I'll upload it to Azure Storage like before.</p>
<p><strong>My question is:</strong> given my goal, how do I change the way I'm uploading the file in models.py? An illustrative example would be nice. I'm thinking I'll need to change <code>FileField.upload_to</code>, but all the examples I've seen indicate it's only to define a local filesystem path. Moreover, I don't want to let the user upload the content normally and then run a process to upload the file to another server. Doing it directly is my preference. Any ideas?</p>
| 3 | 2016-08-27T02:27:07Z | 39,195,066 | <p>I've solved a similar issue with Amazon's S3, but the concept should be the same.</p>
<p>First, I use <code>django-storages</code>, and by default, upload my media files to S3 (<code>django-storages</code> also supports Azure). Then, my team set up an NFS share mount on our Django web servers from the destination server we occasional need to write user uploads to. Then we simply override <code>django-storages</code> by using "upload_to" to the local path that is a mount from the other server.</p>
<p>This answer has a quick example of how to set up an NFS share from one server on another: <a href="http://superuser.com/questions/300662/how-to-mount-a-folder-from-a-linux-machine-on-another-linux-machine">http://superuser.com/questions/300662/how-to-mount-a-folder-from-a-linux-machine-on-another-linux-machine</a></p>
<p>There are a few ways to skin the cat, but this one seemed easiest to our team. Good luck!</p>
| 1 | 2016-08-28T19:36:50Z | [
"python",
"django",
"file-upload",
"django-models"
] |
how to pivot complex dataframe | 39,176,882 | <p>I have a dataframe shown in below.</p>
<pre><code>df =pd.DataFrame({'ID': [1, 2, 3, 4, 5], 'contract1' :["A", "B", "C", "D", "B"],
'contract2' :["C", "A", np.nan, "A", np.nan],
'contract3' :[np.nan, "C", np.nan, np.nan, np.nan] })
df
ID contract1 contract2 contract3
1 A C nan
2 B A C
3 C nan nan
4 D A nan
5 B nan nan
</code></pre>
<p>I would like the flag result like this;</p>
<pre><code>ID A B C D
1 1 0 1 0
2 1 1 1 0
3 0 0 1 0
4 1 0 0 1
5 0 1 0 0
</code></pre>
<p>This flag table show whether each ID have a each contract.
Maybe pivot is available,but I couldn't handle this kind of complex dataframe...
Can I ask how to transform ?</p>
| 3 | 2016-08-27T02:29:00Z | 39,176,955 | <p>You can melt your original data frame to long format and then use <code>crosstab()</code> on the ID and value column:</p>
<pre><code>import pandas as pd
df1 = df.set_index('ID').stack().rename("Type").reset_index()
pd.crosstab(df1.ID, df1.Type)
# Type A B C D
# ID
# 1 1 0 1 0
# 2 1 1 1 0
# 3 0 0 1 0
# 4 1 0 0 1
# 5 0 1 0 0
</code></pre>
| 0 | 2016-08-27T02:44:13Z | [
"python",
"pandas",
"dataframe"
] |
how to pivot complex dataframe | 39,176,882 | <p>I have a dataframe shown in below.</p>
<pre><code>df =pd.DataFrame({'ID': [1, 2, 3, 4, 5], 'contract1' :["A", "B", "C", "D", "B"],
'contract2' :["C", "A", np.nan, "A", np.nan],
'contract3' :[np.nan, "C", np.nan, np.nan, np.nan] })
df
ID contract1 contract2 contract3
1 A C nan
2 B A C
3 C nan nan
4 D A nan
5 B nan nan
</code></pre>
<p>I would like the flag result like this;</p>
<pre><code>ID A B C D
1 1 0 1 0
2 1 1 1 0
3 0 0 1 0
4 1 0 0 1
5 0 1 0 0
</code></pre>
<p>This flag table show whether each ID have a each contract.
Maybe pivot is available,but I couldn't handle this kind of complex dataframe...
Can I ask how to transform ?</p>
| 3 | 2016-08-27T02:29:00Z | 39,178,599 | <p>We could also do this with <code>melt/pivot_table</code></p>
<pre><code>res = pd.melt(df, id_vars = ['ID'], value_vars = ['contract1',
'contract2', 'contract3']).pivot_table(index = 'ID',
columns = 'value', fill_value = 0, aggfunc=len)
print(res)
# variable
#value A B C D
#ID
#1 1 0 1 0
#2 1 1 1 0
#3 0 0 1 0
#4 1 0 0 1
#5 0 1 0 0
</code></pre>
<h3>data</h3>
<pre><code>import pandas as pd;
import numpy as np;
df =pd.DataFrame({'ID': [1, 2, 3, 4, 5], 'contract1' :["A", "B", "C", "D", "B"],
'contract2' :["C", "A", np.nan, "A", np.nan],
'contract3' :[np.nan, "C", np.nan, np.nan, np.nan] })
df
</code></pre>
| 1 | 2016-08-27T07:26:49Z | [
"python",
"pandas",
"dataframe"
] |
how to pivot complex dataframe | 39,176,882 | <p>I have a dataframe shown in below.</p>
<pre><code>df =pd.DataFrame({'ID': [1, 2, 3, 4, 5], 'contract1' :["A", "B", "C", "D", "B"],
'contract2' :["C", "A", np.nan, "A", np.nan],
'contract3' :[np.nan, "C", np.nan, np.nan, np.nan] })
df
ID contract1 contract2 contract3
1 A C nan
2 B A C
3 C nan nan
4 D A nan
5 B nan nan
</code></pre>
<p>I would like the flag result like this;</p>
<pre><code>ID A B C D
1 1 0 1 0
2 1 1 1 0
3 0 0 1 0
4 1 0 0 1
5 0 1 0 0
</code></pre>
<p>This flag table show whether each ID have a each contract.
Maybe pivot is available,but I couldn't handle this kind of complex dataframe...
Can I ask how to transform ?</p>
| 3 | 2016-08-27T02:29:00Z | 39,179,029 | <p>A Faster implementation would be to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> in conjunction with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html" rel="nofollow"><code>str.get_dummies</code></a> as shown:</p>
<pre><code>pd.melt(df, id_vars=['ID']).set_index('ID')['value'] \
.str.get_dummies() \
.groupby(level=0) \
.agg(np.sum)
A B C D
ID
1 1 0 1 0
2 1 1 1 0
3 0 0 1 0
4 1 0 0 1
5 0 1 0 0
</code></pre>
| 2 | 2016-08-27T08:21:56Z | [
"python",
"pandas",
"dataframe"
] |
How to use Firefox add-on SDK / places/bookmarks API from Python | 39,176,887 | <p>I am looking for a kick-start on how to access Firefox bookmarks, folders and tabs from Python using Firefox SDK.
I already tested accessing places.sqlite through the SQLite3 library, but it can run in read-only mode since Firefox locks the database while in use.</p>
<p>How do I initialize the SDK from Python (3.x but I would be willing to use 2.7 too, in case) and send basic commands like create a folder, create a bookmark or tag it?</p>
<p>As you might have already guessed I am learning and rather inexperienced...
Yet I searched quite a bit without finding anything of value other than this link <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Tech/Places/Manipulating_bookmarks_using_Places" rel="nofollow">Manipulating bookmarks using Places</a> that clearly uses some other language.</p>
| 1 | 2016-08-27T02:29:25Z | 39,193,928 | <p>I have investigated a little further, or better: asked to an experienced friend.</p>
<p>The answer seems to be: you cannot invoke Firefox's SDK from anything different than Javascript. It has no bindings for other languages, also because they could not work in Firefox.</p>
<p>In addition to that the guide I linked might be old, since Firefox has moved onto supporting web extensions. </p>
<p>It looks like I might have to shift my focus back to JS if I want to pursue this project.</p>
| 0 | 2016-08-28T17:24:38Z | [
"python",
"sqlite",
"firefox",
"sdk"
] |
Apache Storm - Error on initialization (Worker) | 39,176,913 | <p>storm-1.0.1</p>
<p>my <strong>storm.yaml</strong>:</p>
<pre><code>storm.zookeper.servers:
- "zookeper"
storm.zookeeper.port: 2181
# nimbus.host: "nimbus"
nimbus.seeds: ["nimbus"]
storm.local.dir: "/var/log/storm"
supervisor.slots.ports:
- 6700
- 6701
- 6702
- 6703
worker.childopts: "-Xmx768m"
nimbus.childopts: "-Xmx512m"
supervisor.childopts: "-Xmx256m"
storm.messaging.transport: "backtype.storm.messaging.netty.Context"
storm.messaging.netty.server_worker_threads: 1
storm.messaging.netty.client_worker_threads: 1
storm.messaging.netty.buffer_size: 5242880
storm.messaging.netty.max_retries: 100
storm.messaging.netty.max_wait_ms: 1000
storm.messaging.netty.min_wait_ms: 100
</code></pre>
<p>in my supervisor logs I see this:</p>
<pre><code>2016-08-26 19:22:28.023 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:28.523 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:28.883 o.a.s.d.supervisor [INFO] Worker Process b4a402ba-458d-4c4e-b167-143bd9134200 exited with code: 13
2016-08-26 19:22:28.956 o.a.s.d.supervisor [INFO] Worker Process c9718f4b-131f-4cfe-bce7-e3e448790a4e exited with code: 13
2016-08-26 19:22:28.966 o.a.s.d.supervisor [INFO] Worker Process d30be8b6-6ed0-496e-9d23-6879df1f1bdd exited with code: 13
2016-08-26 19:22:29.023 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:29.040 o.a.s.d.supervisor [INFO] Worker Process e80983c3-1ec6-4b25-9ef1-f29eb42194ae exited with code: 13
2016-08-26 19:22:29.524 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:30.024 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:30.524 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:31.025 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:31.525 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:32.025 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:32.525 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
</code></pre>
<p>worker logs contain the error:</p>
<p><a href="http://nimbus:8000/log?file=wordcount2-8-1472263925%2F6701%2Fworker.log" rel="nofollow">http://nimbus:8000/log?file=wordcount2-8-1472263925%2F6701%2Fworker.log</a></p>
<pre><code>2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:java.compiler=<NA>
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:os.name=Linux
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:os.arch=amd64
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:os.version=4.6.5-300.fc24.x86_64
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:user.name=dmitry
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:user.home=/home/dmitry
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:user.dir=/var/log/storm/workers/3abac0cb-5981-4a87-9ffb-ed2c8053108b
2016-08-26 19:28:39.017 o.a.s.s.o.a.z.ZooKeeper [INFO] Initiating client connection, connectString=localhost:2181 sessionTimeout=20000 watcher=org.apache.storm.shade.org.apache.curator.ConnectionState@79316f3a
2016-08-26 19:28:39.067 o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error)
2016-08-26 19:28:39.163 o.a.s.s.o.a.z.ClientCnxn [INFO] Socket connection established to localhost/0:0:0:0:0:0:0:1:2181, initiating session
2016-08-26 19:28:39.176 o.a.s.s.o.a.z.ClientCnxn [INFO] Session establishment complete on server localhost/0:0:0:0:0:0:0:1:2181, sessionid = 0x156c953110f00d8, negotiated timeout = 20000
2016-08-26 19:28:39.180 o.a.s.s.o.a.c.f.s.ConnectionStateManager [INFO] State change: CONNECTED
2016-08-26 19:28:39.181 o.a.s.zookeeper [INFO] Zookeeper state update: :connected:none
2016-08-26 19:28:39.191 o.a.s.s.o.a.c.f.i.CuratorFrameworkImpl [INFO] backgroundOperationsLoop exiting
2016-08-26 19:28:39.198 o.a.s.s.o.a.z.ZooKeeper [INFO] Session: 0x156c953110f00d8 closed
2016-08-26 19:28:39.199 o.a.s.s.o.a.z.ClientCnxn [INFO] EventThread shut down
2016-08-26 19:28:39.201 o.a.s.s.o.a.c.f.i.CuratorFrameworkImpl [INFO] Starting
2016-08-26 19:28:39.201 o.a.s.s.o.a.z.ZooKeeper [INFO] Initiating client connection, connectString=localhost:2181/storm sessionTimeout=20000 watcher=org.apache.storm.shade.org.apache.curator.ConnectionState@3dd4a6fa
2016-08-26 19:28:39.212 o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error)
2016-08-26 19:28:39.213 o.a.s.s.o.a.z.ClientCnxn [INFO] Socket connection established to localhost/0:0:0:0:0:0:0:1:2181, initiating session
2016-08-26 19:28:39.220 o.a.s.s.o.a.z.ClientCnxn [INFO] Session establishment complete on server localhost/0:0:0:0:0:0:0:1:2181, sessionid = 0x156c953110f00d9, negotiated timeout = 20000
2016-08-26 19:28:39.220 o.a.s.s.o.a.c.f.s.ConnectionStateManager [INFO] State change: CONNECTED
2016-08-26 19:28:39.250 o.a.s.s.a.AuthUtils [INFO] Got AutoCreds []
2016-08-26 19:28:39.254 o.a.s.d.worker [INFO] Reading Assignments.
2016-08-26 19:28:39.310 o.a.s.m.TransportFactory [INFO] Storm peer transport plugin:backtype.storm.messaging.netty.Context
2016-08-26 19:28:39.311 o.a.s.d.worker [ERROR] Error on initialization of server mk-worker
java.lang.RuntimeException: Fail to construct messaging plugin from plugin backtype.storm.messaging.netty.Context
at org.apache.storm.messaging.TransportFactory.makeContext(TransportFactory.java:53) ~[storm-core-1.0.1.jar:1.0.1]
at org.apache.storm.daemon.worker$worker_data.invoke(worker.clj:266) ~[storm-core-1.0.1.jar:1.0.1]
at org.apache.storm.daemon.worker$fn__8450$exec_fn__2461__auto__$reify__8452.run(worker.clj:611) ~[storm-core-1.0.1.jar:1.0.1]
at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_101]
at javax.security.auth.Subject.doAs(Subject.java:422) ~[?:1.8.0_101]
at org.apache.storm.daemon.worker$fn__8450$exec_fn__2461__auto____8451.invoke(worker.clj:609) ~[storm-core-1.0.1.jar:1.0.1]
at clojure.lang.AFn.applyToHelper(AFn.java:178) ~[clojure-1.7.0.jar:?]
at clojure.lang.AFn.applyTo(AFn.java:144) ~[clojure-1.7.0.jar:?]
at clojure.core$apply.invoke(core.clj:630) ~[clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker$fn__8450$mk_worker__8545.doInvoke(worker.clj:583) [storm-core-1.0.1.jar:1.0.1]
at clojure.lang.RestFn.invoke(RestFn.java:512) [clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker$_main.invoke(worker.clj:771) [storm-core-1.0.1.jar:1.0.1]
at clojure.lang.AFn.applyToHelper(AFn.java:165) [clojure-1.7.0.jar:?]
at clojure.lang.AFn.applyTo(AFn.java:144) [clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker.main(Unknown Source) [storm-core-1.0.1.jar:1.0.1]
Caused by: java.lang.ClassNotFoundException: backtype.storm.messaging.netty.Context
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[?:1.8.0_101]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_101]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[?:1.8.0_101]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_101]
at java.lang.Class.forName0(Native Method) ~[?:1.8.0_101]
at java.lang.Class.forName(Class.java:264) ~[?:1.8.0_101]
at org.apache.storm.messaging.TransportFactory.makeContext(TransportFactory.java:38) ~[storm-core-1.0.1.jar:1.0.1]
... 14 more
2016-08-26 19:28:39.319 o.a.s.util [ERROR] Halting process: ("Error on initialization")
java.lang.RuntimeException: ("Error on initialization")
at org.apache.storm.util$exit_process_BANG_.doInvoke(util.clj:341) [storm-core-1.0.1.jar:1.0.1]
at clojure.lang.RestFn.invoke(RestFn.java:423) [clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker$fn__8450$mk_worker__8545.doInvoke(worker.clj:583) [storm-core-1.0.1.jar:1.0.1]
at clojure.lang.RestFn.invoke(RestFn.java:512) [clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker$_main.invoke(worker.clj:771) [storm-core-1.0.1.jar:1.0.1]
at clojure.lang.AFn.applyToHelper(AFn.java:165) [clojure-1.7.0.jar:?]
at clojure.lang.AFn.applyTo(AFn.java:144) [clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker.main(Unknown Source) [storm-core-1.0.1.jar:1.0.1]
</code></pre>
<p>nimbus is up and running </p>
<pre><code>(petrel) [dmitry:~/Projects/experiments/storm/petrel/chapter3/example1]$ netstat -an | grep 6627
69:tcp6 0 0 :::6627 :::* LISTEN
75:tcp6 0 0 192.168.14.164:48582 192.168.14.164:6627 ESTABLISHED
77:tcp6 0 0 192.168.14.164:49154 192.168.14.164:6627 ESTABLISHED
78:tcp6 0 0 192.168.14.164:48548 192.168.14.164:6627 ESTABLISHED
80:tcp6 0 0 192.168.14.164:6627 192.168.14.164:49154 ESTABLISHED
81:tcp6 0 0 192.168.14.164:48578 192.168.14.164:6627 ESTABLISHED
82:tcp6 0 0 192.168.14.164:6627 192.168.14.164:48064 ESTABLISHED
83:tcp6 0 0 192.168.14.164:6627 192.168.14.164:48484 ESTABLISHED
85:tcp6 0 0 192.168.14.164:48560 192.168.14.164:6627 ESTABLISHED
86:tcp6 0 0 192.168.14.164:49130 192.168.14.164:6627 ESTABLISHED
87:tcp6 0 0 192.168.14.164:6627 192.168.14.164:49380 ESTABLISHED
89:tcp6 0 0 192.168.14.164:6627 192.168.14.164:49148 ESTABLISHED
90:tcp6 0 0 192.168.14.164:48058 192.168.14.164:6627 ESTABLISHED
91:tcp6 0 0 192.168.14.164:49424 192.168.14.164:6627 TIME_WAIT
92:tcp6 0 0 192.168.14.164:6627 192.168.14.164:48034 ESTABLISHED
93:tcp6 0 0 192.168.14.164:6627 192.168.14.164:48498 ESTABLISHED
</code></pre>
| 1 | 2016-08-27T02:35:38Z | 39,182,840 | <p>As the error indicates the class <code>backtype.storm.messaging.netty.Context</code> is not found.</p>
<blockquote>
<p>Caused by: java.lang.ClassNotFoundException: backtype.storm.messaging.netty.Context</p>
</blockquote>
<p>In Storm <code>1.0.0</code> the was a major refactoring renaming many packages. I guess you want to use <code>org.apache.storm.messaging.netty.Context</code> now.</p>
<pre><code>storm.messaging.transport: "org.apache.storm.messaging.netty.Context"
</code></pre>
<p>See <a href="https://storm.apache.org/releases/1.0.0/index.html" rel="nofollow">https://storm.apache.org/releases/1.0.0/index.html</a></p>
| 1 | 2016-08-27T15:35:41Z | [
"java",
"python",
"netty",
"apache-storm"
] |
Apache Storm - Error on initialization (Worker) | 39,176,913 | <p>storm-1.0.1</p>
<p>my <strong>storm.yaml</strong>:</p>
<pre><code>storm.zookeper.servers:
- "zookeper"
storm.zookeeper.port: 2181
# nimbus.host: "nimbus"
nimbus.seeds: ["nimbus"]
storm.local.dir: "/var/log/storm"
supervisor.slots.ports:
- 6700
- 6701
- 6702
- 6703
worker.childopts: "-Xmx768m"
nimbus.childopts: "-Xmx512m"
supervisor.childopts: "-Xmx256m"
storm.messaging.transport: "backtype.storm.messaging.netty.Context"
storm.messaging.netty.server_worker_threads: 1
storm.messaging.netty.client_worker_threads: 1
storm.messaging.netty.buffer_size: 5242880
storm.messaging.netty.max_retries: 100
storm.messaging.netty.max_wait_ms: 1000
storm.messaging.netty.min_wait_ms: 100
</code></pre>
<p>in my supervisor logs I see this:</p>
<pre><code>2016-08-26 19:22:28.023 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:28.523 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:28.883 o.a.s.d.supervisor [INFO] Worker Process b4a402ba-458d-4c4e-b167-143bd9134200 exited with code: 13
2016-08-26 19:22:28.956 o.a.s.d.supervisor [INFO] Worker Process c9718f4b-131f-4cfe-bce7-e3e448790a4e exited with code: 13
2016-08-26 19:22:28.966 o.a.s.d.supervisor [INFO] Worker Process d30be8b6-6ed0-496e-9d23-6879df1f1bdd exited with code: 13
2016-08-26 19:22:29.023 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:29.040 o.a.s.d.supervisor [INFO] Worker Process e80983c3-1ec6-4b25-9ef1-f29eb42194ae exited with code: 13
2016-08-26 19:22:29.524 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:30.024 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:30.524 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:31.025 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:31.525 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:32.025 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
2016-08-26 19:22:32.525 o.a.s.d.supervisor [INFO] e80983c3-1ec6-4b25-9ef1-f29eb42194ae still hasn't started
</code></pre>
<p>worker logs contain the error:</p>
<p><a href="http://nimbus:8000/log?file=wordcount2-8-1472263925%2F6701%2Fworker.log" rel="nofollow">http://nimbus:8000/log?file=wordcount2-8-1472263925%2F6701%2Fworker.log</a></p>
<pre><code>2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:java.compiler=<NA>
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:os.name=Linux
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:os.arch=amd64
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:os.version=4.6.5-300.fc24.x86_64
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:user.name=dmitry
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:user.home=/home/dmitry
2016-08-26 19:28:39.016 o.a.s.s.o.a.z.ZooKeeper [INFO] Client environment:user.dir=/var/log/storm/workers/3abac0cb-5981-4a87-9ffb-ed2c8053108b
2016-08-26 19:28:39.017 o.a.s.s.o.a.z.ZooKeeper [INFO] Initiating client connection, connectString=localhost:2181 sessionTimeout=20000 watcher=org.apache.storm.shade.org.apache.curator.ConnectionState@79316f3a
2016-08-26 19:28:39.067 o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error)
2016-08-26 19:28:39.163 o.a.s.s.o.a.z.ClientCnxn [INFO] Socket connection established to localhost/0:0:0:0:0:0:0:1:2181, initiating session
2016-08-26 19:28:39.176 o.a.s.s.o.a.z.ClientCnxn [INFO] Session establishment complete on server localhost/0:0:0:0:0:0:0:1:2181, sessionid = 0x156c953110f00d8, negotiated timeout = 20000
2016-08-26 19:28:39.180 o.a.s.s.o.a.c.f.s.ConnectionStateManager [INFO] State change: CONNECTED
2016-08-26 19:28:39.181 o.a.s.zookeeper [INFO] Zookeeper state update: :connected:none
2016-08-26 19:28:39.191 o.a.s.s.o.a.c.f.i.CuratorFrameworkImpl [INFO] backgroundOperationsLoop exiting
2016-08-26 19:28:39.198 o.a.s.s.o.a.z.ZooKeeper [INFO] Session: 0x156c953110f00d8 closed
2016-08-26 19:28:39.199 o.a.s.s.o.a.z.ClientCnxn [INFO] EventThread shut down
2016-08-26 19:28:39.201 o.a.s.s.o.a.c.f.i.CuratorFrameworkImpl [INFO] Starting
2016-08-26 19:28:39.201 o.a.s.s.o.a.z.ZooKeeper [INFO] Initiating client connection, connectString=localhost:2181/storm sessionTimeout=20000 watcher=org.apache.storm.shade.org.apache.curator.ConnectionState@3dd4a6fa
2016-08-26 19:28:39.212 o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error)
2016-08-26 19:28:39.213 o.a.s.s.o.a.z.ClientCnxn [INFO] Socket connection established to localhost/0:0:0:0:0:0:0:1:2181, initiating session
2016-08-26 19:28:39.220 o.a.s.s.o.a.z.ClientCnxn [INFO] Session establishment complete on server localhost/0:0:0:0:0:0:0:1:2181, sessionid = 0x156c953110f00d9, negotiated timeout = 20000
2016-08-26 19:28:39.220 o.a.s.s.o.a.c.f.s.ConnectionStateManager [INFO] State change: CONNECTED
2016-08-26 19:28:39.250 o.a.s.s.a.AuthUtils [INFO] Got AutoCreds []
2016-08-26 19:28:39.254 o.a.s.d.worker [INFO] Reading Assignments.
2016-08-26 19:28:39.310 o.a.s.m.TransportFactory [INFO] Storm peer transport plugin:backtype.storm.messaging.netty.Context
2016-08-26 19:28:39.311 o.a.s.d.worker [ERROR] Error on initialization of server mk-worker
java.lang.RuntimeException: Fail to construct messaging plugin from plugin backtype.storm.messaging.netty.Context
at org.apache.storm.messaging.TransportFactory.makeContext(TransportFactory.java:53) ~[storm-core-1.0.1.jar:1.0.1]
at org.apache.storm.daemon.worker$worker_data.invoke(worker.clj:266) ~[storm-core-1.0.1.jar:1.0.1]
at org.apache.storm.daemon.worker$fn__8450$exec_fn__2461__auto__$reify__8452.run(worker.clj:611) ~[storm-core-1.0.1.jar:1.0.1]
at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_101]
at javax.security.auth.Subject.doAs(Subject.java:422) ~[?:1.8.0_101]
at org.apache.storm.daemon.worker$fn__8450$exec_fn__2461__auto____8451.invoke(worker.clj:609) ~[storm-core-1.0.1.jar:1.0.1]
at clojure.lang.AFn.applyToHelper(AFn.java:178) ~[clojure-1.7.0.jar:?]
at clojure.lang.AFn.applyTo(AFn.java:144) ~[clojure-1.7.0.jar:?]
at clojure.core$apply.invoke(core.clj:630) ~[clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker$fn__8450$mk_worker__8545.doInvoke(worker.clj:583) [storm-core-1.0.1.jar:1.0.1]
at clojure.lang.RestFn.invoke(RestFn.java:512) [clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker$_main.invoke(worker.clj:771) [storm-core-1.0.1.jar:1.0.1]
at clojure.lang.AFn.applyToHelper(AFn.java:165) [clojure-1.7.0.jar:?]
at clojure.lang.AFn.applyTo(AFn.java:144) [clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker.main(Unknown Source) [storm-core-1.0.1.jar:1.0.1]
Caused by: java.lang.ClassNotFoundException: backtype.storm.messaging.netty.Context
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[?:1.8.0_101]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_101]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[?:1.8.0_101]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_101]
at java.lang.Class.forName0(Native Method) ~[?:1.8.0_101]
at java.lang.Class.forName(Class.java:264) ~[?:1.8.0_101]
at org.apache.storm.messaging.TransportFactory.makeContext(TransportFactory.java:38) ~[storm-core-1.0.1.jar:1.0.1]
... 14 more
2016-08-26 19:28:39.319 o.a.s.util [ERROR] Halting process: ("Error on initialization")
java.lang.RuntimeException: ("Error on initialization")
at org.apache.storm.util$exit_process_BANG_.doInvoke(util.clj:341) [storm-core-1.0.1.jar:1.0.1]
at clojure.lang.RestFn.invoke(RestFn.java:423) [clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker$fn__8450$mk_worker__8545.doInvoke(worker.clj:583) [storm-core-1.0.1.jar:1.0.1]
at clojure.lang.RestFn.invoke(RestFn.java:512) [clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker$_main.invoke(worker.clj:771) [storm-core-1.0.1.jar:1.0.1]
at clojure.lang.AFn.applyToHelper(AFn.java:165) [clojure-1.7.0.jar:?]
at clojure.lang.AFn.applyTo(AFn.java:144) [clojure-1.7.0.jar:?]
at org.apache.storm.daemon.worker.main(Unknown Source) [storm-core-1.0.1.jar:1.0.1]
</code></pre>
<p>nimbus is up and running </p>
<pre><code>(petrel) [dmitry:~/Projects/experiments/storm/petrel/chapter3/example1]$ netstat -an | grep 6627
69:tcp6 0 0 :::6627 :::* LISTEN
75:tcp6 0 0 192.168.14.164:48582 192.168.14.164:6627 ESTABLISHED
77:tcp6 0 0 192.168.14.164:49154 192.168.14.164:6627 ESTABLISHED
78:tcp6 0 0 192.168.14.164:48548 192.168.14.164:6627 ESTABLISHED
80:tcp6 0 0 192.168.14.164:6627 192.168.14.164:49154 ESTABLISHED
81:tcp6 0 0 192.168.14.164:48578 192.168.14.164:6627 ESTABLISHED
82:tcp6 0 0 192.168.14.164:6627 192.168.14.164:48064 ESTABLISHED
83:tcp6 0 0 192.168.14.164:6627 192.168.14.164:48484 ESTABLISHED
85:tcp6 0 0 192.168.14.164:48560 192.168.14.164:6627 ESTABLISHED
86:tcp6 0 0 192.168.14.164:49130 192.168.14.164:6627 ESTABLISHED
87:tcp6 0 0 192.168.14.164:6627 192.168.14.164:49380 ESTABLISHED
89:tcp6 0 0 192.168.14.164:6627 192.168.14.164:49148 ESTABLISHED
90:tcp6 0 0 192.168.14.164:48058 192.168.14.164:6627 ESTABLISHED
91:tcp6 0 0 192.168.14.164:49424 192.168.14.164:6627 TIME_WAIT
92:tcp6 0 0 192.168.14.164:6627 192.168.14.164:48034 ESTABLISHED
93:tcp6 0 0 192.168.14.164:6627 192.168.14.164:48498 ESTABLISHED
</code></pre>
| 1 | 2016-08-27T02:35:38Z | 39,187,727 | <p>the problem was that my JAVA_HOME env var was pointing to a wrong folder.</p>
<p><strong>before:</strong></p>
<p>JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.101-1.b14.fc24.x86_64/jre/</p>
<p><strong>after</strong>:</p>
<p>JAVA_HOME=/usr/lib/jvm/java-1.8.0-oracle-1.8.0.92.x86_64/</p>
<p>I got recommendation to check that storm is installed properly, by running sample java topology that comes in storm examples.</p>
<p>I followed this official <a href="https://github.com/apache/storm/tree/master/examples/storm-starter" rel="nofollow">tutorial</a>.</p>
<pre><code>cd ~/Development/storm/examples/storm-starter
mvn package
</code></pre>
<p>gave me this:</p>
<pre><code>[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 49.281 s
[INFO] Finished at: 2016-08-27T19:16:54-07:00
[INFO] Final Memory: 21M/391M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project storm-starter: Could not resolve dependencies for project org.apache.storm:storm-starter:jar:1.0.1: Could not find artifact jdk.tools:jdk.tools:jar:1.7 at specified path /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.101-1.b14.fc24.x86_64/jre/../lib/tools.jar -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
(petrel) [dmitry:/storm-starter]$ dnf list installed | grep java
55:abrt-java-connector.x86_64 1.1.0-8.fc24 @koji-override-0
749:java-1.8.0-openjdk.x86_64 1:1.8.0.101-1.b14.fc24 @updates
750:java-1.8.0-openjdk-headless.x86_64 1:1.8.0.101-1.b14.fc24 @updates
751:java-1.8.0-oracle.x86_64 1.8.0.92-1.fc24.R @russianfedora-nonfree
752:java-1.8.0-oracle-devel.x86_64 1.8.0.92-1.fc24.R @russianfedora-nonfree
753:java-1.8.0-oracle-headless.x86_64 1.8.0.92-1.fc24.R @russianfedora-nonfree
754:javapackages-tools.noarch 4.6.0-14.fc24 @koji-override-0
1846:python3-javapackages.noarch 4.6.0-14.fc24 @koji-override-0
2431:tzdata-java.noarch 2016f-1.fc24 @updates
</code></pre>
<p>as soon as I switched JAVA_HOME to <strong>/usr/lib/jvm/java-1.8.0-oracle-1.8.0.92.x86_64/</strong> I was able to compile and submit sample tolology into remote cluster (which is still local install of storm and zookeeper/nimbus/supervisor/ui/logviewer are running locally)</p>
<p>also keep in mind that there is Yahoo article where they recommend 'netty' as transport and provide the following values:</p>
<pre><code>#storm.messaging.transport: "backtype.storm.messaging.netty.Context"
#storm.messaging.netty.server_worker_threads: 1
#storm.messaging.netty.client_worker_threads: 1
#storm.messaging.netty.buffer_size: 5242880
#storm.messaging.netty.max_retries: 100
#storm.messaging.netty.max_wait_ms: 1000
#storm.messaging.netty.min_wait_ms: 100
</code></pre>
<p>this <strong>can</strong> affect your system in a negative way, as storm 1.0+ got changes in structure of their classes. </p>
<p><strong>Classes were repackaged in 1.0.1 to org.apache.storm away from backtype.storm.</strong></p>
| 0 | 2016-08-28T03:18:15Z | [
"java",
"python",
"netty",
"apache-storm"
] |
Formatting output of CSV file in Python | 39,176,935 | <p>I am creating a very rudimentary "Address Book" program in Python. I am grabbing contact data from a CSV file, the contents of which looks like the following example:</p>
<pre><code>Name,Phone,Company,Email
Elon Musk,454-6723,SpaceX,emusk@spacex.com
Larry Page,853-0653,Google,lpage@gmail.com
Tim Cook,133-0419,Apple,tcook@apple.com
Steve Ballmer,456-7893,Developers!,sballmer@bluescreen.com
</code></pre>
<p>I am trying to format the output so that it looks cleaner and more readable, i.e. everything lined up in rows and columns, like this:</p>
<pre><code>Name: Phone: Company: Email:
Elon Musk 454-6723 SpaceX emusk@spacex.com
</code></pre>
<p>My current code is as follows:</p>
<pre><code>f = open("contactlist.csv")
csv_f = csv.reader(f)
for row in csv_f:
print(row)
</code></pre>
<p>Which naturally due to lack of formatting, produces this, which still looks very unclean.</p>
<pre><code>['Name', 'Phone', 'Company', 'Email']
['Elon Musk', '454-6723', 'SpaceX', 'emusk@spacex.com']
['Larry Page', '853-0653', 'Google', 'lpage@gmail.com']
['Tim Cook', '133-0419', 'Apple', 'tcook@apple.com']
['Steve Ballmer', '456-7893', 'Developers!', 'sballmer@bluescreen.com']
</code></pre>
<p>Any tips on how to produce a cleaner output would be greatly appreciated, as I am beginner and I find all of this quite confusing. Many thanks in advance.</p>
| 3 | 2016-08-27T02:40:02Z | 39,177,024 | <p>You could use <code>format</code> to left justify your output. For example,</p>
<pre><code>f = open("contactlist.csv")
csv_f = csv.reader(f)
for row in csv_f:
print('{:<15} {:<15} {:<20} {:<25}'.format(*row))
</code></pre>
<p>Output:</p>
<pre><code>Name Phone Company Email
Elon Musk 454-6723 SpaceX emusk@spacex.com
Larry Page 853-0653 Google lpage@gmail.com
Tim Cook 133-0419 Apple tcook@apple.com
Steve Ballmer 456-7893 Developers! sballmer@bluescreen.com
</code></pre>
<p>You can read more about <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow">format here</a>. The <code><</code> symbol left-aligns the text, and the number specifies the width of the string. Each <code>{}</code> can include a positional argument before the colon <code>:</code> - if they are omitted, the strings will appear in the order of the arguments in the unpacked list <code>row</code>.</p>
| 2 | 2016-08-27T02:56:58Z | [
"python",
"csv",
"format"
] |
Can't find all tables in website | 39,176,936 | <p>I'm trying to get the code for all the tables inside <a href="http://www.pro-football-reference.com/years/1932" rel="nofollow">http://www.pro-football-reference.com/years/1932</a>, but I'm only getting the first table.</p>
<p>I've tried switching the parser to lxml, but it still gives the length value of 1 for total tables.</p>
<p>It also doesn't give the all of the tags such as divs, tds ...etc</p>
<pre><code>from bs4 import BeautifulSoup
import requests
base_url = 'http://www.pro-football-reference.com/years/1932'
url = base_url
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
print len(soup.find_all('table'))
</code></pre>
| 1 | 2016-08-27T02:40:05Z | 39,177,475 | <p>This is because your page render the table by javascript.
So there is 2 ways to do that </p>
<ul>
<li>first one is using a scraping engine with javascript like Selenium.</li>
<li>second one is finding inside the html content and render it yourself.</li>
</ul>
<p>For this code I approach the 2nd one. Found that the table was hidden by <code><--</code> and <code>--></code>.
Just find all those things and replace it.</p>
<pre><code>import re
from bs4 import BeautifulSoup
import requests
base_url = 'http://www.pro-football-reference.com/years/1932/'
url = base_url
r = requests.get(url)
content = re.sub(r'(?m)^\<!--.*\n?', '', r.content)
content = re.sub(r'(?m)^\-->.*\n?', '', content)
soup = BeautifulSoup(content, 'html.parser')
print len(soup.find_all('table'))
for table in soup.find_all('table'):
if table.findParent("table") is None:
print "\n\n", str(table)
</code></pre>
| 1 | 2016-08-27T04:31:48Z | [
"python",
"beautifulsoup"
] |
Python: Function not holding the value of a variable after execution | 39,176,982 | <p>I'm trying to convert a string input (y/n) into an integer (1/0). The function appears to be working, as when the 'convert' function is executed using 'a' as an argument, the argument is printed inside the function, however printing outside the function uses the original value of the variable 'a'. I've tried using return inside the 'convert' function, but this appears to have no affect. </p>
<pre><code>a = input("Are you happy?(y/n)")
def convert(x):
if x == ('y'):
x = 1
if x == ('n'):
x = 0
print (x)
convert(a)
print (a)
>>> Are you happy?(y/n)y
1
y
</code></pre>
| 1 | 2016-08-27T02:49:25Z | 39,177,040 | <p>You never actually change <code>a</code> because you never modify the global one. You pass it into a function, where it's value is copied into a local variable <code>x</code>. You then modify <code>x</code>, but it doesn't affect <code>a</code>. Here's an alternative:</p>
<pre><code>a = input("Are you happy?(y/n)")
def convert(x):
if x == ('y'):
x = 1
if x == ('n'):
x = 0
return x
a = convert(a)
print(a)
>>> Are you happy?(y/n)y
1
</code></pre>
<p>What it's doing is returning the local variable <code>x</code>, which is being manipulated and reassigning it to <code>a</code>, thus giving the desired result</p>
| 0 | 2016-08-27T03:00:13Z | [
"python",
"function",
"python-3.x",
"variables",
"if-statement"
] |
Python: Function not holding the value of a variable after execution | 39,176,982 | <p>I'm trying to convert a string input (y/n) into an integer (1/0). The function appears to be working, as when the 'convert' function is executed using 'a' as an argument, the argument is printed inside the function, however printing outside the function uses the original value of the variable 'a'. I've tried using return inside the 'convert' function, but this appears to have no affect. </p>
<pre><code>a = input("Are you happy?(y/n)")
def convert(x):
if x == ('y'):
x = 1
if x == ('n'):
x = 0
print (x)
convert(a)
print (a)
>>> Are you happy?(y/n)y
1
y
</code></pre>
| 1 | 2016-08-27T02:49:25Z | 39,177,042 | <p>That is because you are not changing <code>a</code> at all. You are simply passing <code>a</code> to the <code>convert</code> method, but this will not actually <em>change</em> what is in <code>a</code>. In order to change <code>a</code>, you need to assign <code>a</code> to the result of what <code>convert</code> will do. Like this:</p>
<pre><code>a = convert(a)
</code></pre>
<p>This is now where you will need that <code>return</code>, since you have to actually return something from the <code>convert</code> method in order to change the value of what <code>a</code> will now hold.</p>
<p>So, taking all that in to account, you will now have: </p>
<pre><code>a = input("Are you happy?(y/n)")
def convert(x):
if x == ('y'):
x = 1
if x == ('n'):
x = 0
print (x)
# add the return here to return the value
return x
# Here you have to assign what the new value of a will be
a = convert(a)
print(a)
</code></pre>
<p>Output:</p>
<pre><code>1
1
</code></pre>
| 3 | 2016-08-27T03:00:42Z | [
"python",
"function",
"python-3.x",
"variables",
"if-statement"
] |
How to pipe data from /dev/ttyUSB0 to a python script | 39,176,985 | <p>I can <code>sudo cat /dev/ttyUSB0</code> and data is flowing in the console.</p>
<p>but I cant figure out how to do this in a python script, to consume the data.</p>
<p>I tried</p>
<pre><code>sudo python test.py < /dev/ttyUSB0
sudo cat /dev/ttyUSB0 | python test.py
</code></pre>
<p>where test.py</p>
<pre><code>import sys
for line in sys.stdin:
print line
</code></pre>
<p>It never prints anything, but if i do ls | python test.py it echos the content of ls fine?</p>
<p>What do i need to do in my test.py to read from /dev/ttyUSB0</p>
<h2>update for comments</h2>
<p>So when i reboot the pi and cat out without running anything other than what shown here:</p>
<pre><code>pi@raspberrypi ~ $ sudo gpsd /dev/ttyUSB0 -F /var/run/gpsd.sock
pi@raspberrypi ~ $ sudo cat /dev/ttyUSB0
$GPGGA,111448.000,5543.1460,N,01229.2541,E,2,08,1.13,19.1,M,41.5,M,0000,0000*5A
$GPGSA,A,3,10,16,18,21,26,20,29,27,,,,,1.42,1.13,0.87*0D
$GPRMC,111448.000,A,5543.1460,N,01229.2541,E,0.37,331.77,270816,,,D*63
$GPVTG,331.77,T,,M,0.37,N,0.68,K,D*33
$GPGGA,111449.000,5543.1462,N,01229.2542,E,2,08,1.13,19.1,M,41.5,M,0000,0000*5A
$GPGSA,A,3,10,16,18,21,26,20,29,27,,,,,1.42,1.13,0.87*0D
$GPRMC,111449.000,A,5543.1462,N,01229.2542,E,0.40,336.35,270816,,,D*62
$GPVTG,336.35,T,,M,0.40,N,0.74,K,D*3F
$GPGGA,111450.000,5543.1463,N,01229.2541,E,2,08,1.13,19.1,M,41.5,M,0000,0000*50
$GPGSA,A,3,10,16,18,21,26,20,29,27,,,,,1.42,1.13,0.87*0D
$GPRMC,111450.000,A,5543.1463,N,01229.2541,E,0.18,42.67,270816,,,D*52
$GPVTG,42.67,T,,M,0.18,N,0.33,K,D*06
$GPGGA,111451.000,5543.1464,N,01229.2542,E,2,08,1.13,19.1,M,41.5,M,0000,0000*55
$GPGSA,A,3,10,16,18,21,26,20,29,27,,,,,1.42,1.13,0.87*0D
$GPGSV,4,1,14,21,66,084,17,16,65,264,18,26,56,199,24,27,41,281,20*74
$GPGSV,4,2,14,20,37,067,14,18,37,138,25,49,26,189,28,10,14,169,21*72
$GPGSV,4,3,14,07,13,335,,29,11,100,16,08,07,282,,13,05,050,*73
$GPGSV,4,4,14,05,04,025,,15,04,080,*72
$GPRMC,111451.000,A,5543.1464,N,01229.2542,E,0.30,7.93,270816,,,D*67
$GPVTG,7.93,T,,M,0.30,N,0.55,K,D*36
</code></pre>
<p>it all looks nice
then running the python script</p>
<pre><code>pi@raspberrypi ~ $ python test.py
Traceback (most recent call last):
File "test.py", line 96, in <module>
run_program()
File "test.py", line 85, in run_program
with serial.Serial('/dev/ttyUSB0',9600) as ser:
File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 260, in __init__
self.open()
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 276, in open
raise SerialException("could not open port %s: %s" % (self._port, msg))
serial.serialutil.SerialException: could not open port /dev/ttyUSB0: [Errno 16] Device or resource busy: '/dev/ttyUSB0'
</code></pre>
<p>fixed by killing gpsd</p>
<pre><code>pi@raspberrypi ~ $ sudo killall gpsd
pi@raspberrypi ~ $ python test.py
</code></pre>
<p>on the server i now receive the data, looking good. (i push over socket instead of the print in answer). </p>
<pre><code>$GPGGA,111838.000,5543.1488,N,01229.2451,E,2,09,0.94,21.8,M,41.5,M,0000,0000*5A
$GPGSA,A,3,29,10,16,18,21,26,20,27,07,,,,1.60,0.94,1.30*09
$GPRMC,111838.000,A,5543.1488,N,01229.2451,E,0.55,102.49,270816,,,D*65
$GPVTG,102.49,T,,M,0.55,N,1.02,K,D*35
$GPGGA,111839.000,5543.1488,N,01229.2454,E,2,09,0.93,21.8,M,41.5,M,0000,0000*59
$GPGSA,A,3,29,10,16,18,21,26,20,27,07,,,,1.22,0.93,0.79*04
$GPRMC,111839.000,A,5543.1488,N,01229.2454,E,0.56,54.80,270816,,,D*55
$GPVTG,54.80,T,,M,0.56,N,1.05,K,D*06
$GPGGA,111840.000,5543.1489,N,01229.2456,E,2,09,0.93,21.8,M,41.5,M,0000,0000*54
$GPGSA,A,3,29,10,16,18,21,26,20,27,07,,,,1.22,0.93,0.79*04
$GPRMC,111840.000,A,5543.1489,N,01229.2456,E,0.43,12.04,270816,,,D*52
$GPVTG,12.04,T,,M,0.43,N,0.80,K,D*00
$GPGGA,111841.000,5543.1490,N,01229.2457,E,2,09,0.94,21.8,M,41.5,M,0000,0000*5B
$GPGSA,A,3,29,10,16,18,21,26,20,27,07,,,,1.60,0.94,1.30*09
$GPGSV,4,1,14,16,65,260,27,21,64,082,17,26,54,198,30,27,43,282,17*7B
$GPGSV,4,2,14,18,39,137,29,20,36,065,18,49,26,189,28,10,15,168,16*74
$GPGSV,4,3,14,07,13,334,16,29,10,101,15,08,08,283,,13,06,049,*73
$GPGSV,4,4,14,15,05,079,,05,02,025,*73
$GPRMC,111841.000,A,5543.1490,N,01229.2457,E,0.24,252.88,270816,,,D*69
$GPVTG,252.88,T,,M,0.24,N,0.44,K,D*3B
$GPGGA,111842.000,5543.1490,N,01229.2456,E,2,09,0.93,21.8,M,41.5,M,0000,0000*5E
$GPGSA,A,3,29,10,16,18,21,26,20,27,07,,,,1.22,0.93,0.79*04
</code></pre>
<p>After exiting the python script <code>sudo cat /dev/ttyUSB0</code> nothing happens anymore.
Is this because I did not close something correct in python?</p>
| 2 | 2016-08-27T02:50:12Z | 39,177,386 | <p>you can read the data from usb port/ serial port in python using <a href="https://pypi.python.org/pypi/pyserial" rel="nofollow">pyserial</a> library</p>
<pre><code>import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
while True:
data = ser.readline()
if data:
print(data)
</code></pre>
<p>you don't need to redirect serial input to python script via pipe.</p>
| 0 | 2016-08-27T04:13:38Z | [
"python",
"serial-port"
] |
max sum of list elements each separated by (at least) k elements | 39,177,120 | <p>given a list of numbers to find the maximum sum of non-adjacent elements with time complexity o(n) and space complexity of o(1), i could use this :</p>
<pre><code>sum1= 0
sum2= list[0]
for i in range(1, len(list)):
num= sum1
sum1= sum2+ list[i]
sum2= max(num, sum2)
print(max(sum2, sum1))
</code></pre>
<p>this code will work only if the k = 1 [ only one element between the summing numbers] how could improve it by changing k value using dynamic programming. where k is the number of elements between the summing numbers.
for example:</p>
<p>list = [5,6,4,1,2] k=1
answer = 11 # 5+4+2</p>
<p>list = [5,6,4,1,2] k=2
answer = 8 # 6+2 </p>
<p>list = [5,3,4,10,2] k=1
answer = 15 # 5+10</p>
| 3 | 2016-08-27T03:18:25Z | 39,177,241 | <p>EDIT:
I had misunderstood the question, if you need to have 'atleast' k elements in between then following is an <code>O(n^2)</code> solution.</p>
<p>If the numbers are non-negative, then the DP recurrence relation is:</p>
<pre><code>DP[i] = max (DP[j] + A[i]) For all j st 0 <= j < i - k
= A[i] otherwise.
</code></pre>
<p>If there are negative numbers in the array as well, then we can use the idea from Kadane's algorithm:</p>
<pre><code>DP[i] = max (DP[j] + A[i]) For all j st 0 <= j < i - k && DP[j] + A[i] > 0
= max(0,A[i]) otherwise.
</code></pre>
| 2 | 2016-08-27T03:40:14Z | [
"python",
"algorithm",
"dynamic-programming"
] |
max sum of list elements each separated by (at least) k elements | 39,177,120 | <p>given a list of numbers to find the maximum sum of non-adjacent elements with time complexity o(n) and space complexity of o(1), i could use this :</p>
<pre><code>sum1= 0
sum2= list[0]
for i in range(1, len(list)):
num= sum1
sum1= sum2+ list[i]
sum2= max(num, sum2)
print(max(sum2, sum1))
</code></pre>
<p>this code will work only if the k = 1 [ only one element between the summing numbers] how could improve it by changing k value using dynamic programming. where k is the number of elements between the summing numbers.
for example:</p>
<p>list = [5,6,4,1,2] k=1
answer = 11 # 5+4+2</p>
<p>list = [5,6,4,1,2] k=2
answer = 8 # 6+2 </p>
<p>list = [5,3,4,10,2] k=1
answer = 15 # 5+10</p>
| 3 | 2016-08-27T03:18:25Z | 39,178,071 | <p>It's possible to solve this with space <em>O(k)</em> and time <em>O(nk)</em>. if <em>k</em> is a constant, this fits the requirements in your question.</p>
<p>The algorithm loops from position <em>k + 1</em> to <em>n</em>. (If the array is shorter than that, it can obviously be solved in <em>O(k)</em>). At each step, it maintains an array <code>best</code> of length <em>k + 1</em>, such that the <em>j</em>th entry of <code>best</code> is the best solution found so far, such that the last element it used is at least <em>j</em> to the left of the current position.</p>
<p>Initializing <code>best</code> is done by setting, for its entry <em>j</em>, the largest non-negative entry in the array in positions <em>1, ..., k + 1 - j</em>. So, for example, <code>best[1]</code> is the largest non-negative entry in positions <em>1, ..., k</em>, and <code>best[k + 1]</code> is 0.</p>
<p>When at position <em>i</em> of the array, element <em>i</em> is used or not. If it is used, the relevant <code>best</code> until now is <code>best[1]</code>, so write <code>u = max(best[1] + a[i], best[1])</code>. If element <em>i</em> is not used, then each "at least" part shifts one, so for <em>j = 2, ..., k + 1</em>, <code>best[j] = max(best[j], best[j - 1])</code>. Finally, set <code>best[1] = u</code>.</p>
<p>At the termination of the algorithm, the solution is the largest item in <code>best</code>.</p>
| 4 | 2016-08-27T06:12:12Z | [
"python",
"algorithm",
"dynamic-programming"
] |
max sum of list elements each separated by (at least) k elements | 39,177,120 | <p>given a list of numbers to find the maximum sum of non-adjacent elements with time complexity o(n) and space complexity of o(1), i could use this :</p>
<pre><code>sum1= 0
sum2= list[0]
for i in range(1, len(list)):
num= sum1
sum1= sum2+ list[i]
sum2= max(num, sum2)
print(max(sum2, sum1))
</code></pre>
<p>this code will work only if the k = 1 [ only one element between the summing numbers] how could improve it by changing k value using dynamic programming. where k is the number of elements between the summing numbers.
for example:</p>
<p>list = [5,6,4,1,2] k=1
answer = 11 # 5+4+2</p>
<p>list = [5,6,4,1,2] k=2
answer = 8 # 6+2 </p>
<p>list = [5,3,4,10,2] k=1
answer = 15 # 5+10</p>
| 3 | 2016-08-27T03:18:25Z | 39,178,108 | <p>Not sure for the complexity but coding efficiency landed me with</p>
<pre><code>max([sum(l[i::j]) for j in range(k,len(l)) for i in range(len(l))])
</code></pre>
<p>(I've replace <code>list</code> variable by <code>l</code> not to step on a keyword).</p>
| 0 | 2016-08-27T06:18:34Z | [
"python",
"algorithm",
"dynamic-programming"
] |
max sum of list elements each separated by (at least) k elements | 39,177,120 | <p>given a list of numbers to find the maximum sum of non-adjacent elements with time complexity o(n) and space complexity of o(1), i could use this :</p>
<pre><code>sum1= 0
sum2= list[0]
for i in range(1, len(list)):
num= sum1
sum1= sum2+ list[i]
sum2= max(num, sum2)
print(max(sum2, sum1))
</code></pre>
<p>this code will work only if the k = 1 [ only one element between the summing numbers] how could improve it by changing k value using dynamic programming. where k is the number of elements between the summing numbers.
for example:</p>
<p>list = [5,6,4,1,2] k=1
answer = 11 # 5+4+2</p>
<p>list = [5,6,4,1,2] k=2
answer = 8 # 6+2 </p>
<p>list = [5,3,4,10,2] k=1
answer = 15 # 5+10</p>
| 3 | 2016-08-27T03:18:25Z | 39,185,319 | <p>Here's a quick implementation of the algorithm described by Ami Tavory (as far as I understand it). It should work for any sequence, though if your list is all negative, the maximum sum will be <code>0</code> (the sum of an empty subsequence).</p>
<pre><code>import collections
def max_sum_separated_by_k(iterable, k):
best = collections.deque([0]*(k+1), k+1)
for item in iterable:
best.appendleft(max(item + best[-1], best[0]))
return best[0]
</code></pre>
<p>This uses <code>O(k)</code> space and <code>O(N)</code> time. All of the <code>deque</code> operations, including appending a value to one end (and implicitly removing one from the other end so the length limit is maintained) and reading from the ends, are <code>O(1)</code>.</p>
<p>If you want the algorithm to return the maximum subsequence (rather than only its sum), you can change the initialization of the <code>deque</code> to start with empty lists rather than <code>0</code>, and then append <code>max([item] + best[-1], best[0], key=sum)</code> in the body of the loop. That will be quite a bit less efficient though, since it adds <code>O(N)</code> operations all over the place.</p>
| 1 | 2016-08-27T20:10:46Z | [
"python",
"algorithm",
"dynamic-programming"
] |
Python Syntax Error: expected an intended block | 39,177,135 | <h1> So first i clicked on Run Module</h1>
<p><a href="http://i.stack.imgur.com/N9BfB.png" rel="nofollow"><img src="http://i.stack.imgur.com/N9BfB.png" alt="So first i clicked on Run Module "></a></p>
<h1>Then this came up</h1>
<p><a href="http://i.stack.imgur.com/Ei0U8.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ei0U8.png" alt="Error Image 2"></a></p>
<p><strong>My code</strong></p>
<pre><code>import time
print("First we need to know you.")
print("Enter your name please.")
time.sleep(2)
name = input("Name: ")
print("Welcome, " + name + "!")
time.sleep(3)
criminal = input("Are you a criminal?: ")
if criminal=='Y':
</code></pre>
<p><strong>Right here it highlights print as red</strong> </p>
<pre><code> print('Oh no')
elif criminal=='N':
print('Thank god!')
</code></pre>
| 1 | 2016-08-27T03:22:50Z | 39,177,147 | <p>You have to indent the <code>print('Oh no')</code>:</p>
<pre><code>if criminal=='Y':
print('Oh no')
elif criminal=='N':
print('Thank god!')
</code></pre>
| 1 | 2016-08-27T03:24:58Z | [
"python",
"syntax-error"
] |
Python Syntax Error: expected an intended block | 39,177,135 | <h1> So first i clicked on Run Module</h1>
<p><a href="http://i.stack.imgur.com/N9BfB.png" rel="nofollow"><img src="http://i.stack.imgur.com/N9BfB.png" alt="So first i clicked on Run Module "></a></p>
<h1>Then this came up</h1>
<p><a href="http://i.stack.imgur.com/Ei0U8.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ei0U8.png" alt="Error Image 2"></a></p>
<p><strong>My code</strong></p>
<pre><code>import time
print("First we need to know you.")
print("Enter your name please.")
time.sleep(2)
name = input("Name: ")
print("Welcome, " + name + "!")
time.sleep(3)
criminal = input("Are you a criminal?: ")
if criminal=='Y':
</code></pre>
<p><strong>Right here it highlights print as red</strong> </p>
<pre><code> print('Oh no')
elif criminal=='N':
print('Thank god!')
</code></pre>
| 1 | 2016-08-27T03:22:50Z | 39,177,152 | <p>You need to indent after an <code>if</code> and the <code>elif</code>:</p>
<pre><code>if criminal=='Y':
print('Oh no')
elif criminal=='N':
print('Thank god!')
</code></pre>
<p>Also, don't indent after the <code>import</code>:</p>
<pre><code>import time
print("First we need to know you.")
</code></pre>
| 3 | 2016-08-27T03:25:24Z | [
"python",
"syntax-error"
] |
using map function to square a list | 39,177,332 | <p>I have a list which I want to square each of them.</p>
<p>this is what I have done</p>
<pre><code>def square(x):
return x*x
numbers = [1,2,3,4,5,6]
squares = map(square, numbers)
squares_as_strings = str(squares)
print(','.join(squares_as_strings))
</code></pre>
<p>but the answer is this</p>
<pre><code>[,1,,, ,4,,, ,9,,, ,1,6,,, ,2,5,,, ,3,6,]
</code></pre>
<p>instead of </p>
<pre><code>[1,4,9,16,25,36]
</code></pre>
| 0 | 2016-08-27T04:03:09Z | 39,177,337 | <p>Just solve it with simple list comprehension.</p>
<pre><code>squares = [i*i for i in numbers]
</code></pre>
<p>Or, using map:</p>
<pre><code>squares = map(lambda x:x*x,numbers)
</code></pre>
| 1 | 2016-08-27T04:04:07Z | [
"python",
"string",
"list"
] |
using map function to square a list | 39,177,332 | <p>I have a list which I want to square each of them.</p>
<p>this is what I have done</p>
<pre><code>def square(x):
return x*x
numbers = [1,2,3,4,5,6]
squares = map(square, numbers)
squares_as_strings = str(squares)
print(','.join(squares_as_strings))
</code></pre>
<p>but the answer is this</p>
<pre><code>[,1,,, ,4,,, ,9,,, ,1,6,,, ,2,5,,, ,3,6,]
</code></pre>
<p>instead of </p>
<pre><code>[1,4,9,16,25,36]
</code></pre>
| 0 | 2016-08-27T04:03:09Z | 39,177,356 | <p>If you want to use the <code>map</code> function, you can use:</p>
<pre><code>squares = list(map(square, numbers))
</code></pre>
<p>The <code>map</code> function will return a <code>map</code> object.</p>
| 0 | 2016-08-27T04:07:50Z | [
"python",
"string",
"list"
] |
using map function to square a list | 39,177,332 | <p>I have a list which I want to square each of them.</p>
<p>this is what I have done</p>
<pre><code>def square(x):
return x*x
numbers = [1,2,3,4,5,6]
squares = map(square, numbers)
squares_as_strings = str(squares)
print(','.join(squares_as_strings))
</code></pre>
<p>but the answer is this</p>
<pre><code>[,1,,, ,4,,, ,9,,, ,1,6,,, ,2,5,,, ,3,6,]
</code></pre>
<p>instead of </p>
<pre><code>[1,4,9,16,25,36]
</code></pre>
| 0 | 2016-08-27T04:03:09Z | 39,177,363 | <p>The problem is in these lines:</p>
<pre><code>squares_as_strings = str(squares)
print(','.join(squares_as_strings))
</code></pre>
<p>Applying <code>str</code> to the <code>squares</code> array does not make each number a string.
Instead it gives this - <code>'[1, 2, 3]'</code>, which is a string, not an array of strings as you want.</p>
<p>Now, you are <code>join</code>-ing it, which results in a comma between each character.</p>
<p>You should instead do:</p>
<pre><code>squares = map(str, map(square, numbers))
</code></pre>
<p>This would make each element of the <code>squares</code> array a string. And then use your join.</p>
<hr>
<pre><code>def square(x):
return x * x
nums = [1, 2, 3]
squares = map(str, map(square, nums))
print(','.join(squares))
</code></pre>
| 1 | 2016-08-27T04:08:59Z | [
"python",
"string",
"list"
] |
using map function to square a list | 39,177,332 | <p>I have a list which I want to square each of them.</p>
<p>this is what I have done</p>
<pre><code>def square(x):
return x*x
numbers = [1,2,3,4,5,6]
squares = map(square, numbers)
squares_as_strings = str(squares)
print(','.join(squares_as_strings))
</code></pre>
<p>but the answer is this</p>
<pre><code>[,1,,, ,4,,, ,9,,, ,1,6,,, ,2,5,,, ,3,6,]
</code></pre>
<p>instead of </p>
<pre><code>[1,4,9,16,25,36]
</code></pre>
| 0 | 2016-08-27T04:03:09Z | 39,177,368 | <pre><code>def square(x):
return x*x
numbers = [1,2,3,4,5,6]
squares = map(square, numbers)
print(str(squares)) #str() in not needed
</code></pre>
| 1 | 2016-08-27T04:10:09Z | [
"python",
"string",
"list"
] |
using map function to square a list | 39,177,332 | <p>I have a list which I want to square each of them.</p>
<p>this is what I have done</p>
<pre><code>def square(x):
return x*x
numbers = [1,2,3,4,5,6]
squares = map(square, numbers)
squares_as_strings = str(squares)
print(','.join(squares_as_strings))
</code></pre>
<p>but the answer is this</p>
<pre><code>[,1,,, ,4,,, ,9,,, ,1,6,,, ,2,5,,, ,3,6,]
</code></pre>
<p>instead of </p>
<pre><code>[1,4,9,16,25,36]
</code></pre>
| 0 | 2016-08-27T04:03:09Z | 39,177,369 | <p>You map the <code>square</code> function, but you're not mapping the <code>str</code> function. Your <code>squares_as_strings</code> is one string, of the entire list.</p>
<p>Change <code>str(squares)</code> to <code>map(str, squares)</code>.</p>
| 1 | 2016-08-27T04:10:10Z | [
"python",
"string",
"list"
] |
using map function to square a list | 39,177,332 | <p>I have a list which I want to square each of them.</p>
<p>this is what I have done</p>
<pre><code>def square(x):
return x*x
numbers = [1,2,3,4,5,6]
squares = map(square, numbers)
squares_as_strings = str(squares)
print(','.join(squares_as_strings))
</code></pre>
<p>but the answer is this</p>
<pre><code>[,1,,, ,4,,, ,9,,, ,1,6,,, ,2,5,,, ,3,6,]
</code></pre>
<p>instead of </p>
<pre><code>[1,4,9,16,25,36]
</code></pre>
| 0 | 2016-08-27T04:03:09Z | 39,177,372 | <p>This is happening because you are calling a <code>join</code> on a string and not on a <code>list</code>. Ultimately, you are not handling the result of your <code>map</code> properly.</p>
<p>If you are using Python 2, your map will give you a list, so simply print out <code>squares</code> and you will have your expected result.</p>
<p>If you are using Python 3, you will actually have a map object, so you will need to call <code>list</code> on it, to obtain a list of your map result: </p>
<pre><code>list(squares)
</code></pre>
| 1 | 2016-08-27T04:10:17Z | [
"python",
"string",
"list"
] |
Python numpy reshape issues | 39,177,438 | <p>I am working with machine learning and numpy and having issues with the <code>np.reshape()</code> function. My data sizes are reading in the variable console as Dataframe(22,5), x(21,4),x_lately(1,4), y(22,). I tried reshaping them with <code>np.reshape(22,5)</code> since that is the dataframe size and it is giving me this error:</p>
<blockquote>
<p>ValueError: total size of new array must be unchanged</p>
</blockquote>
<p>I presume I am either not understanding something or there is something wrong with my system.</p>
<p>Thank you in advance.</p>
| 0 | 2016-08-27T04:23:28Z | 39,177,816 | <p>You really need to describe your data better.</p>
<p>I can imagine the pieces fitting together:</p>
<pre><code>Dataframe(22,5), x(21,4),x_lately(1,4), y(22,)
</code></pre>
<p>The dataframe has 22 rows, 5 columns. <code>y</code> could be one column (22 items). <code>x</code> could be most of the 4 other columns, and <code>x_lately</code> the rest of <code>x</code>.</p>
<p>You don't describe how <code>x</code>,<code>y</code>,<code>x_lately</code> are related to the dataframe, though it looks like they might be arrays extracted from it (either as copies or views). In any case, they cannot be <code>reshaped</code> to match the size of the dataframe. At best they are pieces of the dataframe.</p>
<p><code>reshape</code> isn't a resize or expand or pad or anything like that. You don't even explain why want to reshape anything.</p>
| 0 | 2016-08-27T05:32:17Z | [
"python",
"numpy",
"machine-learning"
] |
Trouble parsing data from website into dictionary: python3 | 39,177,504 | <p>I'm trying to parse data from a stock exhcange website and for example for a particular stock the URL is</p>
<p><a href="https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=SGJHL" rel="nofollow">https://nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=SGJHL</a></p>
<p>and the data I need is under id="responseDiv" (extracted below) and is contained within the subarray "data". While I can get the raw data using beautifulsoup, what is the most efficient way to break this into a key:value dictionary? </p>
<p>I can't use "," since it breaks on numerical values which contain "," as thousand separators.</p>
<p>Many thanks!</p>
<pre><code>{"futLink":"","otherSeries":["EQ"],"lastUpdateTime":"26-AUG-2016 16:00:00","tradedDate":"26AUG2016",**"data":[{"extremeLossMargin":"5.00","cm_ffm":"11.65","bcStartDate":"18-SEP-15","change":"-","buyQuantity3":"-","sellPrice1":"-","buyQuantity4":"-","sellPrice2":"-","priceBand":"20","buyQuantity1":"-","deliveryQuantity":"42,643","buyQuantity2":"-","sellPrice5":"-","quantityTraded":"51,997","buyQuantity5":"-","sellPrice3":"-","sellPrice4":"-","open":"6.00","low52":"5.80","securityVar":"6.41","marketType":"N","pricebandupper":"7.20","totalTradedValue":"3.13","faceValue":"10.00","ndStartDate":"-","previousClose":"6.00","symbol":"SGJHL","varMargin":"25.98","lastPrice":"6.00","pChange":"0.00","adhocMargin":"-","companyName":"SHREE GANESH JEWELLERY HOUSE (I) LIMITED","averagePrice":"6.02","secDate":"26AUG2016","series":"EQ","isinCode":"INE553K01019","indexVar":"15.00","pricebandlower":"4.80","totalBuyQuantity":"-","high52":"13.00","purpose":"ANNUAL GENERAL MEETING","cm_adj_low_dt":"19-AUG-16","closePrice":"6.00","isExDateFlag":false,"recordDate":"-","cm_adj_high_dt":"16-OCT-15","totalSellQuantity":"-","dayHigh":"6.15","exDate":"15-SEP-15","sellQuantity5":"-","bcEndDate":"24-SEP-15","css_status_desc":"Listed","ndEndDate":"-","sellQuantity2":"-","sellQuantity1":"-","buyPrice1":"-","sellQuantity4":"-","buyPrice2":"-","sellQuantity3":"-","applicableMargin":"30.98","buyPrice4":"-","buyPrice3":"-","buyPrice5":"-","dayLow":"5.90","deliveryToTradedQuantity":"82.01","totalTradedVolume":"51,997"}]**,"optLink":""}
</code></pre>
| 0 | 2016-08-27T04:37:07Z | 39,177,978 | <p>It seems that this is a JSON response. You can use JSON library to access to the key values like this :</p>
<pre><code>jsonData = json.load('YOUR RAW DATA')
print (jsonData['bcStartDate'])
</code></pre>
| 0 | 2016-08-27T05:56:05Z | [
"python",
"parsing",
"beautifulsoup"
] |
exception when get a subset of a pandas data frame | 39,177,556 | <p>I want to get the first, 2nd and 4th column of a data frame, which is column <code>c_a,c_b,c_d</code>, what is wrong with my code?</p>
<p>I post my code, data (123.csv) and error message,</p>
<pre><code>sample = pd.read_csv('123.csv', header=None, skiprows=1,
dtype={0:str, 1:str, 2:str, 3:float})
sample.columns = pd.Index(data=['c_a', 'c_b', 'c_c', 'c_d'])
sample['c_d'] = sample['c_d'].astype('int64')
print sample.shape # output (3, 4)
X = sample.iloc[0, 1, 3]
raise IndexingError('Too many indexers')
pandas.core.indexing.IndexingError: Too many indexers
</code></pre>
<p>Content of 123.csv,</p>
<pre><code>c_a,c_b,c_c,c_d
hello,python,pandas,0.0
hi,java,pandas,1.0
ho,c++,numpy,0.0
</code></pre>
| 1 | 2016-08-27T04:45:59Z | 39,177,583 | <p>You need to use <code>df.iloc[:, [0, 1, 3]]</code> instead (or <code>df[[0, 1, 3]]</code>).</p>
<p>Comma separates the row indexer and the column indexer. </p>
| 2 | 2016-08-27T04:50:10Z | [
"python",
"python-2.7",
"pandas",
"numpy",
"dataframe"
] |
exception when get a subset of a pandas data frame | 39,177,556 | <p>I want to get the first, 2nd and 4th column of a data frame, which is column <code>c_a,c_b,c_d</code>, what is wrong with my code?</p>
<p>I post my code, data (123.csv) and error message,</p>
<pre><code>sample = pd.read_csv('123.csv', header=None, skiprows=1,
dtype={0:str, 1:str, 2:str, 3:float})
sample.columns = pd.Index(data=['c_a', 'c_b', 'c_c', 'c_d'])
sample['c_d'] = sample['c_d'].astype('int64')
print sample.shape # output (3, 4)
X = sample.iloc[0, 1, 3]
raise IndexingError('Too many indexers')
pandas.core.indexing.IndexingError: Too many indexers
</code></pre>
<p>Content of 123.csv,</p>
<pre><code>c_a,c_b,c_c,c_d
hello,python,pandas,0.0
hi,java,pandas,1.0
ho,c++,numpy,0.0
</code></pre>
| 1 | 2016-08-27T04:45:59Z | 39,177,594 | <p>Try </p>
<pre><code>X = sample[['c_a', 'c_b', 'c_d']]
</code></pre>
<p>More explicit than using <code>iloc</code>.</p>
| 2 | 2016-08-27T04:52:26Z | [
"python",
"python-2.7",
"pandas",
"numpy",
"dataframe"
] |
Variant Of Two Sum Solution Extremely Slow in Objective C | 39,177,643 | <p>I'm taking an algorithms design and analysis course, and was given programming question which is a variant of the two sum problem:</p>
<p><strong>The input is an array of 1 million integers, both positive and negative.
Compute the number of target values t in the interval [-10000,10000] (inclusive) such that there are distinct numbers x,y in the input file that satisfy x+y=t.</strong></p>
<p>I have written a solution in objective C which solves the problem correctly for smaller test cases:</p>
<pre><code>+ (BOOL)pairExistsForSum:(NSInteger)t dictionary:(NSDictionary *)dictionary
{
__block BOOL exists = NO;
[dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *x, BOOL *stop) {
NSInteger y = t - x.integerValue;
NSString *yKey = [NSString stringWithFormat:@"%li", y];
if (y != x.integerValue && dictionary[yKey]) {
exists = YES;
*stop = YES;
}
}];
return exists;
}
+ (NSInteger)twoSumProblem:(NSArray <NSNumber *> *)array interval:(NSInteger)min max:(NSInteger)max
{
NSDictionary *dictionary = [self generateDictionaryOfValuesWithNumbersArray:array];
NSInteger uniquePairs = 0;
for (NSInteger i = min; i <= max; i++) {
uniquePairs += [self pairExistsForSum:i dictionary:dictionary];
}
return uniquePairs;
}
</code></pre>
<p>The issue is that each iteration of <code>pairExistsForSum</code> takes a little over 2 seconds to complete, meaning this entire process will require hours to complete. </p>
<p><strong>I tried some alternative approaches such as:</strong></p>
<p>1) Sorting the input and dividing it into a positive and negative array and using binary search to find the complimentary addend</p>
<p>2) Changing the outer for loop to only traverse the range 0 - 10000, then searched for the addend for the positive and negative sum value simultaneously</p>
<p>Nothing has improved performance significantly enough, not even breaking this into sub problems and running each on concurrent threads.</p>
<p>I finally found someone's python solution that looks like this:</p>
<pre><code>import time
import bisect
a = []
with open('2sum.txt', 'r') as f:
for line in f:
a.append(int(line.strip()))
a.sort()
ret = set()
for x in a:
lower = bisect.bisect_left(a, -10000 - x)
upper = bisect.bisect_right(a, 10000 - x)
for y in a[lower:upper]:
if x != y and x + y not in ret:
ret.add(x + y)
print len(ret)
</code></pre>
<p>This solution runs in a matter of seconds or less. I'm not familiar with Python, but I believe this is using binary search and is not exploiting the data of the input array to improve speed. Although I would expect python code to run faster than Objective C, the difference between these solutions is vast.</p>
<p><strong>My questions are the following:</strong></p>
<ol>
<li>Is there something I'm missing about the difference between these two solutions that would explain such a vast difference in performance?</li>
<li>Is there something I'm overlooking as far as what I can do to make this run in a respectable amount of time (i.e. under an hour) in Objective c?</li>
</ol>
<p>(Someone asked the same question here: <a href="http://stackoverflow.com/questions/38971693/variant-of-the-2-sum-algorithm-with-a-range-of-sums">Variant of the 2-sum algorithm with a range of sums</a> but there is no answer given, and I believe mine is more specific).</p>
<p>Many thanks.</p>
| 0 | 2016-08-27T05:02:35Z | 39,183,747 | <blockquote>
<p>Is there something I'm missing about the difference between these two solutions that would explain such a vast difference in performance?</p>
</blockquote>
<p>You are solving the problem "backwards". You start with <em>t</em> and then search for a pair which sums to it. Think of the extreme example of your input containing just two numbers, you will perform 200001 tests to see if the sum is one of the possible values in the range [-100000, 100000].</p>
<p>The Python is driven by selecting <em>x</em> and <em>y</em>, so only the actual <em>t</em> values that can be produced by the data are considered. Further by sorting the data the solution is able to consider only those <em>x</em>, <em>y</em> pairs which sum to a value in range.</p>
<blockquote>
<p>Is there something I'm overlooking as far as what I can do to make this run in a respectable amount of time (i.e. under an hour) in Objective c?</p>
</blockquote>
<p>Yes, just implement the same algorithm as the Python solution. A quick Google will produce both the specification of the bisect functions and their Python source. You will find they are trivial binary searches which you can easily implement. However for speed you might wish to try to use a standard Objective-C method. <code>NSArray</code> does not have direct equivalents, but look at <code>indexOfObject:inSortedRange:options:usingComparator:</code> and think a little about "abusing" the comparator's definition of equal values... </p>
<p>HTH</p>
| 2 | 2016-08-27T17:14:55Z | [
"python",
"objective-c",
"algorithm",
"hashtable",
"big-o"
] |
Executing an insert into postgres using psycopg2 | 39,177,660 | <p>I'm trying to insert data using psycopg2 into postgres. Here is the psuedo code I have. It seems to run without error but when I use navicat to check, it doesn't seem to update in the database. I did restart navicat to be sure.</p>
<pre><code>conn = psycopg2.connect("dbname=dbname user=username password = **** host='localhost'")
cur = conn.cursor()
</code></pre>
<p>Here I tried a straight execute and a mogrify.</p>
<pre><code>cur.mogrify("""INSERT INTO database (date, id) VALUES (now(), %s );""" % (user,))
cur.execute
</code></pre>
<p>I also tried this instead of the mogrify</p>
<pre><code>cur.execute("""INSERT INTO database (date, id) VALUES (now(), %s );""" % (user,))
</code></pre>
<p>I can query a select statement but insert doesn't seem to be working.</p>
| 1 | 2016-08-27T05:05:45Z | 39,177,694 | <p>commit the data?</p>
<pre><code>conn.commit()
</code></pre>
| 0 | 2016-08-27T05:12:40Z | [
"python",
"postgresql",
"psycopg2"
] |
My python code is not inserting data into the databse. I have no idea why? | 39,177,697 | <p>My code is just making a database which stores links. But due to some reason when i open the database, it is an empty table. I have no idea why does this happen.</p>
<p>Not Causing any trouble</p>
<pre><code>#!/usr/bin/python
import urllib2
from BeautifulSoup import *
import sqlite3
count = 0
ecount = 0
aj = list()
error = list()
run = 1
</code></pre>
<p>The sql connect</p>
<pre><code>conn = sqlite3.connect('example.db')
cur = conn.cursor()
sql = '''CREATE TABLE URL (LINKS CHAR(512), ID INT(512))'''
cur.execute(sql)
</code></pre>
<p>Not Causing any trouble</p>
<pre><code>def retriver(durl):
newurl = list()
url = durl
notpar = {"#", "None", "NONE", "javascript:void(0)"}
hl = urllib2.urlopen(url, None)
html = hl.read()
hl.close()
soup = BeautifulSoup(html)
tags = soup('a')
</code></pre>
<p>THIS IS THE SCRAPER</p>
<pre><code> for tag in tags:
new = tag.get('href', None)
newurl.append(new)
for i in newurl:
try:
if i[0] == "/" and i[0:3] != "www":
if i[len(a)] == "/":
i = url[0:len(url)-1] + i
else:
i = url + i
if i[0:3] == "www":
i = "/" + i
if "." not in list(i):
continue
if i[0] == "/":
i = i[1:len(i)]
if i[0:4] != "http":
if i[len(i)] != "/":
i = "/" + i
</code></pre>
<p>THIS IS WHERE THE PROBLEM STARTS</p>
<pre><code> if i not in aj:
if i not in notpar:
aj.append(i)
print i
count += 1
sql = '''INSERT INTO URL(LINKS, ID) VALUES (%s, %d)'''
sqldata = (i, count)
cur.execute(sql, sqldata)
conn.commit()
except:
error.append(i)
ecount += 1
global ecount
global count
global aj
u = raw_input('Enter the url :: ')
aj.append(u)
retriver(u)
</code></pre>
<p>Not Causing any trouble</p>
<pre><code>while True:
try:
retriver(aj[run])
run += 1
if run > 20:
break
print run
except:
run += 1
retriver(aj[run])
print run
</code></pre>
| 1 | 2016-08-27T05:13:23Z | 39,177,910 | <p>I think you should not use query like <code>sql = '''INSERT INTO URL(LINKS, ID) VALUES (%s, %d)'''</code></p>
<p>For inserting variables directly in your query use format strings like this :</p>
<pre><code>sql = cur.execute("INSERT INTO URL(LINKS, ID) VALUES (?,?)",(x,y))
</code></pre>
| 0 | 2016-08-27T05:46:06Z | [
"python",
"sql",
"database",
"sqlite"
] |
My python code is not inserting data into the databse. I have no idea why? | 39,177,697 | <p>My code is just making a database which stores links. But due to some reason when i open the database, it is an empty table. I have no idea why does this happen.</p>
<p>Not Causing any trouble</p>
<pre><code>#!/usr/bin/python
import urllib2
from BeautifulSoup import *
import sqlite3
count = 0
ecount = 0
aj = list()
error = list()
run = 1
</code></pre>
<p>The sql connect</p>
<pre><code>conn = sqlite3.connect('example.db')
cur = conn.cursor()
sql = '''CREATE TABLE URL (LINKS CHAR(512), ID INT(512))'''
cur.execute(sql)
</code></pre>
<p>Not Causing any trouble</p>
<pre><code>def retriver(durl):
newurl = list()
url = durl
notpar = {"#", "None", "NONE", "javascript:void(0)"}
hl = urllib2.urlopen(url, None)
html = hl.read()
hl.close()
soup = BeautifulSoup(html)
tags = soup('a')
</code></pre>
<p>THIS IS THE SCRAPER</p>
<pre><code> for tag in tags:
new = tag.get('href', None)
newurl.append(new)
for i in newurl:
try:
if i[0] == "/" and i[0:3] != "www":
if i[len(a)] == "/":
i = url[0:len(url)-1] + i
else:
i = url + i
if i[0:3] == "www":
i = "/" + i
if "." not in list(i):
continue
if i[0] == "/":
i = i[1:len(i)]
if i[0:4] != "http":
if i[len(i)] != "/":
i = "/" + i
</code></pre>
<p>THIS IS WHERE THE PROBLEM STARTS</p>
<pre><code> if i not in aj:
if i not in notpar:
aj.append(i)
print i
count += 1
sql = '''INSERT INTO URL(LINKS, ID) VALUES (%s, %d)'''
sqldata = (i, count)
cur.execute(sql, sqldata)
conn.commit()
except:
error.append(i)
ecount += 1
global ecount
global count
global aj
u = raw_input('Enter the url :: ')
aj.append(u)
retriver(u)
</code></pre>
<p>Not Causing any trouble</p>
<pre><code>while True:
try:
retriver(aj[run])
run += 1
if run > 20:
break
print run
except:
run += 1
retriver(aj[run])
print run
</code></pre>
| 1 | 2016-08-27T05:13:23Z | 39,177,916 | <p>In this line:</p>
<pre><code>sql = '''INSERT INTO URL(LINKS, ID) VALUES (%s, %d)'''
</code></pre>
<p>Try changing it to this:</p>
<pre><code>sql = '''INSERT INTO URL(LINKS, ID) VALUES (?, ?)'''
</code></pre>
<p>This post <a href="http://stackoverflow.com/questions/13613037/is-this-python-code-vulnerable-to-sql-injection-sqlite3">here</a> references that the database's API for parameter substitution uses a <strong>?</strong> rather than the <strong>%s</strong> or <strong>%d</strong> symbol.</p>
| 1 | 2016-08-27T05:46:51Z | [
"python",
"sql",
"database",
"sqlite"
] |
Python - sys.stdout.flush() on 2 lines in python 2.7 | 39,177,788 | <p>I am writing with python 2.7</p>
<p>I have the following code:</p>
<pre><code>a = 0
b = 0
while True:
a += 1
b += 1
print str(a)
print str(b)
</code></pre>
<p>The output looks like:</p>
<pre><code>1
1
2
2
3
3
4
....
</code></pre>
<p>And want to flush these two lines with <code>stdout.flush()</code>. The code looks like this but it's not working..</p>
<pre><code>import sys
a = 0
b = 0
while True:
a += 1
b += 1
sys.stdout.write(str(a)+"\n")
sys.stdout.write(str(b)+"\r")
sys.stdout.flush()
</code></pre>
<p>And this produces an output like this:</p>
<pre><code>1 #1
2 #1 ->#2
3 #2 ->#3
4 #3 ->#4
...
</code></pre>
<p>I know this is because <code>\r</code> only jump to the beginning of the 2nd line, and start from the the next prints..</p>
<p>How can I set the cursor to the beginning of 1st line instead of the 2nd line?</p>
<p>So that it will refresh only 2 lines:</p>
<pre><code>n #1 ->#2 ->#3 ->#4 ->#.....
n #1 ->#2 ->#3 ->#4 ->#.....
</code></pre>
<p>I hope somebody will understand what I mean.</p>
| 0 | 2016-08-27T05:27:10Z | 39,177,802 | <p>to go to the upper line from the current one this has to be written on the stdout <code>\x1b[1A</code></p>
<pre><code>CURSOR_UP_ONE = '\x1b[1A'
</code></pre>
<p>to erase the contents of the line <code>\x1b[2K</code> has to be written on stdout.</p>
<pre><code>ERASE_LINE = '\x1b[2K'
</code></pre>
<p>this way you could go to the upper line and overwrite the data there.</p>
<pre><code>data_on_first_line = CURSOR_UP_ONE + ERASE_LINE + "abc\n"
sys.stdout.write(data_on_first_line)
data_on_second_line = "def\r"
sys.stdout.write(data_on_second_line)
sys.stdout.flush()
</code></pre>
<p>for more details <a href="http://www.termsys.demon.co.uk/vtansi.htm#cursor" rel="nofollow">http://www.termsys.demon.co.uk/vtansi.htm#cursor</a></p>
<p>and <a href="http://stackoverflow.com/a/12586667">http://stackoverflow.com/a/12586667</a></p>
| 3 | 2016-08-27T05:30:30Z | [
"python",
"python-2.7",
"stdout",
"flush",
"sys"
] |
matplotlib.pyplot.plot() doesn't show the graph | 39,177,983 | <p>I am learning Python and I have a side project to learn to display data using matplotlib.pyplot module. Here is an example to display the data using dates[] and prices[] as data. Does anyone know why we need line 5 and line 6? I am confused why this step is needed to have the graph displayed. </p>
<pre><code>from sklearn import linear_model
import matplotlib.pyplot as plt
def showgraph(dates, prices):
dates = numpy.reshape(dates, (len(dates), 1)) # line 5
prices = numpy.reshape(prices, (len(prices), 1)) # line 6
linear_mod = linear_model.LinearRegression()
linear_mod.fit(dates,prices)
plt.scatter(dates,prices,color='yellow')
plt.plot(dates,linear_mod.predict(dates),color='green')
plt.show()
</code></pre>
| 0 | 2016-08-27T05:56:47Z | 39,178,073 | <p>Line 5 and 6 transform what Im assuming are row vectors (im not sure how <code>data</code> and <code>prices</code> are encoded before this transformation) into column vectors. So now you have vectors that look like this. </p>
<pre><code>[0,
1,
2,
3]
</code></pre>
<p>which is the form that <code>linear_model.Linear_Regression.fit()</code> is expecting. The reshaping was not necessary for plotting under the assumption that data and prices are row vectors.</p>
| 0 | 2016-08-27T06:12:24Z | [
"python",
"matplotlib",
"linear-regression"
] |
matplotlib.pyplot.plot() doesn't show the graph | 39,177,983 | <p>I am learning Python and I have a side project to learn to display data using matplotlib.pyplot module. Here is an example to display the data using dates[] and prices[] as data. Does anyone know why we need line 5 and line 6? I am confused why this step is needed to have the graph displayed. </p>
<pre><code>from sklearn import linear_model
import matplotlib.pyplot as plt
def showgraph(dates, prices):
dates = numpy.reshape(dates, (len(dates), 1)) # line 5
prices = numpy.reshape(prices, (len(prices), 1)) # line 6
linear_mod = linear_model.LinearRegression()
linear_mod.fit(dates,prices)
plt.scatter(dates,prices,color='yellow')
plt.plot(dates,linear_mod.predict(dates),color='green')
plt.show()
</code></pre>
| 0 | 2016-08-27T05:56:47Z | 39,178,224 | <p>try the following in terminal to check the backend:</p>
<pre><code>import matplotlib
import matplotlib.pyplot
print matplotlib.backends.backend
</code></pre>
<p>If it shows 'agg', it is a non-interactive one and wont show but plt.savefig works.</p>
<p>To show the plot, you need to switch to TkAgg or Qt4Agg.</p>
<p>You need to edit the backend in matplotlibrc file. To print its location in terminal do the following.</p>
<pre><code>import matplotlib
matplotlib.matplotlib_fname()
</code></pre>
<p>more about <a href="http://matplotlib.org/users/customizing.html#the-matplotlibrc-file" rel="nofollow">matplotlibrc</a></p>
| 1 | 2016-08-27T06:35:48Z | [
"python",
"matplotlib",
"linear-regression"
] |
matplotlib.pyplot.plot() doesn't show the graph | 39,177,983 | <p>I am learning Python and I have a side project to learn to display data using matplotlib.pyplot module. Here is an example to display the data using dates[] and prices[] as data. Does anyone know why we need line 5 and line 6? I am confused why this step is needed to have the graph displayed. </p>
<pre><code>from sklearn import linear_model
import matplotlib.pyplot as plt
def showgraph(dates, prices):
dates = numpy.reshape(dates, (len(dates), 1)) # line 5
prices = numpy.reshape(prices, (len(prices), 1)) # line 6
linear_mod = linear_model.LinearRegression()
linear_mod.fit(dates,prices)
plt.scatter(dates,prices,color='yellow')
plt.plot(dates,linear_mod.predict(dates),color='green')
plt.show()
</code></pre>
| 0 | 2016-08-27T05:56:47Z | 39,178,627 | <p>My approach is exactly like yours but still without line 5 and 6 display is correct. I think those line are unnecessary. It seems that you do not need fit() function because of your input data are in row format.</p>
| 0 | 2016-08-27T07:30:43Z | [
"python",
"matplotlib",
"linear-regression"
] |
Interpolate a discrete grid of dots | 39,178,021 | <p>I'm referencing <a href="http://stackoverflow.com/questions/5146025/python-scipy-2d-interpolation-non-uniform-data">this question</a> and <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.griddata.html" rel="nofollow">this documentation</a> in trying to turn a set of points (the purple dots in the image below) into an interpolated grid.</p>
<p><a href="http://i.stack.imgur.com/Qv412.png" rel="nofollow"><img src="http://i.stack.imgur.com/Qv412.png" alt="enter image description here"></a></p>
<p>As you can see, the image has missing spots where dots <em>should</em> be. I'd like to figure out where those are.</p>
<pre><code>import numpy as np
from scipy import interpolate
CIRCLES_X = 25 # There should be 25 circles going across
CIRCLES_Y = 10 # There should be 10 circles going down
points = []
values = []
# Points range from 0-800 ish X, 0-300 ish Y
for point in points:
points.append([points.x, points.y])
values.append(1) # Not sure what this should be
grid_x, grid_y = np.mgrid[0:CIRCLES_Y, 0:CIRCLES_X]
grid = interpolate.griddata(points, values, (grid_x, grid_y), method='linear')
print(grid)
</code></pre>
<p>Whenever I print out the result of the grid, I get <code>nan</code> for all of my values.</p>
<p>Where am I going wrong? Is my problem even the correct use case for <code>interpolate.grid</code>?</p>
| 0 | 2016-08-27T06:05:08Z | 39,181,082 | <p>First, your uncertain points are mainly at an edge, so it's actually <a href="http://stackoverflow.com/questions/2745329/how-to-make-scipy-interpolate-give-an-extrapolated-result-beyond-the-input-range">extrapolation</a>. Second, interpolation methods built into <code>scipy</code> deal with continuous functions defined on the entire plane and approximate it as a polynomial. While yours is discrete (1 or 0), somewhat periodic rather than polynomial and only defined in a discrete "grid" of points.</p>
<p><strong>So you have to invent some algorithm to inter/extrapolate your specific kind of function. Whether you'll be able to reuse an existing one - from <code>scipy</code> or elsewhere - is up to you.</strong></p>
<ul>
<li><p>One possible way is to <em>replace</em> it with some function (continuous or not) defined everywhere, then calculate that approximation in the missing points - whether as one step as <code>scipy.interpolate</code> non-class functions do or as two separate steps.</p>
<ul>
<li><p>e.g. you can use a 3-D parabola with peaks in your dots and troughs exactly between them. Or just with ones in the dots and 0's in the blanks and hope the resulting approximation in the grid's points is good enough to give a meaningful result (random overswings are likely). Then you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html#scipy.interpolate.RegularGridInterpolator" rel="nofollow"><code>scipy.interpolate.RegularGridInterpolator</code></a> for both inter- and extrapolation.</p></li>
<li><p>or as a harmonic function - then what you're seeking is <a href="http://docs.scipy.org/doc/scipy/reference/fftpack.html" rel="nofollow">Fourier transformation</a></p></li>
</ul></li>
<li><p>Another possible way is to go straight for a discrete solution rather than try to shoehorn the continual mathanalysis' methods into your case: design a (probably entirely custom) algorithm that'll try to figure out the "shape" and "dimensions" of your "grids of dots" and then simply fill in the blanks. I'm not sure if it is possible to add it into the <code>scipy.interpolate</code>'s harness as a selectable algorithm in addition to the built-in ones.</p></li>
</ul>
<p>And last but not the least. <strong>You didn't specify whether the "missing" points are points where the value is unknown or are actual part of the data - i.e. are incorrect data.</strong> If it's the latter, simple interpolation is not applicable at all as it assumes that all the data are strictly correct. Then it's a related but different problem: you can approximate the data but then have to somehow "throw away irregularities" (higher order of smallness entities after some point).</p>
| 1 | 2016-08-27T12:20:21Z | [
"python",
"numpy",
"scipy",
"interpolation"
] |
Python - removing some punctuation from text | 39,178,054 | <p>I want Python to remove only some punctuation from a string, let's say I want to remove all the punctuation except '@'</p>
<pre><code>import string
remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))
sample = 'The quick brown fox, like, totally jumped, @man!'
sample.translate(remove)
</code></pre>
<p>Here the output is </p>
<pre><code>The quick brown fox like totally jumped man
</code></pre>
<p>But what I want is something like this </p>
<pre><code>The quick brown fox like totally jumped @man
</code></pre>
<p>Is there a way to selectively remove punctuation from a text leaving out the punctuation that we want in the text intact?</p>
| 1 | 2016-08-27T06:09:21Z | 39,178,095 | <p><a href="https://docs.python.org/2/library/string.html#string.punctuation" rel="nofollow">str.punctuation</a> contains all the punctuations. Remove <code>@</code> from it. Then replace with <code>''</code> whenever you get that punctuation string. </p>
<pre><code>>>> import re
>>> a = string.punctuation.replace('@','')
>>> re.sub(r'[{}]'.format(a),'','The quick brown fox, like, totally jumped, @man!')
'The quick brown fox like totally jumped @man'
</code></pre>
| 2 | 2016-08-27T06:16:11Z | [
"python"
] |
Python - removing some punctuation from text | 39,178,054 | <p>I want Python to remove only some punctuation from a string, let's say I want to remove all the punctuation except '@'</p>
<pre><code>import string
remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))
sample = 'The quick brown fox, like, totally jumped, @man!'
sample.translate(remove)
</code></pre>
<p>Here the output is </p>
<pre><code>The quick brown fox like totally jumped man
</code></pre>
<p>But what I want is something like this </p>
<pre><code>The quick brown fox like totally jumped @man
</code></pre>
<p>Is there a way to selectively remove punctuation from a text leaving out the punctuation that we want in the text intact?</p>
| 1 | 2016-08-27T06:09:21Z | 39,178,110 | <p>Just remove the character you don't want to touch from the replacement string:</p>
<pre><code>import string
remove = dict.fromkeys(map(ord, '\n' + string.punctuation.replace('@','')))
sample = 'The quick brown fox, like, totally jumped, @man!'
sample.translate(remove)
</code></pre>
<p>Also note that I changed <code>'\n '</code> to <code>'\n'</code>, as the former will remove spaces from your string.</p>
<p>Result:</p>
<pre><code>The quick brown fox like totally jumped @man
</code></pre>
| 2 | 2016-08-27T06:18:40Z | [
"python"
] |
How to split a string on commas or periods in nltk | 39,178,154 | <p>I want to separate a string on commas and/or periods in nltk. I've tried with <code>sent_tokenize()</code> but it separates only on periods.</p>
<p>I've also tried this code</p>
<pre><code>from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktLanguageVars
ex_sent = "This is an example showing sentence filtration.This is how it is done, in case of Python I want to learn more. So, that i can have some experience over it, by it I mean python."
class CommaPoint(PunktLanguageVars):
sent_end_chars = ('.','?','!',',')
tokenizer = PunktSentenceTokenizer(lang_vars = CommaPoint())
n_w=tokenizer.tokenize(ex_sent)
print n_w
</code></pre>
<p>The output for the code above is</p>
<pre><code>['This is an example showing sentence filtration.This is how it is done,' 'in case of Python I want to learn more.' 'So,' 'that i can have some experience over it,' 'by it I mean python.\n']
</code></pre>
<p>When I try to give '.' without any space it is taking it as a word </p>
<p>I want the output as</p>
<pre><code>['This is an example showing sentence filtration.' 'This is how it is done,' 'in case of Python I want to learn more.' 'So,' 'that i can have some experience over it,' 'by it I mean python.']
</code></pre>
<p><a href="http://i.stack.imgur.com/4pwEO.png" rel="nofollow">image of the above written code</a></p>
| 0 | 2016-08-27T06:26:10Z | 39,190,983 | <p>How about something simpler with <code>re</code>:</p>
<pre><code>>>> import re
>>> sent = "This is an example showing sentence filtration.This is how it is done, in case of Python I want to learn more. So, that i can have some experience over it, by it I mean python."
>>> re.split(r'[.,]', sent)
['This is an example showing sentence filtration', 'This is how it is done', ' in case of Python I want to learn more', ' So', ' that i can have some experience over it', ' by it I mean python', '']
</code></pre>
<p>To keep the delimiter, you can use group:</p>
<pre><code>>>> re.split(r'([.,])', sent)
['This is an example showing sentence filtration', '.', 'This is how it is done', ',', ' in case of Python I want to learn more', '.', ' So', ',', ' that i can have some experience over it', ',', ' by it I mean python', '.', '']
</code></pre>
| 1 | 2016-08-28T11:52:38Z | [
"python",
"nltk"
] |
Testing within a python class method | 39,178,265 | <p>I am using unittest in python to test a project. The project defines classes that are intended for other python developers to subclass. The project can then be run and utilizes the subclasses that the user has written.</p>
<p>I want to test that the subclass's methods are being passed correct data by the project. How can I do this? It is not straightforward to call <code>unittest.TestCase.assert*</code> methods from within the test classes which are subclassing from the project.</p>
<p>I have tried setting the <code>TestCase</code> object to a global variable and calling the <code>TestCase</code> object's assert methods from within the subclass methods, but the global variable does not seem to be defined from within the scope of the test class methods.</p>
<p>Example</p>
<pre><code>import unittest
import myproject
class TestProjectClass(unittest.TestCase):
def test_within_class_method(self):
myproject.run(config_file_pointing_to_ProjectClass) # Calls SomeUsersClass.project_method()
class SomeUsersClass(myproject.UserClassTemplate):
def project_method(self, data_passed_by_project):
#want to test data_passed_by_project in here
pass
</code></pre>
| 0 | 2016-08-27T06:42:02Z | 39,178,302 | <p>You can try unittest in docstring.</p>
<p>Have a look at this:</p>
<p><a href="http://docs.python-guide.org/en/latest/writing/tests/#doctest" rel="nofollow">http://docs.python-guide.org/en/latest/writing/tests/#doctest</a></p>
| -1 | 2016-08-27T06:47:02Z | [
"python",
"class",
"python-unittest"
] |
Testing within a python class method | 39,178,265 | <p>I am using unittest in python to test a project. The project defines classes that are intended for other python developers to subclass. The project can then be run and utilizes the subclasses that the user has written.</p>
<p>I want to test that the subclass's methods are being passed correct data by the project. How can I do this? It is not straightforward to call <code>unittest.TestCase.assert*</code> methods from within the test classes which are subclassing from the project.</p>
<p>I have tried setting the <code>TestCase</code> object to a global variable and calling the <code>TestCase</code> object's assert methods from within the subclass methods, but the global variable does not seem to be defined from within the scope of the test class methods.</p>
<p>Example</p>
<pre><code>import unittest
import myproject
class TestProjectClass(unittest.TestCase):
def test_within_class_method(self):
myproject.run(config_file_pointing_to_ProjectClass) # Calls SomeUsersClass.project_method()
class SomeUsersClass(myproject.UserClassTemplate):
def project_method(self, data_passed_by_project):
#want to test data_passed_by_project in here
pass
</code></pre>
| 0 | 2016-08-27T06:42:02Z | 39,195,722 | <p>I was able to get this working by using <code>raise</code> to pass a custom exception up to the <code>unittest.TestCase</code>. The custom exception can be packed with whatever data needs to be tested. I don't show it here, but <code>test_helper.py</code> is just a bare bones subclass of <code>Exception</code>.</p>
<pre><code>import unittest
import myproject
from test_helper import PassItUpForTesting
class TestProjectClass(unittest.TestCase):
def test_within_class_method(self):
try:
# The following line calls SomeUsersClass.project_method()
myproject.run(config_file_pointing_to_ProjectClass)
except PassItUpForTesting as e:
# Test things using e.args[0] here
# Example test
self.assertEqual(e.args[0].some_attribute_of_the_data,
e.args[0].some_other_attribute_of_the_data)
class SomeUsersClass(myproject.UserClassTemplate):
def project_method(self, data_passed_by_project):
#want to test data_passed_by_project in here
raise PassItUpForTesting(data_passed_by_project)
</code></pre>
<p>(For some reason, defining the custom exception within the same file wasn't working because the instance of the exception created within the user's class was not being identified as an instance of the custom exception. Inspection of the exception via <code>sys.exc_*</code> revealed that the exception types were coming out differently. So instead I put the exception in another module, import it, and it worked.)</p>
| 0 | 2016-08-28T20:58:18Z | [
"python",
"class",
"python-unittest"
] |
Phyton 3.5 "for loop" "enumerate()â Select Word from List | 39,178,294 | <p>Hi I'm new here I've just started learning python</p>
<p>Individual words in wordList will be referred to as âwordâ as a variable.</p>
<p>who would I set this up this for a python english grammar gen program by the way. </p>
<p>also I wanna try to Enter a loop that repeats once for each word in wordList. Trying to use a for loop with âenumerate()â function but I keep getting stuck. Any help would be great. </p>
<pre><code>print('Welcome to my English Test App')
# Import the random module to allow us to select the word list and questions at random.
import random
candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'PIGEON', 'POSTER', 'TELEVISION', 'SPY', 'RHYTHM', 'SUBSTANTIAL', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY']
# places words down in a list
s = random.sample (candidateWords, 5)
for index,w in enumerate(s):
print(index,w)
</code></pre>
| -2 | 2016-08-27T06:45:53Z | 39,178,326 | <p>if your question is how to use enumerate, here's an application for your code sample:</p>
<pre><code>import random
candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'PIGEON', 'POSTER', 'TELEVISION', 'SPY', 'RHYTHM', 'SUBSTANTIAL', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY']
s = random.sample (candidateWords, 5)
# loop through the list using enumerate
for index,w in enumerate(s):
print("word {} out of {} is {}, nb vowels is {}".format(index+1,len(s),w,countVowels(w)))
</code></pre>
<p>output</p>
<pre><code>word 1 out of 5 is NIGHT, nb vowels is 1
word 2 out of 5 is BALLOON, nb vowels is 3
word 3 out of 5 is SUBSTANTIAL, nb vowels is 4
word 4 out of 5 is BIG, nb vowels is 1
word 5 out of 5 is PIGEON, nb vowels is 3
</code></pre>
<p>Note that you don't have to use enumerate if you don't need the indexes:</p>
<pre><code>for w in s:
print(w,countVowels(w))
</code></pre>
<p>for your count vowels (since everyone seemed to think this was the question at some point), you can do this, and whether Y is a vowel or not is up to you since it's unclear (<a href="http://www.oxforddictionaries.com/words/is-the-letter-y-a-vowel-or-a-consonant" rel="nofollow">Oxford</a>)</p>
<pre><code>def countVowels(word):
return sum(word.count(x) for x in "AEIOUY")
</code></pre>
<p>The generator comp will apply count characters for each vowels in the word, then applies standard sum function.</p>
| 0 | 2016-08-27T06:50:17Z | [
"python",
"python-3.x",
"for-loop",
"enumerate"
] |
Capture keyPressEvent in minimized PyQt application | 39,178,311 | <p>I am trying to write an error reporting application and would like to keep it as a tray icon for the most part - but the idea is to maximize it with a specific key combination (e.g. "Ctrl+Alt+H", or something like it).</p>
| 0 | 2016-08-27T06:48:10Z | 39,180,938 | <p>Look like not possible as is. But I found that. It should be a start of an answer for you:</p>
<p><a href="http://libqxt.bitbucket.org/doc/tip/qxtglobalshortcut.html" rel="nofollow">http://libqxt.bitbucket.org/doc/tip/qxtglobalshortcut.html</a></p>
<p><a href="http://stackoverflow.com/questions/23193038/how-to-detect-global-key-sequence-press-in-qt">How to detect global key sequence press in Qt?</a></p>
| 0 | 2016-08-27T12:03:32Z | [
"python",
"pyqt",
"keyboard-shortcuts",
"trayicon"
] |
Capture keyPressEvent in minimized PyQt application | 39,178,311 | <p>I am trying to write an error reporting application and would like to keep it as a tray icon for the most part - but the idea is to maximize it with a specific key combination (e.g. "Ctrl+Alt+H", or something like it).</p>
| 0 | 2016-08-27T06:48:10Z | 39,198,155 | <p>Thanks for reply, I was looking deeper into some of the codes I had in my repo and found out this -
<a href="https://sourceforge.net/p/pyhook/wiki/PyHook_Tutorial/" rel="nofollow">https://sourceforge.net/p/pyhook/wiki/PyHook_Tutorial/</a></p>
<p>This is specifically for windows but saw pyxhook for linux</p>
<p><a href="http://jeffhoogland.blogspot.in/2014/10/pyhook-for-linux-with-pyxhook.html" rel="nofollow">http://jeffhoogland.blogspot.in/2014/10/pyhook-for-linux-with-pyxhook.html</a></p>
<p>Tried the windows version and it is working like a charm, need to customise that though. Have to the linux version as well</p>
| 0 | 2016-08-29T03:36:11Z | [
"python",
"pyqt",
"keyboard-shortcuts",
"trayicon"
] |
value counts of group by in pandas | 39,178,329 | <p>I am new to pandas and was trying to learn about this feature.</p>
<pre><code>iris = datasets.load_iris()
grps = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
iris = pd.DataFrame(iris.data[:,0],columns = ["SL"])
iris['bins'] = pd.cut(iris["SL"], 10 ,labels = grps )
iris['target'] = datasets.load_iris().target
</code></pre>
<p>I would like to have the number of occurence of each class in each bins. How do i do this as i cannot seem to think of a way. And i would like to plot this output as a stacked histogram</p>
| 1 | 2016-08-27T06:50:30Z | 39,179,715 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> after you have binned them into bins corresponding to the groups specified in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>cut</code></a>.</p>
<pre><code>sns.set_style('darkgrid')
df = pd.DataFrame(datasets.load_iris().data[:,0], columns=['SL'])
df['target'] = datasets.load_iris().target
# Total number of bins to be grouped under
grps = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Empty list to append later
grouped_list = []
# Iterating through grouped by target variable
for label, key in df.groupby('target'):
grouped_list.append(pd.cut(key['SL'], bins = grps).value_counts())
# Concatenate column-wise and create a stacked-bar plot
pd.concat(grouped_list, axis=1).add_prefix('class_').plot(kind='bar', stacked=True, rot=0,
figsize=(6,6), cmap=plt.cm.rainbow)
# Aesthetics
plt.title("Sepal Length binned counts")
plt.xlabel("Buckets")
plt.ylabel("Occurences")
sns.plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/itYfa.png" rel="nofollow"><img src="http://i.stack.imgur.com/itYfa.png" alt="Image"></a></p>
| 1 | 2016-08-27T09:48:29Z | [
"python",
"pandas",
"matplotlib",
"dataframe"
] |
value counts of group by in pandas | 39,178,329 | <p>I am new to pandas and was trying to learn about this feature.</p>
<pre><code>iris = datasets.load_iris()
grps = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
iris = pd.DataFrame(iris.data[:,0],columns = ["SL"])
iris['bins'] = pd.cut(iris["SL"], 10 ,labels = grps )
iris['target'] = datasets.load_iris().target
</code></pre>
<p>I would like to have the number of occurence of each class in each bins. How do i do this as i cannot seem to think of a way. And i would like to plot this output as a stacked histogram</p>
| 1 | 2016-08-27T06:50:30Z | 39,180,624 | <p>Try this:</p>
<pre><code>In [83]: import seaborn as sns
In [84]: x = iris.groupby(['target','bins']).size().to_frame('occurences').reset_index()
In [85]: x
Out[85]:
target bins occurences
0 0 1 9
1 0 2 19
2 0 3 12
3 0 4 9
4 0 5 1
5 1 2 3
6 1 3 2
7 1 4 16
8 1 5 13
9 1 6 7
10 1 7 7
11 1 8 2
12 2 2 1
13 2 4 2
14 2 5 8
15 2 6 13
16 2 7 11
17 2 8 4
18 2 9 5
19 2 10 6
In [86]: sns.barplot(x='bins', y='occurences', hue='target', data=x)
Out[86]: <matplotlib.axes._subplots.AxesSubplot at 0x9b3bb38>
</code></pre>
<p><a href="http://i.stack.imgur.com/qIXbm.png" rel="nofollow"><img src="http://i.stack.imgur.com/qIXbm.png" alt="enter image description here"></a></p>
| 1 | 2016-08-27T11:29:33Z | [
"python",
"pandas",
"matplotlib",
"dataframe"
] |
Python sort sprite dict into new dict sorted by name | 39,178,366 | <p>I have a dict which is part of a <code>SpriteSheet</code> class of the attribute <code>sprite_info</code>. <code>sprite info</code> holds the names and location and xd/yd of each sprite on the sheet, i.e. </p>
<pre><code>{'stone_Wall' : { 'x': '781', 'xd': '70', 'y': '568', 'yd': '70'} ... }
</code></pre>
<p>What I'd like to do is sort the dict by each name. In other words, there are other names in the list list <code>stone_Right</code> and <code>stone_Mid</code> and so on. The one thing they all have in common is <code>stone_</code>.</p>
<p>What's the most efficient way of doing this? My limited experience tells me to just go into a bunch of nested for-loops, but I know there's a better way.</p>
<p>Further clarification:</p>
<p>Once everything is sorted, I would like to separate the dict by name. Using my example, for any key that includes <code>stone</code> or <code>stone_</code>, add it to a new dict within the already existing dict.</p>
| 1 | 2016-08-27T06:55:26Z | 39,178,476 | <p>You can't sort a <code>dict</code>, as it uses its own sorted tree structure internally to keep efficient.</p>
<p>You can use <code>OrderedDict</code> which will keep track of the order elements are added.</p>
<p>To created a sorted <code>OrderedDict</code> from a <code>dict</code>, sort the key/value pairs from the <code>dict</code> based on the <code>key</code>.</p>
<p>edit: having thought a little more, <code>sorted</code> will compare tuples element by element, so item zero (the key) will be compared first, and will also be unique (as <code>dict</code> has unique keys), so we don't need to do anything clever with the <code>sorted</code> <code>key</code> parameter.</p>
<pre><code>from collections import OrderedDict
# from operator import itemgetter
sprites = dict()
# sorted_sprites = OrderedDict(sorted(sprites.items(), key=itemgetter(0)))
sorted_sprites = OrderedDict(sorted(sprites.items())) # equivalent to above
</code></pre>
<p><a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow"><strong><code>sorted</code></strong></a> is a built-in function which returns a <code>list</code> from a sequence.</p>
<p>The <code>key</code> parameter determines how to order the values in the sequence. As we are passing <code>sprites.items()</code> it is getting tuple pairs e.g. <code>('stone_Wall', { 'x': '781', 'xd': '70', 'y': '568', 'yd': '70'})</code>, so the key we want is the zero-th element of the tuple, <code>'stone_Wall'</code>.</p>
<p><a href="https://docs.python.org/2/library/operator.html#operator.itemgetter" rel="nofollow"><strong><code>itemgetter</code></strong></a> is a functor which will retrieve a particular object (or objects) from a sequence. Here we ask it to get the zero-th.</p>
<p>However, as noted above, default tuple comparison will do this for us. See this related question: <a href="https://stackoverflow.com/questions/5292303/python-tuple-comparison">python tuple comparison</a></p>
| 0 | 2016-08-27T07:10:15Z | [
"python",
"python-2.7",
"sorting",
"dictionary",
"pygame"
] |
Exception Value: Cannot assign "x": "y" must be a "z" instance | 39,178,406 | <p>I have a script to pull in football fixtures into my mySQL database. If I do not try to pull in the seasonid it works. But when I put the seasonid in it breaks and I am unsure why. Any help would be appreciated.</p>
<p>The models are as follows:</p>
<pre><code>class StraightredSeason(models.Model):
seasonid = models.IntegerField(primary_key = True)
seasonyear = models.CharField(max_length = 4)
seasonname = models.CharField(max_length = 36)
def __unicode__(self):
return self.seasonid
class Meta:
managed = True
db_table = 'straightred_season'
class StraightredTeam(models.Model):
teamid = models.IntegerField(primary_key=True)
teamname = models.CharField(max_length=36)
country = models.CharField(max_length=36,null=True)
stadium = models.CharField(max_length=36,null=True)
homepageurl = models.TextField(null=True)
wikilink = models.TextField(null=True)
teamcode = models.CharField(max_length=5,null=True)
teamshortname = models.CharField(max_length=24,null=True)
currentteam = models.PositiveSmallIntegerField(null=True)
def __unicode__(self):
return self.teamname
class Meta:
managed = True
db_table = 'straightred_team'
class StraightredFixture(models.Model):
fixtureid = models.IntegerField(primary_key=True)
home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures')
away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures')
fixturedate = models.DateTimeField(null=True)
fixturestatus = models.CharField(max_length=24,null=True)
fixturematchday = models.IntegerField(null=True)
spectators = models.IntegerField(null=True)
hometeamscore = models.IntegerField(null=True)
awayteamscore = models.IntegerField(null=True)
homegoaldetails = models.TextField(null=True)
awaygoaldetails = models.TextField(null=True)
hometeamyellowcarddetails = models.TextField(null=True)
awayteamyellowcarddetails = models.TextField(null=True)
hometeamredcarddetails = models.TextField(null=True)
awayteamredcarddetails = models.TextField(null=True)
soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_season')
def __unicode__(self):
return self.fixtureid
class Meta:
managed = True
db_table = 'straightred_fixture'
</code></pre>
<p>The StraightredSeason table contains the following:</p>
<pre><code>mysql> select * from straightred_season;
+----------+------------+------------+
| seasonid | seasonyear | seasonname |
+----------+------------+------------+
| 1025 | 16/1 | EPL |
+----------+------------+------------+
</code></pre>
<p>But whenever I run the code below I get the following error:</p>
<p>Cannot assign "1025": "StraightredFixture.soccerseason" must be a "StraightredSeason" instance.</p>
<pre><code> fixtureUpdate = StraightredFixture(fixtureid=fixture['Id'],
away_team_id = fixture['AwayTeam_Id'],
home_team_id = fixture['HomeTeam_Id'],
fixturedate = fixture['Date'],
fixturestatus = fixture['Time'],
fixturematchday = fixture['Round'],
spectators = fixture['Spectators'],
hometeamscore = fixture['HomeGoals'],
awayteamscore = fixture['AwayGoals'],
homegoaldetails = fixture['HomeGoalDetails'],
awaygoaldetails = fixture['AwayGoalDetails'],
hometeamyellowcarddetails = fixture['HomeTeamYellowCardDetails'],
awayteamyellowcarddetails = fixture['AwayTeamYellowCardDetails'],
hometeamredcarddetails = fixture['HomeTeamRedCardDetails'],
awayteamredcarddetails = fixture['AwayTeamRedCardDetails'],
soccerseason = 1025)
</code></pre>
| 0 | 2016-08-27T07:01:12Z | 39,178,514 | <p>Try to replace <code>soccerseason = 1025</code> with <code>soccerseason_id = 1025</code>. <code>soccerseason</code> is a relationship to <code>StraightredSeason</code> so you should provide an instance of it when trying to set this attribute.</p>
| 0 | 2016-08-27T07:15:20Z | [
"python",
"mysql",
"django"
] |
Exception Value: Cannot assign "x": "y" must be a "z" instance | 39,178,406 | <p>I have a script to pull in football fixtures into my mySQL database. If I do not try to pull in the seasonid it works. But when I put the seasonid in it breaks and I am unsure why. Any help would be appreciated.</p>
<p>The models are as follows:</p>
<pre><code>class StraightredSeason(models.Model):
seasonid = models.IntegerField(primary_key = True)
seasonyear = models.CharField(max_length = 4)
seasonname = models.CharField(max_length = 36)
def __unicode__(self):
return self.seasonid
class Meta:
managed = True
db_table = 'straightred_season'
class StraightredTeam(models.Model):
teamid = models.IntegerField(primary_key=True)
teamname = models.CharField(max_length=36)
country = models.CharField(max_length=36,null=True)
stadium = models.CharField(max_length=36,null=True)
homepageurl = models.TextField(null=True)
wikilink = models.TextField(null=True)
teamcode = models.CharField(max_length=5,null=True)
teamshortname = models.CharField(max_length=24,null=True)
currentteam = models.PositiveSmallIntegerField(null=True)
def __unicode__(self):
return self.teamname
class Meta:
managed = True
db_table = 'straightred_team'
class StraightredFixture(models.Model):
fixtureid = models.IntegerField(primary_key=True)
home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures')
away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures')
fixturedate = models.DateTimeField(null=True)
fixturestatus = models.CharField(max_length=24,null=True)
fixturematchday = models.IntegerField(null=True)
spectators = models.IntegerField(null=True)
hometeamscore = models.IntegerField(null=True)
awayteamscore = models.IntegerField(null=True)
homegoaldetails = models.TextField(null=True)
awaygoaldetails = models.TextField(null=True)
hometeamyellowcarddetails = models.TextField(null=True)
awayteamyellowcarddetails = models.TextField(null=True)
hometeamredcarddetails = models.TextField(null=True)
awayteamredcarddetails = models.TextField(null=True)
soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_season')
def __unicode__(self):
return self.fixtureid
class Meta:
managed = True
db_table = 'straightred_fixture'
</code></pre>
<p>The StraightredSeason table contains the following:</p>
<pre><code>mysql> select * from straightred_season;
+----------+------------+------------+
| seasonid | seasonyear | seasonname |
+----------+------------+------------+
| 1025 | 16/1 | EPL |
+----------+------------+------------+
</code></pre>
<p>But whenever I run the code below I get the following error:</p>
<p>Cannot assign "1025": "StraightredFixture.soccerseason" must be a "StraightredSeason" instance.</p>
<pre><code> fixtureUpdate = StraightredFixture(fixtureid=fixture['Id'],
away_team_id = fixture['AwayTeam_Id'],
home_team_id = fixture['HomeTeam_Id'],
fixturedate = fixture['Date'],
fixturestatus = fixture['Time'],
fixturematchday = fixture['Round'],
spectators = fixture['Spectators'],
hometeamscore = fixture['HomeGoals'],
awayteamscore = fixture['AwayGoals'],
homegoaldetails = fixture['HomeGoalDetails'],
awaygoaldetails = fixture['AwayGoalDetails'],
hometeamyellowcarddetails = fixture['HomeTeamYellowCardDetails'],
awayteamyellowcarddetails = fixture['AwayTeamYellowCardDetails'],
hometeamredcarddetails = fixture['HomeTeamRedCardDetails'],
awayteamredcarddetails = fixture['AwayTeamRedCardDetails'],
soccerseason = 1025)
</code></pre>
| 0 | 2016-08-27T07:01:12Z | 39,178,524 | <p>You can't set a <code>ForeignKey</code> object as <code>int</code>. You can instead set the <code>ForeignKey</code> <em>value</em> (id associated with the FK object) by appending <code>_id</code> to the field:</p>
<pre><code>fixtureUpdate = StraightredFixture(fixtureid=fixture['Id'],
...
soccerseason_id = 1025)
# ^^^
</code></pre>
| 1 | 2016-08-27T07:16:42Z | [
"python",
"mysql",
"django"
] |
how to run a python file 20 times with 1000 iterations | 39,178,417 | <p>i want to run a python file file.py 20 times with 1000 iterations with single run click so that i dont need to click run 20 times manually.</p>
<pre><code>Init()
globalBest=pop[0].chromosome
# Saving Result
fp=open(resultFileName,"w");
fp.write("Iteration,Fitness,Chromosomes\n")
for i in range(0,iterations):
Crossover()
Mutation()
MemoriseGlobalBest()
if funEval >=maxFunEval:
break
if i%20==0:
print "I:",i,"\t Fitness:", bestFitness
fp.write(str(i) + "," + str(bestFitness) + "," + str(bestChromosome) + "\n")
print "I:",i+1,"\t Fitness:", bestFitness
fp.write(str(i+1) + "," + str(bestFitness) + "," + str(bestChromosome))
fp.close()
</code></pre>
| 1 | 2016-08-27T07:02:24Z | 39,178,510 | <p>You can write another script which call your script 20 times. Make a loop and call the file.py 20 times in it.</p>
| 0 | 2016-08-27T07:15:02Z | [
"python",
"optimization"
] |
how to run a python file 20 times with 1000 iterations | 39,178,417 | <p>i want to run a python file file.py 20 times with 1000 iterations with single run click so that i dont need to click run 20 times manually.</p>
<pre><code>Init()
globalBest=pop[0].chromosome
# Saving Result
fp=open(resultFileName,"w");
fp.write("Iteration,Fitness,Chromosomes\n")
for i in range(0,iterations):
Crossover()
Mutation()
MemoriseGlobalBest()
if funEval >=maxFunEval:
break
if i%20==0:
print "I:",i,"\t Fitness:", bestFitness
fp.write(str(i) + "," + str(bestFitness) + "," + str(bestChromosome) + "\n")
print "I:",i+1,"\t Fitness:", bestFitness
fp.write(str(i+1) + "," + str(bestFitness) + "," + str(bestChromosome))
fp.close()
</code></pre>
| 1 | 2016-08-27T07:02:24Z | 39,179,050 | <p>try:</p>
<pre><code>for iteration in range(20):
Init()
globalBest = pop[0].chromosome
# Saving Result
fp = open(resultFileName, "a")
fp.write("Iteration,Fitness,Chromosomes\n")
for i in range(0, iterations):
Crossover()
Mutation()
MemoriseGlobalBest()
if funEval >= maxFunEval:
break
if i % 20 == 0:
print
"I:", i, "\t Fitness:", bestFitness
fp.write(str(i) + "," + str(bestFitness) + "," + str(bestChromosome) + "\n")
print
"I:", i + 1, "\t Fitness:", bestFitness
fp.write(str(i + 1) + "," + str(bestFitness) + "," + str(bestChromosome))
fp.close()
</code></pre>
| 0 | 2016-08-27T08:25:32Z | [
"python",
"optimization"
] |
Sublime Text 3-Anaconda openCV docstring not working? | 39,178,460 | <p>I'm using the Anaconda plugin in Sublime Text 3. Everything was working exactly as I expected. I love Docstring. It worked great and saved me a lot of time. </p>
<p>But when I tried <code>import cv2</code>, cv2 was not on the autoComplete list. AutoComplete and docstring wouldn't work for anything that is in openCV.</p>
<p>I use Mac, with <strong>Python 3.5.1</strong> and <strong>openCV 3.1.0</strong>. In Anaconda.sublime-settings, my python interpreter is set as: <code>"/usr/local/bin/python3.5"</code> I do have another Windows with Anaconda plugin installed in ST3, and it worked fine. I don't really what is going on. Any suggestion?</p>
| 0 | 2016-08-27T07:07:48Z | 39,184,691 | <p>This setting is not documented in the default <code>Anaconda.sublime-settings</code> file, but I found it once on the <a href="http://damnwidget.github.io/anaconda/anaconda_settings/#toc_5" rel="nofollow">Anaconda website</a>: <code>"extra_paths"</code>. Open your <code>.sublime-project</code> file, and add the following:</p>
<pre class="lang-js prettyprint-override"><code>{
...
"settings": {
"extra_paths":
[
"/usr/local/Cellar/opencv3/3.1.0_3/lib/python3.5/site-packageââs"
]
}
}
</code></pre>
<p>or, if you're just using your user <code>Anaconda.sublime-settings</code>, just add:</p>
<pre class="lang-js prettyprint-override"><code> "extra_paths":
[
"/usr/local/Cellar/opencv3/3.1.0_3/lib/python3.5/site-packageââs"
]
</code></pre>
<p>This will explicitly tell Anaconda to look there for additional modules. Hopefully that will do the trick.</p>
| 0 | 2016-08-27T18:59:06Z | [
"python",
"opencv",
"sublimetext3",
"sublime-anaconda"
] |
pandas inner join performance issue | 39,178,533 | <p>I have two csv file and I load them into pandas data frame. One file is large, about 10M rows and 20 columns (all string type) and size is around 1G bytes, the other file is small, about 5k rows, and 5 columns and size is around 1M. I want to do inner join by a single common column between the two data frame.</p>
<p>This is how I join,</p>
<pre><code>mergedDataSet = pd.merge(smallDataFrame, largeDataFrame, on='uid', how='inner')
</code></pre>
<p>I tried if I sample 1% of the big data set, program runs smoothly without any issues and complete within 5 seconds, so I verified function should be ok for my code.</p>
<p>But if I join the real large data set, the program will be terminated in about 20-30 seconds, error message is <code>Process finished with exit code 137 (interrupted by signal 9: SIGKILL)</code>. I am using Python 2.7 with miniconda, on Mac OSX and I run from PyCharm. My machine has 16G memory and well above the size of 1G file.</p>
<p>Wondering if any thoughts to tune performance of data frame join in pandas, or any other quick solution for inner join?</p>
<p>Another confusion from me is, why the program is KILLed? By whom and why reason?</p>
<p><strong>Edit 1</strong>, error captured in /var/log/system.log when doing inner join,</p>
<pre><code>Aug 27 11:00:18 foo-laptop com.apple.CDScheduler[702]: Thermal pressure state: 1 Memory pressure state: 0
Aug 27 11:00:18 foo-laptop com.apple.CDScheduler[47]: Thermal pressure state: 1 Memory pressure state: 0
Aug 27 11:00:33 foo-laptop iTerm2[43018]: Time to encode state for window <PseudoTerminal: 0x7fb3659d3960 tabs=1 window=<PTYWindow: 0x7fb3637c0c80 frame=NSRect: {{0, 0}, {1280, 800}} title=5. tail alpha=1.000000 isMain=1 isKey=1 isVisible=1 delegate=0x7fb3659d3960>>: 0.02136099338531494
Aug 27 11:00:41 foo-laptop iTerm2[43018]: Time to encode state for window <PseudoTerminal: 0x7fb3659d3960 tabs=1 window=<PTYWindow: 0x7fb3637c0c80 frame=NSRect: {{0, 0}, {1280, 800}} title=5. tail alpha=1.000000 isMain=0 isKey=0 isVisible=1 delegate=0x7fb3659d3960>>: 0.01138699054718018
Aug 27 11:00:46 foo-laptop kernel[0]: low swap: killing pid 92118 (python2.7)
Aug 27 11:00:46 foo-laptop kernel[0]: memorystatus_thread: idle exiting pid 789 [CallHistoryPlugi]
Aug 27 11:00:56 foo-laptop iTerm2[43018]: Time to encode state for window <PseudoTerminal: 0x7fb3659d3960 tabs=1 window=<PTYWindow: 0x7fb3637c0c80 frame=NSRect: {{0, 0}, {1280, 800}} title=5. tail alpha=1.000000 isMain=0 isKey=0 isVisible=1 delegate=0x7fb3659d3960>>: 0.01823097467422485
Aug 27 11:00:58 foo-laptop kernel[0]: process WeChat[85077] caught causing excessive wakeups. Observed wakeups rate (per sec): 184; Maximum permitted wakeups rate (per sec): 150; Observation period: 300 seconds; Task lifetime number of wakeups: 2193951
Aug 27 11:00:58 foo-laptop com.apple.xpc.launchd[1] (com.apple.ReportCrash[92123]): Endpoint has been activated through legacy launch(3) APIs. Please switch to XPC or bootstrap_check_in(): com.apple.ReportCrash
Aug 27 11:00:58 foo-laptop ReportCrash[92123]: Invoking spindump for pid=85077 wakeups_rate=184 duration=245 because of excessive wakeups
Aug 27 11:01:03 foo-laptop com.apple.CDScheduler[702]: Thermal pressure state: 0 Memory pressure state: 0
Aug 27 11:01:03 foo-laptop com.apple.CDScheduler[47]: Thermal pressure state: 0 Memory pressure state: 0
</code></pre>
<p>regards,
Lin</p>
| 2 | 2016-08-27T07:17:54Z | 39,192,848 | <p>Check the cardinality of 'uid' column on both sides. It is most probable that your join is multiplying the data manyfold. For example, if you have uid with value 1 in 100 records of dataframe1 and in 10 records in dataframe2, your join would yield 1000 records.</p>
<p>to check the cardinality, I would do the following:</p>
<pre><code>df1[df1.uid.isin(df2.uid.unique())]['uid'].value_counts()
df2[df2.uid.isin(df1.uid.unique())]['uid'].value_counts()
</code></pre>
<p>This code will check if the values of 'uid' that are present in other frame's uid and have duplicates.</p>
| 2 | 2016-08-28T15:25:35Z | [
"python",
"performance",
"python-2.7",
"pandas",
"dataframe"
] |
Radiobutton Selection | 39,178,537 | <p>I am trying to make a game by combining Turtle and Tkinter. My code is working good but I have a problem with selection of <code>Radiobutton</code> part. When I try to select the "Black" (colored) radiobutton, I am not able to select it, however, there is no problem with other colors selection. Another problem is that I would like to use "No color" option and when the user selects it, shape must be drawn with no filling. But it does not work, it gets filled with a color selected automatically. I do not get how it is selected automatically. How can I fix that problem?</p>
<pre><code>import tkinter
from tkinter import *
import turtle
import sys
sc=Tk()
sc.geometry("1000x1000+100+100")
var= IntVar()
pensize=StringVar()
angle=StringVar()
radius=StringVar()
lenght=StringVar()
#FRAMES
fr1=Frame(sc,height=200,width=200,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr1.grid(row=0,column=0,sticky=(N,E,W,S))
#FR2
fr2=Frame(sc,height=200,width=200,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr2.grid(row=1,column=0,sticky=(N,E,W,S))
#FR3
fr3=Frame(sc,height=200,width=200,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr3.grid(row=2,column=0,sticky=(N,E,W,S))
#FR4
fr4=Frame(sc,height=500,width=600,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr4.grid(row=2,column=2,sticky=(N,E,W,S))
#FR5
fr5=Frame(sc,height=100,width=600,bd=4,bg="gray",takefocus="",relief=SUNKEN)
fr5.grid(row=1,column=2,sticky=(N,E,W,S))
#Canvas
canvas = Canvas(fr4,width=750, height=750)
canvas.pack()
#Turtle
turtle1=turtle.RawTurtle(canvas)
turtle1.color("blue")
turtle1.shape("turtle")
#Functions
def rectangle():
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
for i in range(4):
turtle1.forward(int(lenght.get()))
turtle1.left(90)
turtle1.end_fill()
def circle():
turtle1.begin_fill()
turtle1.pensize(int(pensize.get()))
colorchoices()
turtle1.circle(int(radius.get()))
turtle1.end_fill()
def triangle():
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
turtle1.forward(int(lenght.get()))
turtle1.left(120)
turtle1.forward(int(lenght.get()))
turtle1.left(120)
turtle1.forward(int(lenght.get()))
turtle1.end_fill()
def line100 ():
turtle1.penup()
turtle1.pensize(int(pensize.get()))
turtle1.forward(int(lenght.get()))
turtle1.pendown()
def linel90 ():
turtle1.penup()
turtle1.left(int(angle.get()))
turtle1.pendown()
def liner90 ():
turtle1.penup()
turtle1.pensize(int(pensize.get()))
turtle1.right(int(angle.get()))
turtle1.pendown()
def linebc100 ():
turtle1.penup()
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
turtle1.backward(int(lenght.get()))
turtle1.end_fill()
turtle1.pendown()
def line():
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
turtle1.forward(int(lenght.get()))
turtle1.end_fill()
def colorchoices():
selection=var.get()
for i in range(7):
if selection==1:
turtle1.fillcolor("red")
elif selection==2:
turtle1.fillcolor("blue")
elif selection==3:
turtle1.fillcolor("purple")
elif selection==4:
turtle1.fillcolor("yellow")
elif selection==5:
turtle1.fillcolor("black")
elif selection==6:
turtle1.fillcolor("green")
else:
return
def clear():
turtle1.clear()
but1=Button(fr1,text="Clear",command=clear).pack(side=LEFT)
# shapes
shpc=PhotoImage(file="D://python//ımage/circle.png")
shptr=PhotoImage(file="D://python//ımage/rectangular.png")
shpsq=PhotoImage(file="D://python//ımage/square.png")
shpl=PhotoImage(file="D://python//ımage/line.png")
shphep=PhotoImage(file="D://python//ımage/shapes.png")
#Entry and labels
PenSize=Button(fr5,text="PenSize",font=("Helvetica",14),fg="black").grid(row=0,column=0,columnspan=1,sticky=W)
Angle=Button(fr5,text="Angle",font=("Helvetica",14),fg="black").grid(row=1,column=0,columnspan=1,sticky=W)
Radius=Button(fr5,text="Radius",font=("Helvetica",14),fg="black").grid(row=2,column=0,columnspan=1,sticky=W)
Lenght=Button(fr5,text="Lenght",font=("Helvetica",14),fg="black").grid(row=3,column=0,columnspan=1,sticky=W)
pensize=Entry(fr5)
angle=Entry(fr5)
radius=Entry(fr5)
lenght=Entry(fr5)
pensize.grid(row=0,column=1,columnspan=2,sticky=W)
angle.grid(row=1,column=1,columnspan=2,sticky=W)
radius.grid(row=2,column=1,columnspan=2,sticky=W)
lenght.grid(row=3,column=1,columnspan=2,sticky=W)
#optionmenu
ColorOption=Button(fr5,text="ColorOptions",font=("Helvetica",14),fg="black").grid(row=4,column=0,sticky=W)
R1 = Radiobutton(fr5, text="RED", variable=var, value=1,bg="red").grid(row=4,column=1,sticky=W)
R2 = Radiobutton(fr5, text="BLUE", variable=var, value=2,bg="blue").grid( row=4,column=2,sticky=W)
R3 = Radiobutton(fr5, text="PURPLE", variable=var, value=3,bg="purple").grid( row=4,column=3,sticky=W )
R4 = Radiobutton(fr5, text="YELLOW", variable=var, value=4,bg="yellow").grid( row=4,column=4,sticky=W)
R5 = Radiobutton(fr5, text="BLACK", variable=var, value=5,bg="black",fg="white").grid( row=4,column=5,sticky=W )
R6 = Radiobutton(fr5, text="GREEN", variable=var, value=6,bg="green").grid( row=4,column=6,sticky=W)
R7 = Radiobutton(fr5, text="NO COLOR", variable=var, value=7).grid( row=4,column=7,sticky=W)
#Buttons
but1=Button(fr2,text="Forward",command=line100).grid(row=1,column=2,sticky=(N,E,W,S))
but1=Button(fr2,text="Backward",command=linebc100 ).grid(row=1,column=0,sticky=(N,E,W,S))
but1=Button(fr2,text="Turn90",command=linel90).grid(row=0,column=1,sticky=(N,E,W,S))
but1=Button(fr2,text="Turn(-90)",command=liner90).grid(row=2,column=1,sticky=(N,E,W,S))
#shp1=Label(fr5,text="SHAPES",image=shphep).pack(fill=X)
shp2=Button(fr3,text="Circle",height=200,width=200,image=shpc,command=circle).pack()
shp3=Button(fr3,text="Triangular",height=200,width=200,image=shptr,command=triangle).pack()
shp4=Button(fr3,text="Square",height=200,width=200,image=shpsq,command=rectangle).pack()
shp5=Button(fr3,text="Line",height=200,width=200,compound=LEFT,image=shpl,command=line).pack()
sc.deiconify()
sc.mainloop()
</code></pre>
| 1 | 2016-08-27T07:18:16Z | 39,178,730 | <p>For your second problem:</p>
<pre><code>from tkinter import *
root = Tk()
selvar = StringVar()
selvar.set(' ')
rb1 = Radiobutton(root, variable=selvar, value='a')
rb1.pack()
rb2 = Radiobutton(root, variable=selvar, value='b')
rb2.pack()
</code></pre>
<p>This is for <code>StringVar</code>. And for <code>IntVar</code>:</p>
<pre><code>from tkinter import *
root = Tk()
selvar = IntVar()
selvar.set(0)
rb1 = Radiobutton(root, variable=selvar, value=1)
rb1.pack()
rb2 = Radiobutton(root, variable=selvar, value=2)
rb2.pack()
</code></pre>
<p><b>UPDATE:</b> I figured out that it works fine if I do not use <code>var.set(0)</code> for <code>IntVar()</code> (if I am starting from 1 not 0. Actually, 0 is what makes it selected at the program start). But if it does not work for you without setting it up to 0, then do it. It is actually making it safe anyway.</p>
<p>And for your first problem: You have selected black for background, and white for foreground color. Now when you click on this radiobutton, the dot does not get shown because the color of the dot is white according to the foreground color. Foreground color is not only applied to the text color of a radiobutton, but also to the color of the dot of a radiobutton. So white+white cannot be shown.</p>
| 2 | 2016-08-27T07:45:25Z | [
"python",
"tkinter",
"turtle-graphics"
] |
Radiobutton Selection | 39,178,537 | <p>I am trying to make a game by combining Turtle and Tkinter. My code is working good but I have a problem with selection of <code>Radiobutton</code> part. When I try to select the "Black" (colored) radiobutton, I am not able to select it, however, there is no problem with other colors selection. Another problem is that I would like to use "No color" option and when the user selects it, shape must be drawn with no filling. But it does not work, it gets filled with a color selected automatically. I do not get how it is selected automatically. How can I fix that problem?</p>
<pre><code>import tkinter
from tkinter import *
import turtle
import sys
sc=Tk()
sc.geometry("1000x1000+100+100")
var= IntVar()
pensize=StringVar()
angle=StringVar()
radius=StringVar()
lenght=StringVar()
#FRAMES
fr1=Frame(sc,height=200,width=200,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr1.grid(row=0,column=0,sticky=(N,E,W,S))
#FR2
fr2=Frame(sc,height=200,width=200,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr2.grid(row=1,column=0,sticky=(N,E,W,S))
#FR3
fr3=Frame(sc,height=200,width=200,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr3.grid(row=2,column=0,sticky=(N,E,W,S))
#FR4
fr4=Frame(sc,height=500,width=600,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr4.grid(row=2,column=2,sticky=(N,E,W,S))
#FR5
fr5=Frame(sc,height=100,width=600,bd=4,bg="gray",takefocus="",relief=SUNKEN)
fr5.grid(row=1,column=2,sticky=(N,E,W,S))
#Canvas
canvas = Canvas(fr4,width=750, height=750)
canvas.pack()
#Turtle
turtle1=turtle.RawTurtle(canvas)
turtle1.color("blue")
turtle1.shape("turtle")
#Functions
def rectangle():
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
for i in range(4):
turtle1.forward(int(lenght.get()))
turtle1.left(90)
turtle1.end_fill()
def circle():
turtle1.begin_fill()
turtle1.pensize(int(pensize.get()))
colorchoices()
turtle1.circle(int(radius.get()))
turtle1.end_fill()
def triangle():
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
turtle1.forward(int(lenght.get()))
turtle1.left(120)
turtle1.forward(int(lenght.get()))
turtle1.left(120)
turtle1.forward(int(lenght.get()))
turtle1.end_fill()
def line100 ():
turtle1.penup()
turtle1.pensize(int(pensize.get()))
turtle1.forward(int(lenght.get()))
turtle1.pendown()
def linel90 ():
turtle1.penup()
turtle1.left(int(angle.get()))
turtle1.pendown()
def liner90 ():
turtle1.penup()
turtle1.pensize(int(pensize.get()))
turtle1.right(int(angle.get()))
turtle1.pendown()
def linebc100 ():
turtle1.penup()
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
turtle1.backward(int(lenght.get()))
turtle1.end_fill()
turtle1.pendown()
def line():
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
turtle1.forward(int(lenght.get()))
turtle1.end_fill()
def colorchoices():
selection=var.get()
for i in range(7):
if selection==1:
turtle1.fillcolor("red")
elif selection==2:
turtle1.fillcolor("blue")
elif selection==3:
turtle1.fillcolor("purple")
elif selection==4:
turtle1.fillcolor("yellow")
elif selection==5:
turtle1.fillcolor("black")
elif selection==6:
turtle1.fillcolor("green")
else:
return
def clear():
turtle1.clear()
but1=Button(fr1,text="Clear",command=clear).pack(side=LEFT)
# shapes
shpc=PhotoImage(file="D://python//ımage/circle.png")
shptr=PhotoImage(file="D://python//ımage/rectangular.png")
shpsq=PhotoImage(file="D://python//ımage/square.png")
shpl=PhotoImage(file="D://python//ımage/line.png")
shphep=PhotoImage(file="D://python//ımage/shapes.png")
#Entry and labels
PenSize=Button(fr5,text="PenSize",font=("Helvetica",14),fg="black").grid(row=0,column=0,columnspan=1,sticky=W)
Angle=Button(fr5,text="Angle",font=("Helvetica",14),fg="black").grid(row=1,column=0,columnspan=1,sticky=W)
Radius=Button(fr5,text="Radius",font=("Helvetica",14),fg="black").grid(row=2,column=0,columnspan=1,sticky=W)
Lenght=Button(fr5,text="Lenght",font=("Helvetica",14),fg="black").grid(row=3,column=0,columnspan=1,sticky=W)
pensize=Entry(fr5)
angle=Entry(fr5)
radius=Entry(fr5)
lenght=Entry(fr5)
pensize.grid(row=0,column=1,columnspan=2,sticky=W)
angle.grid(row=1,column=1,columnspan=2,sticky=W)
radius.grid(row=2,column=1,columnspan=2,sticky=W)
lenght.grid(row=3,column=1,columnspan=2,sticky=W)
#optionmenu
ColorOption=Button(fr5,text="ColorOptions",font=("Helvetica",14),fg="black").grid(row=4,column=0,sticky=W)
R1 = Radiobutton(fr5, text="RED", variable=var, value=1,bg="red").grid(row=4,column=1,sticky=W)
R2 = Radiobutton(fr5, text="BLUE", variable=var, value=2,bg="blue").grid( row=4,column=2,sticky=W)
R3 = Radiobutton(fr5, text="PURPLE", variable=var, value=3,bg="purple").grid( row=4,column=3,sticky=W )
R4 = Radiobutton(fr5, text="YELLOW", variable=var, value=4,bg="yellow").grid( row=4,column=4,sticky=W)
R5 = Radiobutton(fr5, text="BLACK", variable=var, value=5,bg="black",fg="white").grid( row=4,column=5,sticky=W )
R6 = Radiobutton(fr5, text="GREEN", variable=var, value=6,bg="green").grid( row=4,column=6,sticky=W)
R7 = Radiobutton(fr5, text="NO COLOR", variable=var, value=7).grid( row=4,column=7,sticky=W)
#Buttons
but1=Button(fr2,text="Forward",command=line100).grid(row=1,column=2,sticky=(N,E,W,S))
but1=Button(fr2,text="Backward",command=linebc100 ).grid(row=1,column=0,sticky=(N,E,W,S))
but1=Button(fr2,text="Turn90",command=linel90).grid(row=0,column=1,sticky=(N,E,W,S))
but1=Button(fr2,text="Turn(-90)",command=liner90).grid(row=2,column=1,sticky=(N,E,W,S))
#shp1=Label(fr5,text="SHAPES",image=shphep).pack(fill=X)
shp2=Button(fr3,text="Circle",height=200,width=200,image=shpc,command=circle).pack()
shp3=Button(fr3,text="Triangular",height=200,width=200,image=shptr,command=triangle).pack()
shp4=Button(fr3,text="Square",height=200,width=200,image=shpsq,command=rectangle).pack()
shp5=Button(fr3,text="Line",height=200,width=200,compound=LEFT,image=shpl,command=line).pack()
sc.deiconify()
sc.mainloop()
</code></pre>
| 1 | 2016-08-27T07:18:16Z | 39,179,055 | <p>Here is my code after correction</p>
<pre><code>import tkinter
from tkinter import *
import turtle
import sys
sc=Tk()
sc.geometry("1000x1000+100+100")
var= IntVar()
pensize=StringVar()
angle=StringVar()
radius=StringVar()
lenght=StringVar()
#FRAMES
fr1=Frame(sc,height=200,width=200,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr1.grid(row=0,column=0,sticky=(N,E,W,S))
#FR2
fr2=Frame(sc,height=200,width=200,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr2.grid(row=1,column=0,sticky=(N,E,W,S))
#FR3
fr3=Frame(sc,height=200,width=200,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr3.grid(row=2,column=0,sticky=(N,E,W,S))
#FR4
fr4=Frame(sc,height=500,width=600,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr4.grid(row=2,column=2,sticky=(N,E,W,S))
#FR5
fr5=Frame(sc,height=100,width=600,bd=4,bg="gray",takefocus="",relief=SUNKEN)
fr5.grid(row=1,column=2,sticky=(N,E,W,S))
#Canvas
canvas = Canvas(fr4,width=750, height=750)
canvas.pack()
#Turtle
turtle1=turtle.RawTurtle(canvas)
turtle1.color("blue")
turtle1.shape("turtle")
#Functions
def rectangle():
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
for i in range(4):
turtle1.forward(int(lenght.get()))
turtle1.left(90)
turtle1.end_fill()
def circle():
turtle1.begin_fill()
turtle1.pensize(int(pensize.get()))
colorchoices()
turtle1.circle(int(radius.get()))
turtle1.end_fill()
def triangle():
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
turtle1.forward(int(lenght.get()))
turtle1.left(120)
turtle1.forward(int(lenght.get()))
turtle1.left(120)
turtle1.forward(int(lenght.get()))
turtle1.end_fill()
def line100 ():
turtle1.penup()
turtle1.pensize(int(pensize.get()))
turtle1.forward(int(lenght.get()))
turtle1.pendown()
def linel90 ():
turtle1.penup()
turtle1.left(int(angle.get()))
turtle1.pendown()
def liner90 ():
turtle1.penup()
turtle1.pensize(int(pensize.get()))
turtle1.right(int(angle.get()))
turtle1.pendown()
def linebc100 ():
turtle1.penup()
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
turtle1.backward(int(lenght.get()))
turtle1.end_fill()
turtle1.pendown()
def line():
turtle1.begin_fill()
colorchoices()
turtle1.pensize(int(pensize.get()))
turtle1.forward(int(lenght.get()))
turtle1.end_fill()
def colorchoices():
selection=var.get()
for i in range(8):
if selection==1:
turtle1.fillcolor("red")
elif selection==2:
turtle1.fillcolor("blue")
elif selection==3:
turtle1.fillcolor("purple")
elif selection==4:
turtle1.fillcolor("yellow")
elif selection==5:
turtle1.fillcolor("orange")
elif selection==6:
turtle1.fillcolor("green")
elif selection==7:
turtle1.fillcolor("")
def clear():
turtle1.clear()
but1=Button(fr1,text="Clear",command=clear).pack(side=LEFT)
# shapes
shpc=PhotoImage(file="D://python//ımage/circle.png")
shptr=PhotoImage(file="D://python//ımage/rectangular.png")
shpsq=PhotoImage(file="D://python//ımage/square.png")
shpl=PhotoImage(file="D://python//ımage/line.png")
shphep=PhotoImage(file="D://python//ımage/shapes.png")
#Entry and labels
PenSize=Button(fr5,text="PenSize",font=("Helvetica",14),fg="black").grid(row=0,column=0,columnspan=1,sticky=W)
Angle=Button(fr5,text="Angle",font=("Helvetica",14),fg="black").grid(row=1,column=0,columnspan=1,sticky=W)
Radius=Button(fr5,text="Radius",font=("Helvetica",14),fg="black").grid(row=2,column=0,columnspan=1,sticky=W)
Lenght=Button(fr5,text="Lenght",font=("Helvetica",14),fg="black").grid(row=3,column=0,columnspan=1,sticky=W)
pensize=Entry(fr5)
angle=Entry(fr5)
radius=Entry(fr5)
lenght=Entry(fr5)
pensize.grid(row=0,column=1,columnspan=2,sticky=W)
angle.grid(row=1,column=1,columnspan=2,sticky=W)
radius.grid(row=2,column=1,columnspan=2,sticky=W)
lenght.grid(row=3,column=1,columnspan=2,sticky=W)
#optionmenu
ColorOption=Button(fr5,text="ColorOptions",font=("Helvetica",14),fg="black").grid(row=4,column=0,sticky=W)
R1 = Radiobutton(fr5, text="RED", variable=var, value=1,bg="red").grid(row=4,column=1,sticky=W)
R2 = Radiobutton(fr5, text="BLUE", variable=var, value=2,bg="blue").grid( row=4,column=2,sticky=W)
R3 = Radiobutton(fr5, text="PURPLE", variable=var, value=3,bg="purple").grid( row=4,column=3,sticky=W )
R4 = Radiobutton(fr5, text="YELLOW", variable=var, value=4,bg="yellow").grid( row=4,column=4,sticky=W)
R5 = Radiobutton(fr5, text="ORANGE", variable=var, value=5,bg="orange").grid( row=4,column=5,sticky=W )
R6 = Radiobutton(fr5, text="GREEN", variable=var, value=6,bg="green").grid( row=4,column=6,sticky=W)
R7 = Radiobutton(fr5, text="NO COLOR", variable=var, value=7).grid( row=4,column=7,sticky=W)
#Buttons
but1=Button(fr2,text="Forward",command=line100).grid(row=1,column=2,sticky=(N,E,W,S))
but1=Button(fr2,text="Backward",command=linebc100 ).grid(row=1,column=0,sticky=(N,E,W,S))
but1=Button(fr2,text="Turn90",command=linel90).grid(row=0,column=1,sticky=(N,E,W,S))
but1=Button(fr2,text="Turn(-90)",command=liner90).grid(row=2,column=1,sticky=(N,E,W,S))
#shp1=Label(fr5,text="SHAPES",image=shphep).pack(fill=X)
shp2=Button(fr3,text="Circle",height=200,width=200,image=shpc,command=circle).pack()
shp3=Button(fr3,text="Triangular",height=200,width=200,image=shptr,command=triangle).pack()
shp4=Button(fr3,text="Square",height=200,width=200,image=shpsq,command=rectangle).pack()
shp5=Button(fr3,text="Line",height=200,width=200,compound=LEFT,image=shpl,command=line).pack()
sc.deiconify()
sc.mainloop()
</code></pre>
| 0 | 2016-08-27T08:25:58Z | [
"python",
"tkinter",
"turtle-graphics"
] |
Tuple error (numpy) | 39,178,550 | <p>I padded my data using <code>np.pad(x,[(0,0)], mode='constant')</code> and got this error:</p>
<pre><code>ValueError: Unable to create correctly shaped tuple from [(0, 0).
</code></pre>
<p>My <code>x</code> has shape (21, 4) and I want to pad it to get a shape of (22,4).</p>
<p>Does anyone know what is happening?</p>
| 1 | 2016-08-27T07:20:46Z | 39,178,612 | <p>The rank of the first argument has to match the number of pairs in the second argument.</p>
<p>For example, observe that this gives the error that you see:</p>
<pre><code>>>> x = np.ones((21, 4))
>>> np.pad(x, [(0,0)], mode='constant')
Traceback (most recent call last):
[...snip...]
ValueError: Unable to create correctly shaped tuple from [(0, 0)]
</code></pre>
<p>The problem is that <code>x</code> has rank 2 but the second argument has only one pair, not two.</p>
<p>However, if we supply a second argument with two pairs, this succeeds:</p>
<pre><code>>>> x2 = np.pad(x, [(0,0), (0,0)], mode='constant')
</code></pre>
<p>To get the final dimension that you want, we have to pad the first dimension by 1. One way to do that is:</p>
<pre><code>>>> x2 = np.pad(x, [(0,1), (0,0)], mode='constant')
>>> x2.shape
(22, 4)
</code></pre>
| 0 | 2016-08-27T07:28:54Z | [
"python",
"numpy"
] |
Shipping python runtime with excel | 39,178,624 | <p>According to the xlwings website:-</p>
<p>Easy deployment: The receiver of an xlwings-powered spreadsheets only needs Python with minimal dependencies â or nothing at all when shipped with the Python runtime.</p>
<p>I have installed Anaconda and written some python code and run it from Excel using xlwings</p>
<p>I put this spreadsheet on a different computer than the one I developed on and placed the python.exe and a few dll's that got installed with Anaconda into a directory with the spreadsheet</p>
<p>I added the path to the environment variables so it could find python</p>
<p>The spreadsheet looked like it invoked python but got an overflow error</p>
<p>I'm trying to ship the spreadsheet in the leanest possible manner. I don't really want to have to get all users to install python</p>
<p>Is this approach possible and which files do I need to include?</p>
| 0 | 2016-08-27T07:30:19Z | 39,179,972 | <p>"When shipped with the Python runtime" is referring to the underdocumented approach of using a freezer (like py2exe or cx_Freeze) and creating a self-contained directory that includes the whole Python dependency.</p>
<p>There is the standalone version of the <a href="https://github.com/ZoomerAnalytics/xlwings/tree/master/examples/fibonacci" rel="nofollow">Fibonacci example</a> where you can see how it is being done. You can also download the respective "standalone" sample from <a href="http://www.xlwings.org/examples" rel="nofollow">http://www.xlwings.org/examples</a>.</p>
| 0 | 2016-08-27T10:16:02Z | [
"python",
"xlwings"
] |
How to filter a nested dictionary (pythonic way) for a specific value using map or filter instead of list comprehensions? | 39,178,715 | <p>I've a nested dictionary.</p>
<pre><code>>>> foo = {'m': {'a': 10}, 'n': {'a': 20}}
>>>
</code></pre>
<p>I'd like to filter specific values, based on the values of 'a'.</p>
<p>I can use list comprehensions for the purpose.</p>
<pre><code>>>> [foo[n] for n in foo if foo[n]['a'] == 10]
[{'a': 10}]
>>>
</code></pre>
<p>Using list alone gives me the elements from foo (and not the values of the elements) - as expected:</p>
<pre><code>>>> list(filter(lambda x: foo[x] if foo[x]['a']==10 else None,foo))
['m']
>>>
</code></pre>
<p>Using map returns me unwanted 'None' values:</p>
<pre><code>>>> list(map(lambda x: foo[x] if foo[x]['a']==10 else None,foo))
[{'a': 10}, None]
>>>
</code></pre>
<p>Combining these two, I can fetch the desired value. But I guess foo is iterated twice - once each for filter and map. The list comprehension solution needs me to iterate just once.</p>
<pre><code>>>> list(map(lambda t: foo[t], filter(lambda x: foo[x] if foo[x]['a']==10 else None,foo)))
[{'a': 10}]
>>>
</code></pre>
<p>Here's another approach using just filter. This gives me the desired values but I'm not sure if iterating over values of a dictionary is a good/pythonic approach:</p>
<pre><code>>>> list(filter(lambda x: x if x['a'] == 10 else None, foo.values()))
[{'a': 10}]
>>>
</code></pre>
<p>I'd like to know if:</p>
<ol>
<li>What's the pythonic/recommended approach for this scenario?</li>
<li>If the last example using filter on dictionary values is an acceptable?</li>
</ol>
<p>Regards</p>
<p>Sharad</p>
| 1 | 2016-08-27T07:42:43Z | 39,178,728 | <p>A list comprehension can do this beautifully.</p>
<pre><code>>>> foo = {'m': {'a': 10}, 'n': {'a': 20}}
>>> [v for v in foo.values() if 10 in v.values()]
[{'a': 10}]
</code></pre>
<p>You don't need the for loop or the list comprehension if you are matching against a known key in the dictionary.</p>
<pre><code>In [15]: if 10 in foo['m'].values():
...: result = [foo['m']]
...:
In [16]: result
Out[16]: [{'a': 10}]
</code></pre>
| 2 | 2016-08-27T07:45:18Z | [
"python",
"list",
"dictionary",
"list-comprehension",
"python-3.5"
] |
How to filter a nested dictionary (pythonic way) for a specific value using map or filter instead of list comprehensions? | 39,178,715 | <p>I've a nested dictionary.</p>
<pre><code>>>> foo = {'m': {'a': 10}, 'n': {'a': 20}}
>>>
</code></pre>
<p>I'd like to filter specific values, based on the values of 'a'.</p>
<p>I can use list comprehensions for the purpose.</p>
<pre><code>>>> [foo[n] for n in foo if foo[n]['a'] == 10]
[{'a': 10}]
>>>
</code></pre>
<p>Using list alone gives me the elements from foo (and not the values of the elements) - as expected:</p>
<pre><code>>>> list(filter(lambda x: foo[x] if foo[x]['a']==10 else None,foo))
['m']
>>>
</code></pre>
<p>Using map returns me unwanted 'None' values:</p>
<pre><code>>>> list(map(lambda x: foo[x] if foo[x]['a']==10 else None,foo))
[{'a': 10}, None]
>>>
</code></pre>
<p>Combining these two, I can fetch the desired value. But I guess foo is iterated twice - once each for filter and map. The list comprehension solution needs me to iterate just once.</p>
<pre><code>>>> list(map(lambda t: foo[t], filter(lambda x: foo[x] if foo[x]['a']==10 else None,foo)))
[{'a': 10}]
>>>
</code></pre>
<p>Here's another approach using just filter. This gives me the desired values but I'm not sure if iterating over values of a dictionary is a good/pythonic approach:</p>
<pre><code>>>> list(filter(lambda x: x if x['a'] == 10 else None, foo.values()))
[{'a': 10}]
>>>
</code></pre>
<p>I'd like to know if:</p>
<ol>
<li>What's the pythonic/recommended approach for this scenario?</li>
<li>If the last example using filter on dictionary values is an acceptable?</li>
</ol>
<p>Regards</p>
<p>Sharad</p>
| 1 | 2016-08-27T07:42:43Z | 39,183,551 | <p>If you want to return the full nested dictionary if it contains <code>a</code>, a list comprehension is probably the cleanest way. Your initial list comprehension would work:</p>
<pre><code>[foo[n] for n in foo if foo[n]['a'] == 10]
</code></pre>
<p>You can also avoid the lookup on <code>n</code> with:</p>
<pre><code>[d for d in foo.values() if d['a'] == 10]
</code></pre>
<p>List comprehensions are generally considered more Pythonic than <code>map</code> or <code>filter</code> related approaches for simpler problems like this, though <code>map</code> and <code>filter</code> certainly have their place if you're using a pre-defined function.</p>
<blockquote>
<p>This gives me the desired values but I'm not sure if iterating over values of a dictionary is a good/pythonic approach.</p>
</blockquote>
<p>If you want to return all values of a dictionary that meet a certain criteria, I'm not sure how you would be able to get around <em>not</em> iterating over the values of a dictionary.</p>
<p>For a filter-based approach, I would do it as:</p>
<pre><code>list(filter(lambda x: x['a'] == 10, foo.values()))
</code></pre>
<p>There's no need for the <code>if-else</code> in your original code.</p>
| 1 | 2016-08-27T16:53:10Z | [
"python",
"list",
"dictionary",
"list-comprehension",
"python-3.5"
] |
Access docker image through web server | 39,178,736 | <p>I am using a docker image and I can successfully access it and run it through a python script from my host machine. I am using sidomo for that purpose. The script works fine locally but doesn't give any output when I run it on server. Even the docker images command doesn't give correct output on server. The output is:</p>
<pre><code>Cannot connect to the Docker daemon. Is the docker daemon running on this host?
</code></pre>
<p>What permissions do I need to change in order to access my docker image from server? I only need the output from the docker program in my web application. </p>
| 0 | 2016-08-27T07:45:39Z | 39,178,812 | <p>Accessing the docker daemon remotely is dangerous. It is equivalent to root access. This is why the daemon's socket can be accessed by root and on most setups the members of the <code>docker</code> group only.</p>
<p>Now I'm at a point where I'm unsure to tell you how to allow access for your application. You don't seem to have deep experience in Linux permission which would be required to secure your web application.</p>
<p>So it giv only the concept, not the commmand: add the user your web application is running as to the docker` group.</p>
<p>And one last reminder: Secure the web application! It will be the only security you have for your sever then.</p>
| 0 | 2016-08-27T07:54:50Z | [
"python",
"web",
"docker",
"server",
"daemon"
] |
Python Convert Bytes Literal To Image | 39,178,896 | <p>In Python3 I am working on a music playing application. I'm using a library called TinyTag to get metadata from the music files, like the title and artist. It also supports getting the album art. When the art is retrieved it loads it as what I believe is called a bytes literal (I'm unfamiliar with it). I was wondering how to turn this data into an image. Here's the code:</p>
<pre><code>from tinytag import TinyTag
tag = TinyTag.get("/path/to/file.mp3", image=True)
image_data = tag.get_image()
print(image_data)
</code></pre>
<p>The image data is a massive sting prefaced by the letter "b". It looks like this:</p>
<pre><code>b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01...'
</code></pre>
<p>but is much longer. How do I convert this into the album cover image. What libraries are need and how can it be done?</p>
| 0 | 2016-08-27T08:05:18Z | 39,179,061 | <p>The string you see are the contents of an image file. You can just save the string directly to a file:</p>
<pre><code>$ file /tmp/file.mp3
/tmp/file.mp3: Audio file with ID3 version 2.3.0, contains: MPEG ADTS, layer III, v1, 128 kbps, 44.1 kHz, JntStereo
$ ipython
Python 2.7.12 (default, Aug 9 2016, 15:48:18)
Type "copyright", "credits" or "license" for more information.
IPython 3.2.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: from tinytag import TinyTag
In [2]: tag = TinyTag.get("/tmp/file.mp3", image=True)
In [3]: image_data = tag.get_image()
In [4]: type(image_data)
Out[4]: str
In [5]: image_data[:20]
Out[5]: '\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00'
In [6]: with open("/tmp/album_art.jpg", "w") as f:
...: f.write(image_data)
...:
In [7]: exit()
$ file /tmp/album_art.jpg
/tmp/album_art.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, Exif Standard: [TIFF image data, big-endian, direntries=7, orientation=upper-left, xresolution=98, yresolution=106, resolutionunit=2, software=Adobe Photoshop CS2 Windows, datetime=2008:04:02 00:23:04], baseline, precision 8, 320x300, frames 3
</code></pre>
<p>If you are using python3, you will have to explicitly specify 'wb' in the mode, since you get a stream of bytes instead:</p>
<pre><code>$ python3
Python 3.5.1 (default, Aug 9 2016, 15:35:51)
[GCC 6.1.1 20160621 (Red Hat 6.1.1-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from tinytag import TinyTag
>>> tag = TinyTag.get("/tmp/file.mp3", image=True)
>>> image_data = tag.get_image()
>>> type(image_data)
<class 'bytes'>
>>> image_data[:20]
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00'
>>> with open("/tmp/album_art.jpg", "wb") as f:
... f.write(image_data)
...
64790
>>> exit()
$ file /tmp/album_art.jpg
/tmp/album_art.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, Exif Standard: [TIFF image data, big-endian, direntries=7, orientation=upper-left, xresolution=98, yresolution=106, resolutionunit=2, software=Adobe Photoshop CS2 Windows, datetime=2008:04:02 00:23:04], baseline, precision 8, 320x300, frames 3
</code></pre>
| 3 | 2016-08-27T08:26:43Z | [
"python",
"python-3.x",
"music-player"
] |
Python sort (json) list by calculated value | 39,178,905 | <p>I have originally a JSON format with products and the challenge is to sort this list by the best price per unit (prdata3, prdata2, prdata1): </p>
<pre><code>{'prdata3': {'variation': 'stand', 'price': '78 54', 'amount': '6',
'url': 'https://www.productwebaddress.com/3'},
'prdata2': {'variation': 'stand', 'price': '15 24', 'amount': '1',
'url': 'https://www.productwebaddress.com/2'},
'prdata1': {'variation': 'vc', 'price': '78 54', 'amount': '12',
'url': 'https://www.productwebaddress.com/1'}}
</code></pre>
<p>The price needs to be divided by the amount and the list needs to be sorted by this value, so in my example the output need to be (prdata1 (6,55), prdata3 (13,09), prdata2 (15,24)):</p>
<pre><code>{'prdata1': {'variation': 'vc', 'price': '78 54', 'amount': '12', 'url': 'https://www.productwebaddress.com/1'}, 'prdata3': {'variation': 'stand', 'price': '78 54', 'amount': '6', 'url': 'https://www.productwebaddress.com/3'}, 'prdata2': {'variation': 'stand', 'price': '15 24', 'amount': '1', 'url': 'https://www.productwebaddress.com/2'}}
</code></pre>
<p>What is the best strategy here? I gave my best to first go in there with "for each", looking for the price, replace the space with a dot, divide it with the amount and now use this result to sort my list with something like: <code>sorted(mylist.items(), key=lambda t: t[1])</code> ... but my result as key, right? </p>
| -2 | 2016-08-27T08:06:11Z | 39,179,105 | <p>You can't sort a dictionary, as dictionary have no order. </p>
<p>But you can do the following:</p>
<pre><code>print sorted(a.items(),key=lambda x:float(x[1]['price'])/int(x[1]['amount']))
</code></pre>
<p>Output:</p>
<pre><code>[('prdata1', {'url': 'https://www.productwebaddress.com/1', 'price': '78.54', 'amount': '12', 'variation': 'vc'}),
('prdata3', {'url': 'https://www.productwebaddress.com/3', 'price': '78.54', 'amount': '6', 'variation': 'stand'}),
('prdata2', {'url': 'https://www.productwebaddress.com/2', 'price': '15.24', 'amount': '1', 'variation': 'stand'})]
</code></pre>
<p>And, you can use <code>collections.OrderedDict</code> to retain the dictionary structure if it really matters. </p>
<pre><code>from collections import OrderedDict
print OrderedDict(sorted(a.items(),key=lambda x:float(x[1]['price'])/int(x[1]['amount'])))
</code></pre>
<p>Output:</p>
<pre><code>OrderedDict([('prdata1', {'url': 'https://www.productwebaddress.com/1', 'price': '78.54', 'amount': '12', 'variation': 'vc'}),
('prdata3', {'url': 'https://www.productwebaddress.com/3', 'price': '78.54', 'amount': '6', 'variation': 'stand'}),
('prdata2', {'url': 'https://www.productwebaddress.com/2', 'price': '15.24', 'amount': '1', 'variation': 'stand'})])
</code></pre>
| 0 | 2016-08-27T08:31:25Z | [
"python",
"json",
"sorting"
] |
Python sort (json) list by calculated value | 39,178,905 | <p>I have originally a JSON format with products and the challenge is to sort this list by the best price per unit (prdata3, prdata2, prdata1): </p>
<pre><code>{'prdata3': {'variation': 'stand', 'price': '78 54', 'amount': '6',
'url': 'https://www.productwebaddress.com/3'},
'prdata2': {'variation': 'stand', 'price': '15 24', 'amount': '1',
'url': 'https://www.productwebaddress.com/2'},
'prdata1': {'variation': 'vc', 'price': '78 54', 'amount': '12',
'url': 'https://www.productwebaddress.com/1'}}
</code></pre>
<p>The price needs to be divided by the amount and the list needs to be sorted by this value, so in my example the output need to be (prdata1 (6,55), prdata3 (13,09), prdata2 (15,24)):</p>
<pre><code>{'prdata1': {'variation': 'vc', 'price': '78 54', 'amount': '12', 'url': 'https://www.productwebaddress.com/1'}, 'prdata3': {'variation': 'stand', 'price': '78 54', 'amount': '6', 'url': 'https://www.productwebaddress.com/3'}, 'prdata2': {'variation': 'stand', 'price': '15 24', 'amount': '1', 'url': 'https://www.productwebaddress.com/2'}}
</code></pre>
<p>What is the best strategy here? I gave my best to first go in there with "for each", looking for the price, replace the space with a dot, divide it with the amount and now use this result to sort my list with something like: <code>sorted(mylist.items(), key=lambda t: t[1])</code> ... but my result as key, right? </p>
| -2 | 2016-08-27T08:06:11Z | 39,179,111 | <p>Welcome to Stack Overflow.</p>
<p>I would be nice if you could show us a code snippet, so we can look it over and see where you could be stuck.</p>
<p>This might be a one liner, because of the clear specification, it would be something like (pseudo code, won't run): </p>
<p><code>sorted(data, key=lambda x: float(x['price'].replace(' ', '.')) / int(x['amount']))</code></p>
<p>I hope this helps, but if it doesn't, please provide some of your code.</p>
| 0 | 2016-08-27T08:31:39Z | [
"python",
"json",
"sorting"
] |
How do I adjust tooltip in Pygal? | 39,178,949 | <p>I tried to produce a bar chart that visualizes the most-starred projects on GitHub. I added <code>'label'</code> and <code>'xlink'</code> inside tooltips, however, <code>'label'</code> contents are not very well fit in for some items, also, some links are not shown up in certain projects' tooltip. See below,</p>
<p><a href="http://i.stack.imgur.com/WtchD.png" rel="nofollow"><img src="http://i.stack.imgur.com/WtchD.png" alt="enter image description here"></a></p>
<p>Below is the Python code using Pygal module, run it and see the .svg file yourself.</p>
<pre><code>import requests, pygal
url = 'https://api.github.com/search/repositories?q=language:python&sort=star'
r = requests.get(url)
repo_list = r.json()['items']
names, stars = [], []
for k in repo_list:
names.append(k['name'])
temp = {
'value': k['stargazers_count'],
'label': k['description'],
'xlink': k['html_url'],
}
stars.append(temp)
my_config = pygal.Config()
my_config.x_label_rotation = 45
chart = pygal.Bar(my_config)
chart.title = 'GitHub, Python Most Starred Projects'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('MyFile.svg', force_uri_protocol = 'http')
</code></pre>
<p>How do I solve this problem, either by adjusting font size of tooltip or tooltip window size?</p>
| 2 | 2016-08-27T08:11:01Z | 39,183,446 | <p>I don't think there's a clean way to do this; I think you'd need to modify the .svg file directly. There's an <a href="https://github.com/Kozea/pygal/issues/324" rel="nofollow">open issue</a> on the Pygal project asking this question. Someone seems to have found <a href="https://github.com/Kozea/pygal/issues/258" rel="nofollow">a solution</a> using <code>\n</code> and the <code>force_uri_protocol='http'</code>, but that doesn't work for me. On my machine <code>\n</code> just gets converted to a single space.</p>
<p>The best I could come up with is truncating the description to a certain number of characters, something like this:</p>
<pre><code>temp = {
'value': k['stargazers_count'],
'label': k['description'][:80] + "..." ,
'xlink': k['html_url'],
}
</code></pre>
<p>If you like this solution you can add some logic so short labels don't have the ellipsis at the end. I think this is the solution I'll use next time I run into this issue.</p>
| 1 | 2016-08-27T16:42:12Z | [
"python",
"pygal"
] |
Crawl a wikipedia page in python and store it in a .csv file | 39,178,984 | <p>This is my python script code</p>
<pre><code>from bs4 import BeautifulSoup
import requests
url='https://en.wikipedia.org/wiki/List_of_Pok%C3%A9mon'
source_code=requests.get(url)
print(url)
plain_text=source_code.text
soup=BeautifulSoup(plain_text,"html.parser")
print("hello")
f = open('pokemons.csv', 'w')
for table2 in soup.findAll('table'):
print("yash")
for i in table2.findAll('tbody'):
print("here")
for link in i.findAll('tr'):
for x in link.findAll('td'):
for y in x.findAll('a'):
z=y.get('href')
print(z)
#f.write(link)
f.close()
</code></pre>
<p>All i want to do is crawl all the pokemons name from this wiki link
<a href="https://en.wikipedia.org/wiki/List_of_Pok%C3%A9mon" rel="nofollow">https://en.wikipedia.org/wiki/List_of_Pok%C3%A9mon</a>
but problem here is i am unable to get into the specified table i. e the table in which the all the pokemons names are stored but im my above code i m travelling through alll the table and trying to acces the "tbody" tag so that i will access "tr" tags in it but it not happening the same way !! tell me my mistake.</p>
| 0 | 2016-08-27T08:18:28Z | 39,180,484 | <p>The <em>tbody</em> is added by the browser so not in the actual source returned by requests so your code could never find anything using it.</p>
<p>All you need to do is get every <em>anchor</em> with a <em>title</em> attribute in each row:</p>
<pre><code>with open('pokemons.csv', 'w') as f:
table = soup.select_one("table.wikitable.sortable")
for a in table.select("tr td a[title]"):
f.write(a.text.encode("utf-8") + "\n")
</code></pre>
<p>That gives you 761 names, one per line.</p>
<p>If you were to use find_all and find, it would be like: </p>
<pre><code> # get all orws
for tr in table.find_all("tr"):
# see if there is an anchor inside with a title attribute
a = tr.find("a", title=True)
# if there is write the text
if a:
f.write(tr.find("a", title=True).text.encode("utf-8") + "\n")
</code></pre>
| 1 | 2016-08-27T11:12:33Z | [
"python",
"beautifulsoup",
"web-crawler"
] |
python loop x + 1 times in a list of list until number y | 39,179,018 | <p>What I want is the list in <code>num</code> loops <code>x + 1</code> everytime until <code>y</code> is generated(and loops is stoped), which is a large number.</p>
<pre><code>def loop_num(y):
num = []
num.append([1])
num.append([2,3])
num.append([4,5,6])
num.append([7,8,9,10])
... #stop append when y in the appended list
#if y = 9, then `append [7,8]` and `return num`
return num
# something like[[1 item], [2items], [3items], ...]
# the number append to the list can be a random number or ascending integers.
</code></pre>
<p>sorry for not clear</p>
| -1 | 2016-08-27T08:21:14Z | 39,179,192 | <p>I am not sure what is your question. But I am assuming that you have done something similar to this.</p>
<pre><code>x=[[1], [2,3], [4,5,6]]
b=[str(a)+' items' for a in [j for i in x for j in i]]
</code></pre>
<p>And what you are looking for is this.</p>
<pre><code>c=max([j for i in x for j in i])
</code></pre>
<p>to do this.</p>
<pre><code>z=[]
z.append(str(c)+' items')
</code></pre>
| 0 | 2016-08-27T08:41:26Z | [
"python",
"list",
"loops",
"random",
"iteratee"
] |
python loop x + 1 times in a list of list until number y | 39,179,018 | <p>What I want is the list in <code>num</code> loops <code>x + 1</code> everytime until <code>y</code> is generated(and loops is stoped), which is a large number.</p>
<pre><code>def loop_num(y):
num = []
num.append([1])
num.append([2,3])
num.append([4,5,6])
num.append([7,8,9,10])
... #stop append when y in the appended list
#if y = 9, then `append [7,8]` and `return num`
return num
# something like[[1 item], [2items], [3items], ...]
# the number append to the list can be a random number or ascending integers.
</code></pre>
<p>sorry for not clear</p>
| -1 | 2016-08-27T08:21:14Z | 39,179,242 | <p>Two <a href="https://docs.python.org/2/library/itertools.html#itertools.count" rel="nofollow"><code>itertools.count</code></a> objects should do what you want:</p>
<pre><code>from itertools import count
def loop_num(y):
counter, x = count(1), count(1)
n = 0
while n < y:
num = []
for i in range(next(x)):
num.append(next(counter))
if num[-1] == y:
break
yield num
n = num[-1]
</code></pre>
<p>Output:</p>
<pre><code>>>> list(loop_num(100))
[[1],
[2, 3],
[4, 5, 6],
[7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21],
[22, 23, 24, 25, 26, 27, 28],
[29, 30, 31, 32, 33, 34, 35, 36],
[37, 38, 39, 40, 41, 42, 43, 44, 45],
[46, 47, 48, 49, 50, 51, 52, 53, 54, 55],
[56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66],
[67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78],
[79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91],
[92, 93, 94, 95, 96, 97, 98, 99, 100]]
</code></pre>
| 1 | 2016-08-27T08:49:00Z | [
"python",
"list",
"loops",
"random",
"iteratee"
] |
python loop x + 1 times in a list of list until number y | 39,179,018 | <p>What I want is the list in <code>num</code> loops <code>x + 1</code> everytime until <code>y</code> is generated(and loops is stoped), which is a large number.</p>
<pre><code>def loop_num(y):
num = []
num.append([1])
num.append([2,3])
num.append([4,5,6])
num.append([7,8,9,10])
... #stop append when y in the appended list
#if y = 9, then `append [7,8]` and `return num`
return num
# something like[[1 item], [2items], [3items], ...]
# the number append to the list can be a random number or ascending integers.
</code></pre>
<p>sorry for not clear</p>
| -1 | 2016-08-27T08:21:14Z | 39,180,159 | <pre><code>def loop_num(x):
i=1
cnt=0
sum=0
while sum<x:
sum+=i
cnt=cnt+1
i=i+1
num=[ [] for x in range(cnt)]
count=0
sz=1
init=1
while(count<cnt):
cur=1
while(cur<=sz):
num[count].append(init)
init=init+1
cur=cur+1
count=count+1
sz=sz+1;
return num
</code></pre>
<p>From a python file you may run it from command line (say filename is test.py)</p>
<pre><code>python -c 'import test; print test.loop_num(55)'
</code></pre>
| 1 | 2016-08-27T10:36:43Z | [
"python",
"list",
"loops",
"random",
"iteratee"
] |
Changing part of a message's color in tkinter messagebox | 39,179,022 | <p>I have a TKinter messagebox like the one below. I would like to change <strong>part</strong> of the message to a different color. For example in the messagebox below I would like the language to be <code>Blue</code>. Is this possible?</p>
<p><a href="http://i.stack.imgur.com/wekJQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/wekJQ.png" alt="enter image description here"></a></p>
| 0 | 2016-08-27T08:21:26Z | 39,180,519 | <p>It's not possible to change such options of <a href="http://effbot.org/tkinterbook/tkinter-standard-dialogs.htm" rel="nofollow">Tkinter Standard Dialogs</a>. You need to create your own dialog. You'll also need to separate the text parts. I've tried to make something similar in the image that the <a href="http://stackoverflow.com/users/1480488/darthopto">OP</a> has posted above:</p>
<pre><code>from tkinter import *
root = Tk()
def choosefunc(option):
if option == "cancel":
print("Cancel choosen")
else:
print("OK choosen")
def popupfunc():
tl = Toplevel(root)
tl.title("Languages")
frame = Frame(tl)
frame.grid()
canvas = Canvas(frame, width=100, height=130)
canvas.grid(row=1, column=0)
imgvar = PhotoImage(file="pyrocket.png")
canvas.create_image(50,70, image=imgvar)
canvas.image = imgvar
msgbody1 = Label(frame, text="The", font=("Times New Roman", 20, "bold"))
msgbody1.grid(row=1, column=1, sticky=N)
lang = Label(frame, text="language(s)", font=("Times New Roman", 20, "bold"), fg='blue')
lang.grid(row=1, column=2, sticky=N)
msgbody2 = Label(frame, text="of this country is: Arabic", font=("Times New Roman", 20, "bold"))
msgbody2.grid(row=1, column=3, sticky=N)
cancelbttn = Button(frame, text="Cancel", command=lambda: choosefunc("cancel"), width=10)
cancelbttn.grid(row=2, column=3)
okbttn = Button(frame, text="OK", command=lambda: choosefunc("ok"), width=10)
okbttn.grid(row=2, column=4)
label = Label(root, text="Click to proceed:")
label.grid()
button = Button(root, text="Click", command=popupfunc)
button.grid()
</code></pre>
<p>(Image URL: <a href="http://imgur.com/a/Nf75v" rel="nofollow">http://imgur.com/a/Nf75v</a>)</p>
| 2 | 2016-08-27T11:16:40Z | [
"python",
"python-3.x",
"tkinter"
] |
How to detect HTTP response status code and set a proxy accordingly in scrapy? | 39,179,041 | <p>Is there a way to set a new proxy ip (e.g.: from a pool) according to the HTTP response status code?
For example, start up with an IP form an IP list till it gets a 503 response (or another http error code), then use the next one till it gets blockedï¼and so on, something like:</p>
<pre><code>if http_status_code in [403, 503, ..., n]:
proxy_ip = 'new ip'
# Then keep using it till it's gets another error code
</code></pre>
<p>Any ideas?</p>
| 0 | 2016-08-27T08:23:59Z | 39,179,534 | <p>Scrapy has a downloader middleware which is enabled by default to handle proxies. It's called <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware" rel="nofollow">HTTP Proxy Middleware</a> and what it does is allows you to supply meta key <code>proxy</code> to your <code>Request</code> and use that proxy for this request.</p>
<p>There are few ways of doing this.<br>
First one, straight-forward just use it in your spider code:</p>
<pre><code>def parse(self, response):
if response.status in range(400, 600):
return Request(response.url,
meta={'proxy': 'http://myproxy:8010'}
dont_filter=True) # you need to ignore filtering because you already did one request to this url
</code></pre>
<p>Another more elegant way would be to use custom downloader middleware which would handle this for multiple callbacks and keep your spider code cleaner:</p>
<pre><code>from project.settings import PROXY_URL
class MyDM(object):
def process_response(self, request, response, spider):
if response.status in range(400, 600):
logging.debug('retrying [{}]{} with proxy: {}'.format(response.status, response.url, PROXY_URL)
return Request(response.url,
meta={'proxy': PROXY_URL}
dont_filter=True)
return response
</code></pre>
<p>Note that by default scrapy doesn't let through any response codes other than <code>200</code> ones. Scrapy automatically handles redirect codes <code>300</code> with <code>Redirect middleware</code> and raises request errors on <code>400</code> and <code>500</code> with HttpError middleware. To handle requests other than 200 you need to either:</p>
<p>Specify that in Request Meta: </p>
<pre><code>Request(url, meta={'handle_httpstatus_list': [404,505]})
# or for all
Request(url, meta={'handle_httpstatus_all': True})
</code></pre>
<p>Set a project/spider wide parameters:</p>
<pre><code>HTTPERROR_ALLOW_ALL = True # for all
HTTPERROR_ALLOWED_CODES = [404, 505] # for specific
</code></pre>
<p>as per <a href="http://doc.scrapy.org/en/latest/topics/spider-middleware.html#httperror-allowed-codes" rel="nofollow">http://doc.scrapy.org/en/latest/topics/spider-middleware.html#httperror-allowed-codes</a></p>
| 0 | 2016-08-27T09:27:18Z | [
"python",
"scrapy"
] |
How to find permutations in a list then remove them? | 39,179,226 | <p>I'm trying to find a permutation of another number in this txt file and then add them to a list:</p>
<pre><code>167
168
148
143
289
194
683
491
</code></pre>
<p>In this file, the permutations are 491 and 194.</p>
<p>This is my code:</p>
<pre><code>numberList = []
file = open("file.txt", "r")
for line in file:
numberList.append(line)
</code></pre>
<p>Now they're added to <code>numberList</code>, how do I remove them (491 and 194) from this list.</p>
| 1 | 2016-08-27T08:46:20Z | 39,179,365 | <p>Ok, let's do a bit of group theory:</p>
<p>assume you can decompose your numbers x into digits X[i] (removing the <code>\n</code> is really trivial, and surely someone else will cover this). </p>
<p>Then we know that, by how the decimal system works,</p>
<p><img src="http://i.stack.imgur.com/9ut2V.png" alt="$$x = \sum_{i=0}^{\log_{10} x} x[i] 10^i$$"></p>
<p>what we need to find is a function y=f(x) that maps x'es that are permutations of the same number to the same y, but x'es that aren't permutations to different y. </p>
<p>we can use the fact that the prime factorization of different numbers is different, and simply find the sum over exponents of a prime that isn't a digit (and larger than the length of the number*digits). This get's easier if we assume less than 9 digits, so we'll do that.</p>
<p>for this example, let's stick to 17 (which further limits our number of digits, but oh well).</p>
<p><img src="http://i.stack.imgur.com/Q1Yhi.png" alt="$$y= f(x) = \sum_{i=0}^{6} 17^{x[i]}$$"></p>
<p>so, now you'd use that function as <em>comparison key</em> in a python <code>set</code> and be done.</p>
<p>So, very naively (and very untested):</p>
<pre><code>class permutation(object):
def __init__(self, x):
"""
we'll assume x is an integer
"""
digits = str(x)
self.original = x
self._hash = sum([17**int(digit) for digit in digits])
def __hash__(self):
return self._hash
def __eq__(self,other):
return self._hash == hash(other)
def __ne__(self,other):
return self._hash != hash(other)
permutation_free = set()
file = open("file.txt", "r")
for line in file:
x = int(line)
permutation_free.add(permutation(x))
print [perm.original for perm in permutation_free]
</code></pre>
<p><strong>EDIT:</strong> even tested it. </p>
| 7 | 2016-08-27T09:04:07Z | [
"python",
"permutation"
] |
How to find permutations in a list then remove them? | 39,179,226 | <p>I'm trying to find a permutation of another number in this txt file and then add them to a list:</p>
<pre><code>167
168
148
143
289
194
683
491
</code></pre>
<p>In this file, the permutations are 491 and 194.</p>
<p>This is my code:</p>
<pre><code>numberList = []
file = open("file.txt", "r")
for line in file:
numberList.append(line)
</code></pre>
<p>Now they're added to <code>numberList</code>, how do I remove them (491 and 194) from this list.</p>
| 1 | 2016-08-27T08:46:20Z | 39,179,424 | <p>There seem to be two problems: How to read numbers from a text file, and how to detect and filter out the duplicates w.r.t. permutations. For the first, you can use <code>strip</code> to get rid of the <code>\n</code> and convert to <code>int</code> to get actual numbers (although when using <code>int</code>, the first step is not really necessary). For filtering out the permutations, I suggest using a dictionary, associating each number with itself in sorted order. Since each permutation will be the same after sorting, this will group numbers that are permutations of each other. If you want to retain the original order, use <code>collections.OrderedDict</code>.</p>
<pre><code>import collections
numbers = collections.OrderedDict()
with open("file.txt") as f:
for line in map(str.strip, f):
print(line)
key = ''.join(sorted(line))
if key not in numbers:
numbers[key] = []
numbers[key].append(int(line))
print(numbers)
</code></pre>
<p>Afterwards, <code>numbers</code> is </p>
<pre><code>OrderedDict([('167', [167]), ('168', [168]), ('148', [148]), ('134', [143]), ('289', [289]), ('149', [194, 491]), ('368', [683])])
</code></pre>
<p>To get the ordered sequence of numbers with no "permutation-duplicates", just get the first element from each of the value-lists:</p>
<pre><code>>>> [v[0] for v in numbers.values()]
[167, 168, 148, 143, 289, 194, 683]
</code></pre>
<p>In case you want to remove <em>both</em> the duplicates, you can add an accordant condition:</p>
<pre><code>>>> [v[0] for v in numbers.values() if len(v) == 1]
[167, 168, 148, 143, 289, 683]
</code></pre>
| 4 | 2016-08-27T09:10:37Z | [
"python",
"permutation"
] |
How to find permutations in a list then remove them? | 39,179,226 | <p>I'm trying to find a permutation of another number in this txt file and then add them to a list:</p>
<pre><code>167
168
148
143
289
194
683
491
</code></pre>
<p>In this file, the permutations are 491 and 194.</p>
<p>This is my code:</p>
<pre><code>numberList = []
file = open("file.txt", "r")
for line in file:
numberList.append(line)
</code></pre>
<p>Now they're added to <code>numberList</code>, how do I remove them (491 and 194) from this list.</p>
| 1 | 2016-08-27T08:46:20Z | 39,179,633 | <p>So, you can do this in just 3 additional lines of code:</p>
<ol>
<li>Sort each item in the list so that permutations will match</li>
<li>Check each item on the list to see where there are permutations, and create a list of those indices</li>
<li>Create the new list do not add the indices that were identified as permutations:</li>
</ol>
<p>So the whole program will look like this:</p>
<pre><code>numberList = []
file = open("file.txt", "r")
for line in file:
numberList.append(line.strip())
x = [sorted(y) for y in numberList]
indices = [i for i, item in enumerate(x) if x.count(item) > 1]
numberList = [item for i, item in enumerate(numberList) if i not in indices]
</code></pre>
<p>Results:</p>
<pre><code>>>> numberList
[167, 168, 148, 143, 289, 683]
>>>
</code></pre>
| 1 | 2016-08-27T09:38:28Z | [
"python",
"permutation"
] |
Counter within django loop | 39,179,257 | <p>I have the following django / html code:</p>
<pre><code>{% for x in fixtures %}
<div id="match1" style="display:block">{{x.home_team.teamname}}</div>
{% endfor %}
</code></pre>
<p>The above simply displays all teams from a set of fixtures. It works perfectly as it stands. However, I would like the div id to go up 1 each time it runs through the loop. I.e "match1" then "match2" then "match3" etc.</p>
<p>I am assuming javascript is my friend here? but some direction would be appreciated.</p>
<p>Many thanks in advance for any assistance :)</p>
| 0 | 2016-08-27T08:51:01Z | 39,179,296 | <p>There's no need for javascript. You can use the <code>forloop.counter</code> variable:</p>
<pre><code>{% for x in fixtures %}
<div id="match{{ forloop.counter }}" style="display:block">{{x.home_team.teamname}}</div>
{% endfor %}
</code></pre>
<p>The various variables available in a for loop are described in <a href="https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#for" rel="nofollow">the docs</a>. </p>
| 3 | 2016-08-27T08:56:14Z | [
"javascript",
"python",
"django"
] |
SQLAlchemy update neither works nor raises errors | 39,179,260 | <p>I want to update the <code>email</code> column of the <code>user</code> table where <code>id == 3</code>. Below code does not update any rows or even raise any errors. Where could the problem be?</p>
<pre><code>from sqlalchemy import update
@app.route('/testupdate/')
def testupdate():
stmt = update(user).where(user.id==3).values(email='a@b')
db.session.commit()
return 'done'
</code></pre>
| 0 | 2016-08-27T08:51:18Z | 39,184,526 | <p>The problem is that no SQL was emitted to the database.</p>
<pre><code> stmt = update(user).where(user.id==3).values(email='a@b')
</code></pre>
<p>Does not actually execute the statement, it just creates it. To actually execute it you have to pass it to</p>
<pre><code> db.session.execute(stmt)
</code></pre>
<p>and then commit. You could also instead just use the <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html" rel="nofollow"><code>Query</code></a> API of the session:</p>
<pre><code> db.session.query(user).\
filter_by(id=3).\
update({user.email: 'a@b'},
synchronize_session='evaluate')
</code></pre>
<p>Note that depending on whether or not you have the affected instances in the session and will be using them later on you could choose not to synchronize at all with <code>False</code>.</p>
| 0 | 2016-08-27T18:39:40Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] |
How to install firefoxdriver webdriver for python3 selenium on ubuntu 16.04? | 39,179,320 | <p>I installed python3-selenium apt package on Ubuntu 16.04. While installing, got a message:</p>
<pre><code>Suggested packages:
chromedriver firefoxdriver
The following NEW packages will be installed:
python3-selenium
</code></pre>
<p>When I try to run the following python code,</p>
<pre><code>#! /usr/bin/python3.5
from selenium import webdriver
import time
def get_profile():
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.privatebrowsing.autostart", True)
return profile
def main():
browser = webdriver.Firefox(firefox_profile=getProfile())
#browser shall call the URL
browser.get("http://www.google.com")
time.sleep(5)
browser.quit()
if __name__ == "__main__":
main()
</code></pre>
<p>I get the following error:</p>
<blockquote>
<p>Traceback (most recent call last):
File "./test.py", line 19, in
main()
File "./test.py", line 11, in main
browser = webdriver.Firefox(firefox_profile=getProfile())
File "/usr/lib/python3/dist-packages/selenium/webdriver/firefox /webdriver.py", line 77, in <strong>init</strong>
self.binary, timeout),
File "/usr/lib/python3/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 47, in <strong>init</strong>
self.profile.add_extension()
File "/usr/lib/python3/dist-packages/selenium/webdriver/firefox/firefox_profile.py", line 91, in add_extension
self._install_extension(extension)
File "/usr/lib/python3/dist-packages/selenium/webdriver/firefox/firefox_profile.py", line 251, in _install_extension
compressed_file = zipfile.ZipFile(addon, 'r')
File "/usr/lib/python3.5/zipfile.py", line 1009, in <strong>init</strong>
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: '/usr/lib /firefoxdriver/webdriver.xpi'</p>
</blockquote>
<p>I did searching for packages name firefoxdriver in Ubuntu repositories but none exist.
How do I solve this problem?</p>
<p>Any help with installing the webdrivers appreciated!</p>
| 1 | 2016-08-27T08:58:25Z | 39,195,764 | <p>You can either upgrade to 16.10 (it's in yakkety) or you can download the deb from <a href="http://pk.archive.ubuntu.com/ubuntu/ubuntu/pool/multiverse/s/selenium-firefoxdriver/" rel="nofollow">here</a> (it works - I tried it). Alternatively you can follow <a href="https://christopher.su/2015/selenium-chromedriver-ubuntu/#selenium-version" rel="nofollow">these</a> instructions to install by hand (chromedriver but for Firefox it's the same).</p>
| 0 | 2016-08-28T21:04:19Z | [
"python",
"python-3.x",
"selenium",
"selenium-webdriver",
"python-3.5"
] |
How to install firefoxdriver webdriver for python3 selenium on ubuntu 16.04? | 39,179,320 | <p>I installed python3-selenium apt package on Ubuntu 16.04. While installing, got a message:</p>
<pre><code>Suggested packages:
chromedriver firefoxdriver
The following NEW packages will be installed:
python3-selenium
</code></pre>
<p>When I try to run the following python code,</p>
<pre><code>#! /usr/bin/python3.5
from selenium import webdriver
import time
def get_profile():
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.privatebrowsing.autostart", True)
return profile
def main():
browser = webdriver.Firefox(firefox_profile=getProfile())
#browser shall call the URL
browser.get("http://www.google.com")
time.sleep(5)
browser.quit()
if __name__ == "__main__":
main()
</code></pre>
<p>I get the following error:</p>
<blockquote>
<p>Traceback (most recent call last):
File "./test.py", line 19, in
main()
File "./test.py", line 11, in main
browser = webdriver.Firefox(firefox_profile=getProfile())
File "/usr/lib/python3/dist-packages/selenium/webdriver/firefox /webdriver.py", line 77, in <strong>init</strong>
self.binary, timeout),
File "/usr/lib/python3/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 47, in <strong>init</strong>
self.profile.add_extension()
File "/usr/lib/python3/dist-packages/selenium/webdriver/firefox/firefox_profile.py", line 91, in add_extension
self._install_extension(extension)
File "/usr/lib/python3/dist-packages/selenium/webdriver/firefox/firefox_profile.py", line 251, in _install_extension
compressed_file = zipfile.ZipFile(addon, 'r')
File "/usr/lib/python3.5/zipfile.py", line 1009, in <strong>init</strong>
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: '/usr/lib /firefoxdriver/webdriver.xpi'</p>
</blockquote>
<p>I did searching for packages name firefoxdriver in Ubuntu repositories but none exist.
How do I solve this problem?</p>
<p>Any help with installing the webdrivers appreciated!</p>
| 1 | 2016-08-27T08:58:25Z | 39,548,509 | <p>I'm not certain if this will fix the issue you're having, but you can give it a try. But first, to answer the question as to where you can download firefoxdriver, my answer would be <strong>maybe firefoxdriver is not available, because the file is now called geckodriver, but it's really called Marionette Driver.</strong> It's described here: <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver</a> , and it's made available here <a href="https://github.com/mozilla/geckodriver/releases" rel="nofollow">https://github.com/mozilla/geckodriver/releases</a></p>
<p>That answers the question, I believe, however I'd like to try to address the issue you're having.</p>
<p><strong>My understanding of your issue:</strong>
You're trying to spawn an instance of firefox, through selenium, but it's not working.</p>
<p><strong>My hypothesis as to why it's not working:</strong>
Maybe you're using Firefox 47 or newer. If you're looking for where to downlad the new 'firefoxdriver' (its called the Marionette Driver, but the file is called geckodriver), you'll have to download the file directly from its github release page: <a href="https://github.com/mozilla/geckodriver/releases" rel="nofollow">https://github.com/mozilla/geckodriver/releases</a> (I suggest downloading v0.9.0, since v0.10.0 hasn't worked for me).</p>
<p>If you're using Firefox 47 or newer, then starting up Firefox browser with a simple <code>browser = webdriver.Firefox()</code> just isn't going to work. This used to work for Firefox 46, and I'm assuming older versions, however it no longer works because support for Firefox Webdriver has now been dropped. You now have to download the new Marionette driver, and modify your code a bit to make it work with this new driver. You can learn more about Marionette in the link I provided above.</p>
<p><strong>The solutions I'm proposing</strong>
You can either:</p>
<ol>
<li>Download and downgrade to Firefox 46</li>
</ol>
<p>or </p>
<ol start="2">
<li>Download the new Marionette driver and adapt your code to work with it</li>
</ol>
<p>If you choose option #1, then simply find a way to downgrade to Firefox 46. </p>
<p>If however you want your code to work with the most recent release of Firefox, then you choose option #2 and the basic gist of how to accomplish that is as follows:</p>
<ol>
<li>Download and extract the driver</li>
<li>Make sure that your OS can find the file in its systempath</li>
<li>Modify your code to work with the new Marionette webdriver</li>
</ol>
<p>The specific <strong>step by step process</strong> (for ubuntu) can be found in this stackoverflow answer <a href="https://stackoverflow.com/questions/39478101/launch-selenium-from-python-on-ubuntu/39536091#39536091">launch selenium from python on ubuntu</a></p>
<p>selenium should be able to spawn firefox normally once that's done.</p>
| 0 | 2016-09-17T15:26:05Z | [
"python",
"python-3.x",
"selenium",
"selenium-webdriver",
"python-3.5"
] |
Is it possible in Python to decorate a function so that its begin and end are logged? | 39,179,519 | <p>For logging, I would like each function to log its own name at the start and end of the function.</p>
<pre><code>def my_function():
print("Enter my_function")
# ...
print("Leave my_function")
</code></pre>
<p>If I change the name of the function, I have to update these print messages as well. I am looking for a way to automate this.</p>
<pre><code>def my_decorator(func):
print("Enter ", func.__name__)
func()
print("Leave ", func.__name__)
def my_function():
# do the work
pass
# main:
my_decorator(my_function)
</code></pre>
<p>Is this possible in a simple way, maybe using decorators? How would this look like if my_function had parameters?</p>
| 1 | 2016-08-27T09:25:29Z | 39,179,602 | <p>You are right, using a decorator is a perfect way to implement such behavior.</p>
<p>What you need to know is <a class='doc-link' href="http://stackoverflow.com/documentation/python/229/decorators#t=201608270936002345573">how a decorator works</a>: it simply takes a function as an argument, and returns another function. This other returned function is intended to wrap your argument function.</p>
<pre><code>def log_in_out(func):
def decorated_func(*args, **kwargs):
print("Enter ", func.__name__)
result = func(*args, **kwargs)
print("Leave ", func.__name__)
return result
return decorated_func
@log_in_out
def my_function():
print("Inside my_function")
return 42
val = my_function()
print(val)
# Output:
# Enter my_function
# Inside my_function
# Leave my_function
# 42
</code></pre>
<p>Also, note that the answer of @ÅukaszRogalski using <a href="https://docs.python.org/3/library/functools.html#functools.wraps" rel="nofollow"><code>functools.wraps</code></a> is usefull for preserving the function docstring.</p>
<p>Finally, a good idea from @MartinBonner, is that you can also use it to log the errors in your function:</p>
<pre><code>def log_in_out(func):
def decorated_func(*args, **kwargs):
name = func.__name__
print("Enter", name)
try:
result = func(*args, **kwargs)
print("Leave", name)
except:
print("Error in", name)
raise
return result
return decorated_func
</code></pre>
<p>Note that I re-throw the error because I think the control flow should be managed from the outside of the function.</p>
<p>For more advanced logging, you should use <a href="https://docs.python.org/3.5/library/logging.html#logging.Logger.exception" rel="nofollow">the built-in module</a> which provides many facilities.</p>
| 6 | 2016-08-27T09:35:00Z | [
"python",
"python-decorators"
] |
Is it possible in Python to decorate a function so that its begin and end are logged? | 39,179,519 | <p>For logging, I would like each function to log its own name at the start and end of the function.</p>
<pre><code>def my_function():
print("Enter my_function")
# ...
print("Leave my_function")
</code></pre>
<p>If I change the name of the function, I have to update these print messages as well. I am looking for a way to automate this.</p>
<pre><code>def my_decorator(func):
print("Enter ", func.__name__)
func()
print("Leave ", func.__name__)
def my_function():
# do the work
pass
# main:
my_decorator(my_function)
</code></pre>
<p>Is this possible in a simple way, maybe using decorators? How would this look like if my_function had parameters?</p>
| 1 | 2016-08-27T09:25:29Z | 39,179,611 | <p>Sure, it's really simple with star args and star kwargs. <code>functools.wraps</code> is used to rewrite any metadata (<code>__name__</code>, <code>__doc__</code> etc.) from input function to wrapper. If function object string representation is too verbose to you, you may use <code>print("Enter", f.__name__)</code> instead.</p>
<pre><code>import functools
def d(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
print("Enter", f)
result = f(*args, **kwargs)
print("Exit", f)
return result
return wrapper
@d
def my_func():
print("hello")
@d
def my_func2(x):
print(x)
my_func()
my_func2("world")
</code></pre>
<p>Output:</p>
<pre><code>Enter <function my_func at 0x10ca93158>
hello
Exit <function my_func at 0x10ca93158>
Enter <function my_func2 at 0x10caed950>
world
Exit <function my_func2 at 0x10caed950>
</code></pre>
| 1 | 2016-08-27T09:35:54Z | [
"python",
"python-decorators"
] |
Handling Arabic text in Python | 39,179,538 | <p>I have the following Python 2.7 code:</p>
<pre><code>mydoclist = ['جÙÙÙØ§ ØªØØ¨ÙÙ Ø§ÙØ«Ø± Ù
Ù ÙÙÙØ¯Ø§','جÙÙ ØªØØ¨ÙÙ Ø§ÙØ«Ø± Ù
٠جÙÙÙØ§','اØÙ
د ÙØØ¨ ÙØ±Ø© Ø§ÙØ³ÙØ© Ø§ÙØ«Ø± Ù
Ù ÙØ±Ø© Ø§ÙØ·Ø§ÙÙØ©']
from collections import Counter
for doc in mydoclist:
tf = Counter()
for word in doc.split():
tf[word] +=1
print tf.items()
</code></pre>
<p>I got the following output:</p>
<pre><code>[(u'\u062a\u062d\u0628\u0646\u064a', 1), (u'\u0645\u0646', 1), (u'\u062c \u0648\u0644\u064a\u0627', 1), (u'\u0644\u064a\u0646\u062f\u0627', 1), (u'\u0627\u0643\u062b\u0631', 1)]
[('\xd8\xac\xd9\x8a\xd9\x86', 1), ('\xd9\x85\xd9\x86', 1), ('\xd8\xac\xd9\x88\xd9\x84\xd9\x8a\xd8\xa7', 1), ('\xd8\xaa\xd8\xad\xd8\xa8\xd9\x86\xd9\x8a', 1), ('\xd8\xa7\xd9\x83\xd8\xab\xd8\xb1', 1)]
[('\xd8\xa7\xd9\x83\xd8\xab\xd8\xb1', 1), ('\xd8\xa7\xd8\xad\xd9\x85\xd8\xaf', 1), ('\xd9\x8a\xd8\xad\xd8\xa8', 1), ('\xd8\xa7\xd9\x84\xd8\xb7\xd8\xa7\xd9\x88\xd9\x84\xd8\xa9', 1), ('\xd9\x83\xd8\xb1\xd8\xa9', 2), ('\xd8\xa7\xd9\x84\xd8\xb3\xd9\x84\xd8\xa9', 1), ('\xd9\x85\xd9\x86', 1)]
</code></pre>
<p>Why I can not see Arabic words. I want to see Arabic words instead of these codes that appear in the output. Thanks.</p>
| 0 | 2016-08-27T09:27:54Z | 39,179,763 | <p>Python prints lists so that all items in them are passed through <code>repr</code> which in turn produces this stuff with "\u...". Also have a look at the tutorial section about <a href="https://docs.python.org/2.7/tutorial/introduction.html#unicode-strings" rel="nofollow">unicode-strings</a> or better the <a href="https://docs.python.org/2.7/howto/unicode.html" rel="nofollow">unicode HOWTO</a> they helped me a lot.
For sourcecode containing non-ascii characters you should <a href="https://www.python.org/dev/peps/pep-0263/" rel="nofollow">set an encoding</a> (most likely "utf-8"). Also you propably want to mark strings containing such characters as unicode (<code>u"..."</code> instead of <code>"..."</code>)</p>
<pre><code># -*- coding: utf-8 -*-
from collections import Counter
mydoclist = [u'جÙÙÙØ§ ØªØØ¨ÙÙ Ø§ÙØ«Ø± Ù
Ù ÙÙÙØ¯Ø§',u'جÙÙ ØªØØ¨ÙÙ Ø§ÙØ«Ø± Ù
٠جÙÙÙØ§',u'اØÙ
د ÙØØ¨ ÙØ±Ø© Ø§ÙØ³ÙØ© Ø§ÙØ«Ø± Ù
Ù ÙØ±Ø© Ø§ÙØ·Ø§ÙÙØ©']
for doc in mydoclist:
tf = Counter()
for word in doc.split():
tf[word] +=1
print u", ".join( u"(%i: %s)"%(n,s) for (s,n) in tf.items())
</code></pre>
<p>works for me.</p>
| 2 | 2016-08-27T09:54:52Z | [
"python",
"arabic"
] |
How to detect the number of threads i can & i should run? | 39,179,607 | <p>i have a 6th generation Intel i5 Processor (4 cores, 3 ghZ) and 8 gigabytes of RAM. Let's assume i need to create a text file which includes every number from 0 to 999999999. </p>
<p>How can i make it faster? How many threads i should use? 4 or more than 4? How many threads i should run and why?</p>
| 1 | 2016-08-27T09:35:34Z | 39,180,217 | <p>Due to the fact you're writing into the same file, you will need a lock in order for the text not to get garbled. If you're using a lock however, multi-threading or multi-processing won't make a difference as it will be writing sequentially.</p>
<p>Not using a lock will get a result much like this:</p>
<pre><code>1, 2, 3, 54,, ...
</code></pre>
<p>as one thread will write it's own and the other thread will write at the same time.</p>
| 1 | 2016-08-27T10:43:10Z | [
"python",
"multithreading"
] |
How to detect the number of threads i can & i should run? | 39,179,607 | <p>i have a 6th generation Intel i5 Processor (4 cores, 3 ghZ) and 8 gigabytes of RAM. Let's assume i need to create a text file which includes every number from 0 to 999999999. </p>
<p>How can i make it faster? How many threads i should use? 4 or more than 4? How many threads i should run and why?</p>
| 1 | 2016-08-27T09:35:34Z | 39,180,370 | <p>because of GIL you should use multiprocessing module. number of process should be:</p>
<pre><code>multiprocessing.cpu_count() - 1 # -1 for other system process.
</code></pre>
| 1 | 2016-08-27T11:00:36Z | [
"python",
"multithreading"
] |
How to detect the number of threads i can & i should run? | 39,179,607 | <p>i have a 6th generation Intel i5 Processor (4 cores, 3 ghZ) and 8 gigabytes of RAM. Let's assume i need to create a text file which includes every number from 0 to 999999999. </p>
<p>How can i make it faster? How many threads i should use? 4 or more than 4? How many threads i should run and why?</p>
| 1 | 2016-08-27T09:35:34Z | 39,183,116 | <p>Thanks for the answers & comments. I couldn't try the multiprocessing module because i am on a vacation and my computer has 2 cores, it would be the same (1 for system, 1 for python.). But i will add the results with the multiprocessing as soon as i get home. So, here is my test results with a Intel Pentium Dual Core 1.80ghZ:</p>
<p>Without extra threads it took 4 seconds.<br>
With one extra thread it took 3 seconds.</p>
<p>After the second thread it didn't change. I tried with 3, 4 and 5 threads, every time it took 3 seconds.</p>
<p>Here are the codes; </p>
<p><a href="http://paste.ubuntu.com/23098237/" rel="nofollow">http://paste.ubuntu.com/23098237/</a> > 1 thread</p>
<p><a href="http://paste.ubuntu.com/23098229/" rel="nofollow">http://paste.ubuntu.com/23098229/</a> > 2 thread</p>
<p><a href="http://paste.ubuntu.com/23098131/" rel="nofollow">http://paste.ubuntu.com/23098131/</a> > 3 thread</p>
<p><a href="http://paste.ubuntu.com/23098136/" rel="nofollow">http://paste.ubuntu.com/23098136/</a> > 4 thread</p>
<p><a href="http://paste.ubuntu.com/23098139/" rel="nofollow">http://paste.ubuntu.com/23098139/</a> > 5 thread</p>
<p>sorry, i couldn't paste the code here, it said "not properly formatted as code". i tried for like 10 minutes, (ctrl + k, 4 spaces) it didn't work, so i just posted it on paste.ubuntu.com</p>
| 0 | 2016-08-27T16:06:52Z | [
"python",
"multithreading"
] |
python to extract list match from email thread | 39,179,672 | <p>I m new to python. I need to retrieve the list of match </p>
<p>for Example my text is below which is an email.
I need to extract all To, From, Sent, Subject and body from a mail thread.</p>
<p>Result need to From List</p>
<p>From(1) = Crandall, Sean
From(2) = Nettelton, Marcus </p>
<p>To(1)= Crandall, Sean; Badeer, Robert
To(2)= Meredith, Kevin</p>
<p>Like for above Sent, subject etc</p>
<pre><code>"-----Original Message-----
From: Crandall, Sean
Sent: Wednesday, May 23, 2001 2:56 PM
To: Meredith, Kevin
Subject: RE: Spreads and Product long desc.
Kevin,
Is the SP and NP language in the spread language the same language we use when we transact SP15 or NP15 on eol?
-----Original Message-----
From: Meredith, Kevin
Sent: Wednesday, May 23, 2001 11:16 AM
To: Crandall, Sean; Badeer, Robert
Subject: FW: Spreads and Product long desc."
</code></pre>
| 0 | 2016-08-27T09:43:00Z | 39,180,211 | <p>You can use <code>re.findall()</code> for this, see: <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow">https://docs.python.org/2/library/re.html#re.findall</a>. E.g.</p>
<pre><code>re.findall("From: (.*) ", input_string);
</code></pre>
<p>would return a list of the From-names (<code>['Crandall, Sean', 'Meredith, Kevin']</code>), assuming it's always the same amount of white spaces.</p>
<p>If you want to get fancy, you could do several searches in the same expression: E.g.</p>
<pre><code>re.findall("From: (.*) \nSent: (.*)", input_string);
</code></pre>
<p>would return <code>[('Crandall, Sean', 'Wednesday, May 23, 2001 2:56 PM'), ('Meredith, Kevin', 'Wednesday, May 23, 2001 11:16 AM')]</code></p>
| 1 | 2016-08-27T10:42:38Z | [
"python",
"regex",
"match"
] |
python to extract list match from email thread | 39,179,672 | <p>I m new to python. I need to retrieve the list of match </p>
<p>for Example my text is below which is an email.
I need to extract all To, From, Sent, Subject and body from a mail thread.</p>
<p>Result need to From List</p>
<p>From(1) = Crandall, Sean
From(2) = Nettelton, Marcus </p>
<p>To(1)= Crandall, Sean; Badeer, Robert
To(2)= Meredith, Kevin</p>
<p>Like for above Sent, subject etc</p>
<pre><code>"-----Original Message-----
From: Crandall, Sean
Sent: Wednesday, May 23, 2001 2:56 PM
To: Meredith, Kevin
Subject: RE: Spreads and Product long desc.
Kevin,
Is the SP and NP language in the spread language the same language we use when we transact SP15 or NP15 on eol?
-----Original Message-----
From: Meredith, Kevin
Sent: Wednesday, May 23, 2001 11:16 AM
To: Crandall, Sean; Badeer, Robert
Subject: FW: Spreads and Product long desc."
</code></pre>
| 0 | 2016-08-27T09:43:00Z | 39,180,246 | <p>If you don't know how to use regex and as your problem is not that tough, you may consider to use the <code>split()</code> and <code>replace()</code> functions.</p>
<p>Here are some lines of code that might be a good start:</p>
<pre><code>mails = """-----Original Message-----
From: Crandall, Sean
Sent: Wednesday, May 23, 2001 2:56 PM
To: Meredith, Kevin
Subject: RE: Spreads and Product long desc.
Kevin,
Is the SP and NP language in the spread language the same language we use when we transact SP15 or NP15 on eol?
-----Original Message-----
From: Meredith, Kevin
Sent: Wednesday, May 23, 2001 11:16 AM
To: Crandall, Sean; Badeer, Robert
Subject: FW: Spreads and Product long desc."""
mails_list = mails.split("-----Original Message-----\n")
mails_from = []
mails_sent = []
mails_to = []
mails_subject = []
mails_body = []
for mail in mails_list:
if not mail:
continue
inter = mail.split("From: ")[1].split("\nSent: ")
mails_from.append(inter[0])
inter = inter[1].split("\nTo: ")
mails_sent.append(inter[0])
inter = inter[1].split("\nSubject: ")
mails_to.append(inter[0])
inter = inter[1].split("\n")
mails_subject.append(inter[0])
mails_body.append(inter[0])
</code></pre>
<p>See how this only use really basic concepts.</p>
<p>Here are some points that you might need to consider:</p>
<ul>
<li>Try by yourself, you might need some adjustments.</li>
<li>With that method, the parsing method is quite tough, the format of the mails must be really accurate.</li>
<li>There might be some space that you want to remove, for example with the <code>replace()</code> method.</li>
</ul>
| 1 | 2016-08-27T10:47:49Z | [
"python",
"regex",
"match"
] |
Is there a way to get multiple ngram orders using NTLK instead of obtaining a iterating over a generator? | 39,179,703 | <p>I need ngrams. I know <code>nltk.utils.ngrams</code> can be used to obtain ngrams, but in practice, the ngrams function returns a generator object. I can always iterate over it and store the ngrams in a list. But is there another, more direct way to obtaining these ngrams in a list without having to iterate over them?</p>
| 0 | 2016-08-27T09:47:09Z | 39,179,853 | <p>@georg's comment pretty much nails it.</p>
<pre><code>In [12]: from nltk.util import ngrams
In [13]: g = ngrams([1,2,3,4,5], 3)
In [14]: list(g)
Out[14]: [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
In [15]: g = ngrams([1,2,3,4,5], 3)
In [16]: map(lambda x: x, g)
Out[16]: [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
</code></pre>
| 2 | 2016-08-27T10:04:55Z | [
"python",
"nlp",
"generator",
"nltk",
"n-gram"
] |
Is there a way to get multiple ngram orders using NTLK instead of obtaining a iterating over a generator? | 39,179,703 | <p>I need ngrams. I know <code>nltk.utils.ngrams</code> can be used to obtain ngrams, but in practice, the ngrams function returns a generator object. I can always iterate over it and store the ngrams in a list. But is there another, more direct way to obtaining these ngrams in a list without having to iterate over them?</p>
| 0 | 2016-08-27T09:47:09Z | 39,180,306 | <p>or alternatively without <code>nltk</code>:</p>
<pre><code>from itertools import chain
def ngrams(L, n = 2):
orders = [n] if type(n) is int else sorted(list(n))
return list(chain(*[zip(*[L[i:] for i in range(n)]) for n in orders]))
>>> ngrams([1,2,3,4,5], n = 3)
[(1, 2, 3), (2, 3, 4), (3, 4, 5)]
>>> ngrams([1,2,3,4,5], n = [2,3])
[(1, 2), (2, 3), (3, 4), (4, 5), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
</code></pre>
| 0 | 2016-08-27T10:54:15Z | [
"python",
"nlp",
"generator",
"nltk",
"n-gram"
] |
Is there a way to get multiple ngram orders using NTLK instead of obtaining a iterating over a generator? | 39,179,703 | <p>I need ngrams. I know <code>nltk.utils.ngrams</code> can be used to obtain ngrams, but in practice, the ngrams function returns a generator object. I can always iterate over it and store the ngrams in a list. But is there another, more direct way to obtaining these ngrams in a list without having to iterate over them?</p>
| 0 | 2016-08-27T09:47:09Z | 39,182,566 | <p>There's actually a built-in function to get multiple orders of ngrams call <code>everygrams</code> ,see <a href="https://github.com/nltk/nltk/blob/develop/nltk/util.py#L504" rel="nofollow">https://github.com/nltk/nltk/blob/develop/nltk/util.py#L504</a></p>
<pre><code>>>> from nltk import everygrams
>>> sent = 'a b c'.split()
# By default, it will extract every possible order of ngrams.
>>> list(everygrams(sent))
[('a',), ('b',), ('c',), ('a', 'b'), ('b', 'c'), ('a', 'b', 'c')]
# You can set a max order or ngrams.
>>> list(everygrams(sent, max_len=2))
[('a',), ('b',), ('c',), ('a', 'b'), ('b', 'c')]
# Or specify a range.
>>> list(everygrams(sent, min_len=2, max_len=3))
[('a', 'b'), ('b', 'c'), ('a', 'b', 'c')]
</code></pre>
| 3 | 2016-08-27T15:06:45Z | [
"python",
"nlp",
"generator",
"nltk",
"n-gram"
] |
Should I include this boilerplate code in every Python script I write? | 39,179,738 | <p>My boss asked me to put the following lines (from <a href="https://stackoverflow.com/questions/4374455/how-to-set-sys-stdout-encoding-in-python-3">this answer</a>) into a Python 3 script I wrote:</p>
<pre><code>import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
</code></pre>
<p>He says it's to prevent <code>UnicodeEncodeErrors</code> when printing Unicode characters in non-UTF8 locales. I am wondering whether this is really necessary, and why Python wouldn't handle encoding/decoding correctly without boilerplate code.</p>
<p>What is the most Pythonic way to make Python scripts compatible with different operating system locales? And what does this boilerplate code do exactly?</p>
| 3 | 2016-08-27T09:51:03Z | 39,179,986 | <p>The answer provided <a href="http://stackoverflow.com/questions/11741574/how-to-print-utf-8-encoded-text-to-the-console-in-python-3">here</a> has a good excerpt from the Python mailing list regarding your question. I guess it is not necessary to do this.</p>
<blockquote>
<p>The only supported default encodings in Python are:</p>
<p>Python 2.x: ASCII<br>
Python 3.x: UTF-8</p>
<p>If you change these, you are on your own and strange things will start
to happen. The default encoding does not only affect the translation
between Python and the outside world, but also all internal
conversions between 8-bit strings and Unicode.</p>
<p>Hacks like what's happening in the pango module (setting the default
encoding to 'utf-8' by reloading the site module in order to get the
sys.setdefaultencoding() API back) are just downright wrong and will
cause serious problems since Unicode objects cache their default
encoded representation.</p>
<p>Please don't enable the use of a locale based default encoding.</p>
<p>If all you want to achieve is getting the encodings of stdout and
stdin correctly setup for pipes, you should instead change the
.encoding attribute of those (only).</p>
<p>--<br>
Marc-Andre Lemburg<br>
eGenix.com</p>
</blockquote>
| 4 | 2016-08-27T10:17:25Z | [
"python",
"python-3.x",
"unicode"
] |
creating nested dicts in python 3 | 39,179,799 | <p>I'm trying to create the following nested dict structure, <code>{0: {0: 1}, 1: {0: 1, 1: 1}}</code> with the following code:</p>
<pre><code>feats = {}
for i in range(2):
feat = feats.get(i, {})
for j in range(i+1):
feat[j] = 1
</code></pre>
<p>but all I'm getting <code>feats = {}</code>. Why is that? Thanks.</p>
| 1 | 2016-08-27T09:59:42Z | 39,179,838 | <p>The problem here is, you are not storing <code>feat</code> value in <code>feats</code>, so it is lost after every iteration. At the end of the iterations, <code>feats</code> is empty.</p>
<p>You can fix your code like below: </p>
<pre><code>feats = {}
for i in range(2):
feat = feats.get(i, {})
for j in range(i+1):
feat[j] = 1
feats[i] = feat
print(feats)
</code></pre>
<p>output:</p>
<pre><code>{0: {0: 1}, 1: {0: 1, 1: 1}}
</code></pre>
| 3 | 2016-08-27T10:03:44Z | [
"python",
"python-3.x",
"dictionary"
] |
creating nested dicts in python 3 | 39,179,799 | <p>I'm trying to create the following nested dict structure, <code>{0: {0: 1}, 1: {0: 1, 1: 1}}</code> with the following code:</p>
<pre><code>feats = {}
for i in range(2):
feat = feats.get(i, {})
for j in range(i+1):
feat[j] = 1
</code></pre>
<p>but all I'm getting <code>feats = {}</code>. Why is that? Thanks.</p>
| 1 | 2016-08-27T09:59:42Z | 39,180,214 | <p>First of all I ran your program and I printed feats, it printed{0: 1, 1: 1} and not {}</p>
<p>Second thing, what I can understand from your requirement is that, in a generic way, while looping through a range of numbers, you want to have that number as key and value as dictionary containing key value pairs, where number of keys are from 0 to that number and value as 1. Correct me if I am wrong.</p>
<p>So the correct program for this would be:</p>
<pre><code>feats = {}
for i in range(2):
feats[i] = feats.get(i, {})
for j in range(0,i+1):
feats[i][j] = 1
print feats
</code></pre>
<p>You can replace 2 with any number in range and get your answer accordingly.</p>
| 0 | 2016-08-27T10:42:45Z | [
"python",
"python-3.x",
"dictionary"
] |
oddo can't adapt type 'hr.employee' | 39,179,843 | <p>I want to get value of field in my class that one2many to hr_employee:</p>
<pre><code>class cashadvance(osv.osv):
def get_employeeid(self, cr, uid, context=None):
idemployee = ""
employee_id = ""
ids = self.search(cr, uid, [], context=context) # you probably want to search for all the records
for adv in self.browse(cr, uid, ids, context=context):
employee_id = adv.id_employee
if (employee_id is None):
idemployee = 0
else:
idemployee = employee_id
return idemployee
_name = 'comben.cashadvance'
_columns = {
'id_employee' : fields.many2one('hr.employee', string='Employee', required=True, readonly=True),
}
</code></pre>
<p>it raised error : can't adapt type 'hr.employee' </p>
<p>but when I changed :</p>
<pre><code>class cashadvance(osv.osv):
def get_employeeid(self, cr, uid, context=None):
idemployee = ""
employee_id = ""
ids = self.search(cr, uid, [], context=context) # you probably want to search for all the records
for adv in self.browse(cr, uid, ids, context=context):
employee_id = adv.id_employee
if (employee_id is None):
idemployee = 0
else:
**idemployee = 1348 #employee_id**
return idemployee
_name = 'comben.cashadvance'
_columns = {
'id_employee' : fields.many2one('hr.employee', string='Employee', required=True, readonly=True),
}
</code></pre>
<p>I worked fine, what I'm doing wrong with this, please help</p>
| 0 | 2016-08-27T10:04:04Z | 39,180,347 | <pre><code> for adv in self.browse(cr, uid, ids, context=context):
employee_id = adv.id_employee
</code></pre>
<p>On this part of the code your are browsing the self model. Browse method returns a recordset, that means it returns a instance of the class that represents the model your browse runs to. If you want to get the id of any record you have to:</p>
<pre><code> employee_id = adv.id_employee.id
</code></pre>
| 3 | 2016-08-27T10:58:30Z | [
"python",
"openerp"
] |
XLRD vs Win32 COM performance comparison | 39,179,880 | <p>I have this huge <code>Excel (xls)</code> file that I have to read data from. I tried using the <code>xlrd</code> library, but is pretty slow. I then found out that by converting the <code>Excel</code> file to <code>CSV</code> file manually and reading the <code>CSV</code> file is orders of magnitude faster.</p>
<p>But I cannot ask my client to save the <code>xls</code> as <code>csv</code> manually every time before importing the file. So I thought of converting the file on the fly, before reading it.</p>
<p>Has anyone done any benchmarking as to which procedure is faster:</p>
<ul>
<li>Open the <code>Excel</code> file with with the <code>xlrd</code> library and save it as <code>CSV</code> file, or</li>
<li>Open the <code>Excel</code> file with <code>win32com</code> library and save it as <code>CSV</code> file?</li>
</ul>
<p>I am asking because the slowest part is the opening of the file, so if I can get a performance boots from using <code>win32com</code> I would gladly try it.</p>
| -1 | 2016-08-27T10:07:25Z | 39,360,812 | <p>if you need to read the file frequently, I think it is better to save it as CSV. Otherwise, just read it on the fly. </p>
<p>for performance issue, I think win32com outperforms. however, considering cross-platform compatibility, I think xlrd is better.
win32com is more powerful. With it, one can handle Excel in all ways (e.g. reading/writing cells or ranges).
However, if you are seeking a quick file conversion, I think pandas.read_excel also works.</p>
<p>I am using another package xlwings. so I am also interested with a comparison among these packages. </p>
<p>to my opinion,
I would use pandas.read_excel to for quick file conversion.
If demanding more processing on Excel, I would choose win32com.</p>
| 0 | 2016-09-07T03:32:21Z | [
"python",
"excel",
"csv",
"win32com"
] |
Can't *update* pycharm educational | 39,180,027 | <p>I am a Ubuntu 16 user and I installed pycharm educational 2 at my computer.
A few days ago while starting the app I received the notification that there's am update : version 3
So I downloaded the file(.tgz) from from the developer website and tried to install the update. I can only extract the file instead of actually installing like in Windows wizards
Can you explain me what went wrong?
Thanks in advance</p>
| 0 | 2016-08-27T10:21:55Z | 39,185,756 | <p>Unpack the archive, go to <code>bin</code> folder and run <code>.sh</code> script.</p>
| 0 | 2016-08-27T21:06:32Z | [
"python",
"ide",
"install",
"pycharm"
] |
Is there is any way to identify background of an image (indoor or outdoor) | 39,180,041 | <p>I am doing a research on object identification. I did it using tensorflow and it identified objects of an image well. It does not, however, have any idea how to identify the background of an image (indoor or outdoor).</p>
| -1 | 2016-08-27T10:23:17Z | 39,243,099 | <p>It seems like for each image, you're interested in two classification results: what object appears in the image, and whether it's outdoors or indoors.</p>
<p>A straightforward way of doing that would be to train and apply two different classifiers, one for object recognition and one for background classification. </p>
<p>Getting some images for training shouldn't be difficult, as there are many datasets having exlicitly indoor or outdoor scenes (e.g. <a href="http://web.mit.edu/torralba/www/indoor.html" rel="nofollow">here</a>). However depending on your specific data, e.g. specific scenery, colors or light conditions, this may or may not yield good results.</p>
| 0 | 2016-08-31T07:16:56Z | [
"python",
"image-processing",
"machine-learning",
"neural-network"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.