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 |
---|---|---|---|---|---|---|---|---|---|
pass data result from python to Java variable by processbuilder | 39,908,283 | <p>I used process builder to run a python script from java. and i can sent the data from Java to python variable ( import sys to get data from Java) . and print out the python result in java.
for example: </p>
<pre><code>public static void main(String a[]){
try{
int number1 = 100;
int number2 = 200;
String searchTerm="water";
ProcessBuilder pb = new ProcessBuilder("C:/Python27/python","D://my_utils.py",""+number1,""+number2,""+searchTerm);
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(".........start process.........");
String line = "";
while ((line = bfr.readLine()) != null){
System.out.println("Python Output: " + line);
}
System.out.println("........end process.......");
}catch(Exception e){System.out.println(e);}
}
}
</code></pre>
<p>However, I do not know how to get back the result from python and pass the result to <strong>JAVA Variable</strong> for further use. How to do that?
I have issue with passing a list as a method argument in JAVA.
[![enter image description here][1]][1]
[![enter image description here][2]][2]
How to pass the variable (<strong>return variable</strong> in def MatchSearch() in python) to the <strong>JAVA VARIABLE</strong>? </p>
| 0 | 2016-10-07T02:09:42Z | 39,955,546 | <p>u can save the python result in JSON format. and use java to read parser the json file to get the content so as to create the variable.</p>
| 1 | 2016-10-10T09:46:25Z | [
"java",
"python",
"json",
"processbuilder",
"sys"
]
|
Pass variable to an exception? | 39,908,291 | <p>I am trying to learn Python and I want to know if it is possible to pass a variable to an <code>Exception</code>? This is the code I have:</p>
<pre><code>try:
staffId = int(row['staffId'])
openingSalary = int(row['initialSalary'])
monthsWorked = float(row['monthsWorked'])
except CutomException:
pass
class CustomException(ValueError): # raised if data conversion fails
def __init__(self):
print("There was a problem converting data")
</code></pre>
<p>I want to pass <code>staffId</code> to the exception so that I can print something like: </p>
<p>print("There was a problem converting data for staff Id: ", staffId)</p>
<p>I tried this with no success: <a href="http://stackoverflow.com/questions/6626816/how-to-pass-a-variable-to-an-exception-when-raised-and-retrieve-it-when-excepted">How to pass a variable to an exception when raised and retrieve it when excepted?</a></p>
| 0 | 2016-10-07T02:10:39Z | 39,908,321 | <p>The caller of the exception, e.g. the one that <code>raise</code> exception will have to pass an argument to the constructor.</p>
<pre><code>class CustomException(ValueError): # raised if data conversion fails
def __init__(self, message):
self.message = message;
print("There was a problem converting data")
try:
try:
staffId = int(row['staffId'])
openingSalary = int(row['initialSalary'])
monthsWorked = float(row['monthsWorked'])
except ValueError as e:
raise CutomException(e);
except CutomException:
pass
</code></pre>
| 1 | 2016-10-07T02:13:55Z | [
"python",
"exception"
]
|
Pass variable to an exception? | 39,908,291 | <p>I am trying to learn Python and I want to know if it is possible to pass a variable to an <code>Exception</code>? This is the code I have:</p>
<pre><code>try:
staffId = int(row['staffId'])
openingSalary = int(row['initialSalary'])
monthsWorked = float(row['monthsWorked'])
except CutomException:
pass
class CustomException(ValueError): # raised if data conversion fails
def __init__(self):
print("There was a problem converting data")
</code></pre>
<p>I want to pass <code>staffId</code> to the exception so that I can print something like: </p>
<p>print("There was a problem converting data for staff Id: ", staffId)</p>
<p>I tried this with no success: <a href="http://stackoverflow.com/questions/6626816/how-to-pass-a-variable-to-an-exception-when-raised-and-retrieve-it-when-excepted">How to pass a variable to an exception when raised and retrieve it when excepted?</a></p>
| 0 | 2016-10-07T02:10:39Z | 39,908,528 | <p>The custom exception will need to be <code>raise</code>'d conditionally by the <code>try</code> block to include the <code>staffId</code> variable. As an example, when the <code>staffId</code> is a <code>str</code> and not an <code>int</code>.</p>
<pre><code>try:
# conditionalize a scenario where you'd want to raise an error
# (e.g. the variable is a string)
if type(staffId) is str:
raise CustomException(staffId)
else:
staffId = int(row['staffId'])
openingSalary = int(row['initialSalary'])
monthsWorked = float(row['monthsWorked'])
except CutomException:
pass
class CustomException(ValueError): # raised if data conversion fails
def __init__(self, id):
print("There was a problem converting data %s" % id)
</code></pre>
| 1 | 2016-10-07T02:38:22Z | [
"python",
"exception"
]
|
Slice all strings in a list? | 39,908,314 | <p>Is there a Pythonic way to slice all strings in a list?</p>
<p>Suppose I have a list of strings:</p>
<pre><code>list = ['foo', 'bar', 'baz']
</code></pre>
<p>And I want just the last 2 characters from each string:</p>
<pre><code>list2 = ['oo', 'ar', 'az']
</code></pre>
<p>How can I get that? </p>
<p>I know I can iterate thru the list and take <code>list[i][-2:]</code> from each one, but that doesn't seem very Pythonic.</p>
<p>Less generally, my code is:</p>
<pre><code>def parseIt(filename):
with open(filename) as f:
lines = f.readlines()
result = [i.split(',') for i in lines[]]
</code></pre>
<p>...except I only want to split <code>lines[i][20:]</code> from each line (not the whole line).</p>
| 2 | 2016-10-07T02:13:03Z | 39,908,453 | <p>You mentioned that you can do <code>list[i][-2:]</code> for transforming the list per your specification, but what you are actually looking for is:</p>
<pre><code>[word[1:] for word in lst]
</code></pre>
<p>Furthermore, for the code sample you provided where you are looking to seem to slice 20 characters from the beginning, the solution is the same: </p>
<pre><code>result = [i[20:].split(',') for i in lines]
</code></pre>
| 5 | 2016-10-07T02:29:48Z | [
"python",
"string",
"list",
"slice"
]
|
Mock standard input - multi line in python 3 | 39,908,390 | <p>I am new to python and have been using python 3 for my learning. I am using python's unit test framework to test my code.</p>
<p>Problem :-</p>
<p>The function that I need to unit test takes inputs in the following manner:-</p>
<pre><code>def compare():
a, b, c = input().strip().split(' ')
d, e, f = input().strip().split(' ')
# other code here
</code></pre>
<p>I am using the following test case to mock the input :-</p>
<pre><code>class TestCompare(unittest.TestCase):
@patch("builtins.input", lambda: "1 2 3")
@patch("builtins.input", lambda: "4 5 6")
def test_compare(self):
self.assertEqual(compare(), "1 1")
</code></pre>
<p>The problem I am facing is that when the test case is run the variable triplets a,b,c and d,e,f have the same values - 1,2,3</p>
<p>I have been trying to find a way to inject the second set of inputs to run my test but in vain.</p>
<p>Any help regarding the above is greatly appreciated.</p>
<p>Solution environment :- Python 3</p>
| 0 | 2016-10-07T02:22:10Z | 39,908,499 | <p>You can't patch it twice like that. You'll have to patch it once, with an object that returns different values on subsequent calls. Here's an example:</p>
<pre><code>fake_input = iter(['1 2 3', '4 5 6']).__next__
@patch("builtins.input", fake_input)
def test_compare(self):
...
</code></pre>
| 2 | 2016-10-07T02:34:12Z | [
"python",
"unit-testing",
"python-3.x",
"lambda",
"patch"
]
|
Mock standard input - multi line in python 3 | 39,908,390 | <p>I am new to python and have been using python 3 for my learning. I am using python's unit test framework to test my code.</p>
<p>Problem :-</p>
<p>The function that I need to unit test takes inputs in the following manner:-</p>
<pre><code>def compare():
a, b, c = input().strip().split(' ')
d, e, f = input().strip().split(' ')
# other code here
</code></pre>
<p>I am using the following test case to mock the input :-</p>
<pre><code>class TestCompare(unittest.TestCase):
@patch("builtins.input", lambda: "1 2 3")
@patch("builtins.input", lambda: "4 5 6")
def test_compare(self):
self.assertEqual(compare(), "1 1")
</code></pre>
<p>The problem I am facing is that when the test case is run the variable triplets a,b,c and d,e,f have the same values - 1,2,3</p>
<p>I have been trying to find a way to inject the second set of inputs to run my test but in vain.</p>
<p>Any help regarding the above is greatly appreciated.</p>
<p>Solution environment :- Python 3</p>
| 0 | 2016-10-07T02:22:10Z | 39,908,502 | <p>The patch decorator will ensure the patched function always return that value, and if subsequent calls must be different, your mock object must have a way to simulate that. This ends up being much more complicated.</p>
<p>What you can do however is go one step lower and patch the underlying layer, which is the standard input/output layer. One common strategy that other test frameworks have done is to deal with the <code>sys.stdin</code> and <code>sys.stdout</code> objects directly. Consider this:</p>
<pre><code>import unittest
from unittest.mock import patch
from io import StringIO
def compare():
a, b, c = input().strip().split(' ')
d, e, f = input().strip().split(' ')
return '%s %s' % (a, d)
class TestCompareSysStdin(unittest.TestCase):
@patch("sys.stdin", StringIO("1 2 3\n4 5 6"))
def test_compare(self):
self.assertEqual(compare(), "1 4")
</code></pre>
<p>Execution</p>
<pre><code>$ python -m unittest foo
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
</code></pre>
<p>Naturally, this works at a lower level, and so the option to have an iterator that returns different values on subsequent calls may be more suitable.</p>
| 2 | 2016-10-07T02:34:48Z | [
"python",
"unit-testing",
"python-3.x",
"lambda",
"patch"
]
|
Mock standard input - multi line in python 3 | 39,908,390 | <p>I am new to python and have been using python 3 for my learning. I am using python's unit test framework to test my code.</p>
<p>Problem :-</p>
<p>The function that I need to unit test takes inputs in the following manner:-</p>
<pre><code>def compare():
a, b, c = input().strip().split(' ')
d, e, f = input().strip().split(' ')
# other code here
</code></pre>
<p>I am using the following test case to mock the input :-</p>
<pre><code>class TestCompare(unittest.TestCase):
@patch("builtins.input", lambda: "1 2 3")
@patch("builtins.input", lambda: "4 5 6")
def test_compare(self):
self.assertEqual(compare(), "1 1")
</code></pre>
<p>The problem I am facing is that when the test case is run the variable triplets a,b,c and d,e,f have the same values - 1,2,3</p>
<p>I have been trying to find a way to inject the second set of inputs to run my test but in vain.</p>
<p>Any help regarding the above is greatly appreciated.</p>
<p>Solution environment :- Python 3</p>
| 0 | 2016-10-07T02:22:10Z | 39,908,520 | <p>You can't patch out your function twice like that. When you are looking to mock the same function, and have it return different values each time it is called, you should use <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect" rel="nofollow">side_effect</a>.</p>
<p><code>side_effect</code> takes a list of values, where each value in the list is the return of every time that function is called in your code: </p>
<pre><code>class TestCompare(unittest.TestCase):
@patch("builtins.input", side_effect=["1 2 3", "4 5 6"])
def test_compare(self, mock_input):
self.assertEqual(compare(), "1 1")
</code></pre>
| 2 | 2016-10-07T02:37:04Z | [
"python",
"unit-testing",
"python-3.x",
"lambda",
"patch"
]
|
Pythonanywhere - ImportError: No module named 'myapp.settings' | 39,908,467 | <p>Using Python 3.5 and Django 1.9, I was trying to deploy my app to pythonanywhere, but I keep getting this error</p>
<pre><code>2016-10-07 01:44:28,879 :Error running WSGI application
Traceback (most recent call last):
File "/bin/user_wsgi_wrapper.py", line 154, in __call__
app_iterator = self.app(environ, start_response)
File "/bin/user_wsgi_wrapper.py", line 170, in import_error_application
raise e
File "/bin/user_wsgi_wrapper.py", line 154, in __call__
app_iterator = self.app(environ, start_response)
File "/bin/user_wsgi_wrapper.py", line 170, in import_error_application
raise e
File "/bin/user_wsgi_wrapper.py", line 179, in <module>
application = load_wsgi_application()
File "/bin/user_wsgi_wrapper.py", line 175, in load_wsgi_application
return __import__(os.environ['WSGI_MODULE'], globals(), locals(), ['application']).application
File "/var/www/nidalmer_pythonanywhere_com_wsgi.py", line 21, in <module>
application = StaticFilesHandler(get_wsgi_application())
File "/home/nidalmer/trailersapp/myvenv/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
django.setup()
File "/home/nidalmer/trailersapp/myvenv/lib/python3.5/site-packages/django/__init__.py", line 17, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/home/nidalmer/trailersapp/myvenv/lib/python3.5/site-packages/django/conf/__init__.py", line 55, in __getattr__
self._setup(name)
File "/home/nidalmer/trailersapp/myvenv/lib/python3.5/site-packages/django/conf/__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "/home/nidalmer/trailersapp/myvenv/lib/python3.5/site-packages/django/conf/__init__.py", line 99, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/home/nidalmer/trailersapp/myvenv/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: No module named 'trailersapp.settings'
</code></pre>
<p>Here is my <strong>wsgi.py</strong> file</p>
<pre><code>import os
import sys
path = '/home/nidalmer/trailersapp/trailers/settings.py'
if path not in sys.path:
sys.path.append(path)
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.settings")
application = get_wsgi_application()
</code></pre>
<p>and my tree:</p>
<pre><code>trailersapp
âââ db.sqlite3
âââ manage.py
âââ movies
â âââ __init__.py
â âââ __pycache__
â âââ admin.py
â âââ apps.py
â âââ forms.py
â âââ migrations
â âââ models.py
â âââ templates
â âââ tests.py
â âââ urls.py
â âââ views.py
âââ myvenv
âââ requirements.txt
âââ static
â âââ admin
â âââ movies
âââ trailers
âââ __init__.py
âââ __pycache__
âââ settings.py
âââ urls.py
âââ wsgi.py
</code></pre>
<p>I can't tell where the error is coming from since my wsgi file says trailers.settings and not trailersapp.settings and I don't have that anywhere. </p>
<p>Any help would be appreciated!</p>
| 2 | 2016-10-07T02:31:01Z | 39,917,257 | <p>The path in your wsgi file is wrong. It's supposed to be the path to your app, so:</p>
<pre><code>path = '/home/nidalmer/trailersapp'
</code></pre>
<p>Also, I think you're looking at an old traceback or an old copy of the wsgi file. Make sure they're both up-to-date.</p>
| 3 | 2016-10-07T12:24:41Z | [
"python",
"django",
"pythonanywhere"
]
|
numpy version error when importing tensorflow | 39,908,504 | <p>I have executed <code>pip install</code> for tensorflow.</p>
<p>Under the python command line environment, when I tried </p>
<pre><code>import tensorflow as tf
</code></pre>
<p>I met the following errors:</p>
<pre><code>RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 23, in <module>
from tensorflow.python import *
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
_pywrap_tensorflow = swig_import_helper()
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: numpy.core.multiarray failed to import
</code></pre>
<p>I have checked my <code>numpy</code> version using <code>print numpy.__version__</code>. It showed <code>"1.8.2"</code>. So, what should I do now? Thanks!</p>
| 0 | 2016-10-07T02:35:08Z | 39,913,467 | <p>From the error, it looks like you're running python 2.7 from <code>usr/local/bin</code>. There is a mismatch problem between your <code>numpy</code> version and <code>tensorflow</code> installation. I'd recommend you to install anaconda since it will make sure that correct version of <code>tensorflow</code> that is compatible with your <code>numpy</code> version be installed.</p>
<p>Once you have anaconda, then do:</p>
<pre><code>conda install tensorflow
</code></pre>
| 0 | 2016-10-07T09:04:34Z | [
"python",
"python-2.7",
"numpy",
"runtime-error",
"tensorflow"
]
|
Weeks difference between two dates in python | 39,908,548 | <p>How do I get the differences between two valid dates in weeks. I have googled many, but none are the one that I have been looking for</p>
<p>Say I have two dates:</p>
<blockquote>
<p><strong>02-Dec-2016</strong> and <strong>10-Jan-2017</strong>.</p>
</blockquote>
<p>I want it to provide me with output like following</p>
<pre><code>02-Dec-2016 - 04-Dec-2016 (2 days) (2 days before monday comes)
05-Dec-2016 - 08-Jan-2017 (5 weeks) (starts from monday-sunday)
08-Jan-2017 - 10-Jan-2017 (2 days) (2 days after monday has gone)
</code></pre>
| -2 | 2016-10-07T02:40:54Z | 39,912,043 | <p>This is what you actualy want: </p>
<pre><code>import datetime
def diff(d1, d2):
result = []
delta = datetime.timedelta(days=0)
day = datetime.timedelta(days=1)
while d1.weekday() != 0:
d1 += day
delta += day
result.append((d1 - delta, d1 - day))
weeks, days = divmod((d2 - d1).days, 7)
d3 = d1 + datetime.timedelta(weeks=weeks)
d4 = d3 + datetime.timedelta(days=days)
result.append((d1, d3 - day))
result.append((d3, d4))
return result
d1 = datetime.date(2016, 12, 2)
d2 = datetime.date(2017, 01, 10)
for i,j in diff(d1,d2):
print '{} - {} ({} days)'.format(datetime.datetime.strftime(i, "%d-%b-%Y"), datetime.datetime.strftime(j, "%d-%b-%Y"), (j-i).days + 1)
# 02-Dec-2016 - 04-Dec-2016 (3 days)
# 05-Dec-2016 - 08-Jan-2017 (35 days)
# 09-Jan-2017 - 10-Jan-2017 (2 days)
</code></pre>
| 1 | 2016-10-07T07:44:33Z | [
"python"
]
|
flask-login:Exception: No user_loader has been installed for this LoginManager. Add one with the 'LoginManager.user_loader' decorator | 39,908,552 | <p>I want to use flask_login to manager user login but some error like this:</p>
<p>Exception: No user_loader has been installed for this LoginManager. Add one with the 'LoginManager.user_loader' decorator.</p>
<p>this is my models.py (PS:I use Flask peewee to build my models)</p>
<pre><code>from peewee import *
from playhouse.fields import ManyToManyField
from .__init__ import login_manager
from flask_login import UserMixin, AnonymousUserMixin
db = SqliteDatabase('adminSystem.db')
class BaseModel(Model):
class Meta:
database = db
class User(UserMixin, BaseModel):
name = CharField()
email = CharField()
is_admin = BooleanField()
username = CharField()
passwd_hash = CharField()
teacher = ForeignKeyField('self', related_name='students', null=True)
#def is_authenticated(self):
# return True
#def is_active(self):
# return True
#def is_anonymous(self):
# return False
#def get_id(self):
# try:
# return unicode(self.id)
# except NameError:
# return str(self.id)
class Homework(BaseModel):
owner = ForeignKeyField(User, related_name='homeworks', null=True)
pub_datetime = DateTimeField()
connect = TextField()
homework_id =CharField()
file_url = CharField()
class Score(BaseModel):
homework_id = CharField()
stu_id = CharField()
grade = IntegerField()
file_url = CharField()
class AnonymousUser(AnonymousUserMixin):
def can(self, permissions):
return False
def is_administrator(self):
return False
@login_manager.user_loader
def load_user(userid):
try:
#: Flask Peewee used here to return the user object
return User.get(User.id==userid)
except User.DoesNotExist:
return None
</code></pre>
<p>and this is some part of my view.py</p>
<pre><code>from flask import render_template, url_for, redirect, request, g
from . import auth
from werkzeug.security import generate_password_hash, check_password_hash
from ..models import db, User, Homework, Score
from flask_login import login_user, logout_user, login_required, current_user
@auth.before_app_request
def before_request():
g.user = current_user
@auth.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
if request.form['role'] == 'teacher':
user = User.get(User.username == request.form['username'])
if check_password_hash(user.passwd_hash, request.form['password']):
login_user(user)
return redirect(url_for('main.post'))
return render_template('login.html')
elif request.form['role'] == 'student':
user = User.get(User.username == request.form['username'])
if check_password_hash(user.passwd_hash, request.form['password']):
login_user(user)
return redirect(url_for('main.show'))
return render_template('login.html')
return render_template('login.html')
</code></pre>
<p>and there is a picture that I had try <a href="http://i.stack.imgur.com/3woAj.png" rel="nofollow">enter image description here</a></p>
| 0 | 2016-10-07T02:42:07Z | 39,908,998 | <p>According to <a href="https://flask-login.readthedocs.io/en/latest/#configuring-your-application" rel="nofollow">https://flask-login.readthedocs.io/en/latest/#configuring-your-application</a></p>
<blockquote>
<p>Once the actual application object has been created, you can configure
it for login with:</p>
<p>login_manager.init_app(app)</p>
</blockquote>
<p>After that, you can register callbacks by using decorators etc. So that the <code>login_manager</code> has the context to process.</p>
| 0 | 2016-10-07T03:41:28Z | [
"python",
"flask",
"flask-login"
]
|
How to define an Integral as an objective function in pyomo? | 39,908,555 | <p>I want to be able to define an integral in <code>pyomo</code> as part of an objective function. </p>
<p>I cannot figure out what kind of expression is needed for the integral.<br>
Here's my best guess:</p>
<pre><code>model = ConcreteModel()
model.t = ContinuousSet(bounds = (0,1))
model.y = Var(model.t)
model.dydt = DerivativeVar(model.y, wrt=(model.t))
def myintegral(model,i):
return model.dydt[i]
model.n = Integral(model.t, wrt=model.t, rule=myintegral) # this line is the trouble
def myobjective(model):
return model.n
model.obj = Objective(rule=myobjective)
</code></pre>
<p>The error is: <code>TypeError: A callable type that is not a Pyomo expression can not be used to initialize an Expression object. Use 'rule' to initalize with function types.</code></p>
<p>But, I don't understand why the expression inside of the integral is a problem, since these variables seem to be totally indexable by the index <code>model.t</code>:</p>
<pre><code># but, this is totally fine:
print model.dydt[0]
print model.dydt[1]
</code></pre>
<p>Am I misunderstanding something about this? </p>
<p>Here are some resources that I consulted thus far: </p>
<p><a href="https://groups.google.com/forum/#!topic/pyomo-forum/6RhEXEMDTPc" rel="nofollow">https://groups.google.com/forum/#!topic/pyomo-forum/6RhEXEMDTPc</a>
<a href="https://software.sandia.gov/downloads/pub/pyomo/PyomoOnlineDocs.html#_parameters" rel="nofollow">https://software.sandia.gov/downloads/pub/pyomo/PyomoOnlineDocs.html#_parameters</a>
<a href="https://projects.coin-or.org/Coopr/browser/pyomo/trunk/examples/dae/Heat_Conduction.py?rev=9315" rel="nofollow">https://projects.coin-or.org/Coopr/browser/pyomo/trunk/examples/dae/Heat_Conduction.py?rev=9315</a></p>
<p>I'm open to suggestions/links about other resources about <code>pyomo</code>.</p>
| 0 | 2016-10-07T02:42:32Z | 39,908,672 | <p>This looks like a bug. You should open up a ticket here: <a href="https://github.com/Pyomo/pyomo/issues" rel="nofollow">https://github.com/Pyomo/pyomo/issues</a></p>
| 1 | 2016-10-07T02:57:39Z | [
"python",
"pyomo"
]
|
How to define an Integral as an objective function in pyomo? | 39,908,555 | <p>I want to be able to define an integral in <code>pyomo</code> as part of an objective function. </p>
<p>I cannot figure out what kind of expression is needed for the integral.<br>
Here's my best guess:</p>
<pre><code>model = ConcreteModel()
model.t = ContinuousSet(bounds = (0,1))
model.y = Var(model.t)
model.dydt = DerivativeVar(model.y, wrt=(model.t))
def myintegral(model,i):
return model.dydt[i]
model.n = Integral(model.t, wrt=model.t, rule=myintegral) # this line is the trouble
def myobjective(model):
return model.n
model.obj = Objective(rule=myobjective)
</code></pre>
<p>The error is: <code>TypeError: A callable type that is not a Pyomo expression can not be used to initialize an Expression object. Use 'rule' to initalize with function types.</code></p>
<p>But, I don't understand why the expression inside of the integral is a problem, since these variables seem to be totally indexable by the index <code>model.t</code>:</p>
<pre><code># but, this is totally fine:
print model.dydt[0]
print model.dydt[1]
</code></pre>
<p>Am I misunderstanding something about this? </p>
<p>Here are some resources that I consulted thus far: </p>
<p><a href="https://groups.google.com/forum/#!topic/pyomo-forum/6RhEXEMDTPc" rel="nofollow">https://groups.google.com/forum/#!topic/pyomo-forum/6RhEXEMDTPc</a>
<a href="https://software.sandia.gov/downloads/pub/pyomo/PyomoOnlineDocs.html#_parameters" rel="nofollow">https://software.sandia.gov/downloads/pub/pyomo/PyomoOnlineDocs.html#_parameters</a>
<a href="https://projects.coin-or.org/Coopr/browser/pyomo/trunk/examples/dae/Heat_Conduction.py?rev=9315" rel="nofollow">https://projects.coin-or.org/Coopr/browser/pyomo/trunk/examples/dae/Heat_Conduction.py?rev=9315</a></p>
<p>I'm open to suggestions/links about other resources about <code>pyomo</code>.</p>
| 0 | 2016-10-07T02:42:32Z | 39,960,159 | <p>Gabe is right, this is indeed a bug in the Integral class and it has been fixed on the github repository. One other error in your example model is the specification of the Objective component. You should be using the 'rule' keyword instead of 'expr'</p>
<pre><code>def myobjective(model):
return model.n
model.obj = Objective(rule=myobjective)
</code></pre>
<p>Also, I want to reiterate something mentioned in the online documentation for pyomo.dae. The Integral component is a prototype and not fully developed. I do not recommend using it for complex integrals or models that require high accuracy solutions. The Integral class uses the trapezoid rule for numerical integration. I would recommend converting any integrals in your problem to differential equations and solving them using the provided automatic discretization transformations.</p>
| 2 | 2016-10-10T14:04:49Z | [
"python",
"pyomo"
]
|
Python dill: Pickle namedtuple doesnt seem to work | 39,908,774 | <p>I have namedtuple inside a class. When pickling using dill, it complains the classic issue of not being able to find the namedtuple object at top module. </p>
<pre><code>import dill as pickle
class NNRTMParse(object):
def __init__(self,logfile)):
.
.
.
.
self.TM = namedtuple('TM',tmeas_fields)
#print self.TM
CFH = namedtuple('CFH',cfhdr_fields)
PM = namedtuple('PM',pmeas_fields2)
print PM
</code></pre>
<p>This is default assignment for self.TM and others, and I dynamically assign namedtuple as I parse the log.</p>
<p>But pickling :</p>
<pre><code> if __name__ == "__main__":
filename = 'dbggen_rx_loc_2-llh_rtm_lla_out_20160929_130711_day2_4381_JN2_SN64_rtmproc_2M5M.txt'
N = NNRTMParse(filename)
N.parse()
N.get_rx_loc('oak484_bora-llh')
filehandler = open("NNRTMParse_JB2-SN052.obj","wb")
pickle.dump(N,filehandler)
filehandler.close()
Traceback (most recent call last):
File "C:/NN_Hardware/spos_proc/NNRTMParse.py", line 937, in <module>
pickle.dump(N,filehandler)
File "C:\Python27\lib\site-packages\dill\dill.py", line 236, in dump
pik.dump(obj)
File "C:\Python27\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Python27\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python27\lib\pickle.py", line 419, in save_reduce
save(state)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\site-packages\dill\dill.py", line 835, in save_module_dict
StockPickler.save_dict(pickler, obj)
File "C:\Python27\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python27\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\site-packages\dill\dill.py", line 1189, in save_type
StockPickler.save_global(pickler, obj)
File "C:\Python27\lib\pickle.py", line 748, in save_global
(obj, module, name))
pickle.PicklingError: Can't pickle <class '__main__.TM'>: it's not found as __main__.TM
</code></pre>
<p>I am not sure if there is any way out. Else would have to route thru the path just to nit-pick the dataframes to pickle, which I hate to do.</p>
<p>Any help is very appreciated.</p>
| 0 | 2016-10-07T03:11:59Z | 39,942,024 | <p>The issue is the <code>self.TM</code> <code>namedtuple</code>. If you don't use the <code>namedtuple</code> as a class attribute, then your class should pickle.</p>
<pre><code># file: xxx.py
from collections import namedtuple
class NNRTMParse(object):
def __init__(self):
TM = namedtuple("TM", 'a')
CFH = namedtuple("CFH", 'b')
print CFH
</code></pre>
<p>It should work like this:</p>
<pre><code>>>> from xxx import *
>>> a = NNRTMParse()
<class 'xxx.CFH'>
>>> import dill
>>> dill.copy(a)
<xxx.NNRTMParse object at 0x107da3350>
</code></pre>
<p>However, as soon as you try to use the <code>namedtuple</code> as a attribute, it fails with the error you are seeing.</p>
<p>I'd suggest adding a <code>__reduce__</code> method (<a href="https://docs.python.org/3/library/pickle.html#object.__reduce__" rel="nofollow">https://docs.python.org/3/library/pickle.html#object.<strong>reduce</strong></a>) to tell <code>pickle</code> how to serialize the state of the class instance.</p>
| 0 | 2016-10-09T09:27:35Z | [
"python",
"pickle",
"namedtuple",
"dill"
]
|
This python code is not solving equations | 39,908,815 | <p>I have a chat bot for an Instant messenger and I am trying to make a math solver for it but it can't send the solution of equation to the Instant messenger, it sends equation instead.</p>
<p>If someone from Instant messenger sends "solve: 2+2", this program should send them "4" not "2+2".</p>
<p><strong>Main problem:</strong></p>
<pre><code>if (parser.getPayload().lower()[:6]=="solve:"):
parser.sendGroupMessage(parser.getTargetID(), str(parser.getPayload()[7:]))
</code></pre>
<p><strong>output:</strong></p>
<p><a href="http://i.stack.imgur.com/Rf4ND.png" rel="nofollow">it's sending same input again not the answer of equation</a></p>
<p><strong>Test:</strong>
I tested something and that's working properly. If I add this code, program will send solution of equation:</p>
<pre><code>if (parser.getPayload().lower()=="test"):
parser.sendGroupMessage(parser.getTargetID(), str(2 + 2 -3 + 8 * 7))
</code></pre>
<p><strong>Output:</strong>
<a href="http://i.stack.imgur.com/uHg55.png" rel="nofollow">Working perfectly</a></p>
| 0 | 2016-10-07T03:17:29Z | 39,909,052 | <p>What you need to do this evaluating math expressions in string form.</p>
<p>However, user inputs are dangerous if you are just <code>eval</code> things whatever they give you. <a href="http://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings">Security of Python's eval() on untrusted strings?</a></p>
<p>You can use <code>ast.literal_eval</code> to lower the risk.</p>
<p>Or you can use a evaluator from answers of following question
<a href="http://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string">Evaluating a mathematical expression in a string</a></p>
| 0 | 2016-10-07T03:48:25Z | [
"python",
"bots",
"irc",
"instant-messaging",
"payload"
]
|
This python code is not solving equations | 39,908,815 | <p>I have a chat bot for an Instant messenger and I am trying to make a math solver for it but it can't send the solution of equation to the Instant messenger, it sends equation instead.</p>
<p>If someone from Instant messenger sends "solve: 2+2", this program should send them "4" not "2+2".</p>
<p><strong>Main problem:</strong></p>
<pre><code>if (parser.getPayload().lower()[:6]=="solve:"):
parser.sendGroupMessage(parser.getTargetID(), str(parser.getPayload()[7:]))
</code></pre>
<p><strong>output:</strong></p>
<p><a href="http://i.stack.imgur.com/Rf4ND.png" rel="nofollow">it's sending same input again not the answer of equation</a></p>
<p><strong>Test:</strong>
I tested something and that's working properly. If I add this code, program will send solution of equation:</p>
<pre><code>if (parser.getPayload().lower()=="test"):
parser.sendGroupMessage(parser.getTargetID(), str(2 + 2 -3 + 8 * 7))
</code></pre>
<p><strong>Output:</strong>
<a href="http://i.stack.imgur.com/uHg55.png" rel="nofollow">Working perfectly</a></p>
| 0 | 2016-10-07T03:17:29Z | 39,909,195 | <p>Your test code</p>
<pre><code>str(2 + 2 -3 + 8 * 7)
</code></pre>
<p>is distinct from your production code</p>
<pre><code>str(parser.getPayload()[7:])
</code></pre>
<p>which gets expanded into</p>
<pre><code>str("2 + 2 -3 + 8 * 7")
</code></pre>
<p>assuming you pass in the same equotation. Good thing is you have the plumbing working, now you need to implement the actual math solver like</p>
<pre><code>str(solve_math(parser.getPayload()[7:]))
def solve_math(expr : str) -> float:
"""
Parses and evaluates math expression `expr` and returns its result.
"""
</code></pre>
<p>Here you need to first parse the expression string into some structure representing the data, the operators / functions and the evaluation order. So your "2 + 2" expression gets turned into something like <code>Addition(Const(2), Const(2))</code> while expression "2 + 2 * 3" gets turned into somethng like <code>Addition(Const(2), Multiplication(Const(2), Const(3)))</code> and then you need to just evaluate it which should be fairly simple.</p>
<p>I recommend <code>pyparsing</code> to help you with that.</p>
| 0 | 2016-10-07T04:04:53Z | [
"python",
"bots",
"irc",
"instant-messaging",
"payload"
]
|
Reading user selection from Django 1.5 template without using Models | 39,908,826 | <p>Im using <strong>Python27</strong> with <strong>Django 1.5</strong>.</p>
<p>i have been scowering the internet for hours without success. Is there a way to capture what the user has selected from a dropdown listbox in a template without using Models? Im looking for a direct way to read some sort of var into code in views.py.</p>
<p><em>example.html</em></p>
<pre><code><select name="num_select">
<option value="0">-----</option>
<option value="10">1 - 10</option>
<option value="20">10 - 20</option>
<option value="30">20 - 30</option>
<option value="40">30 - 40</option>
<option value="all">all</option>
</select>
</code></pre>
<p>which every option i select I want to pass the value to a var in my views.py</p>
<p><em>views.py</em></p>
<pre><code>def my_view(request):
...
num_select = forms.????.get['num_select']
...
return blah blah....
</code></pre>
<p>I hope i have provided enough details for you to assist me. Not sure what else i can add. I have been going through pages of docs without success. I know how to get vars from views.py to html templates, but not vise-versa. </p>
<p>Help is greatly appreciated. </p>
| 0 | 2016-10-07T03:18:14Z | 39,908,885 | <p>You can read raw form data by using <code>HttpRequest.POST</code> API</p>
<p><a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.POST" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.POST</a></p>
<p>It's a dictionary-like object containing all given HTTP POST parameters.</p>
<p>You can just <code>request.POST['num_select']</code></p>
<p>Remember to include <code>if request.method == 'POST':</code> before using <code>request.POST</code></p>
| 0 | 2016-10-07T03:25:56Z | [
"python",
"html",
"django",
"templates",
"html-select"
]
|
Reading user selection from Django 1.5 template without using Models | 39,908,826 | <p>Im using <strong>Python27</strong> with <strong>Django 1.5</strong>.</p>
<p>i have been scowering the internet for hours without success. Is there a way to capture what the user has selected from a dropdown listbox in a template without using Models? Im looking for a direct way to read some sort of var into code in views.py.</p>
<p><em>example.html</em></p>
<pre><code><select name="num_select">
<option value="0">-----</option>
<option value="10">1 - 10</option>
<option value="20">10 - 20</option>
<option value="30">20 - 30</option>
<option value="40">30 - 40</option>
<option value="all">all</option>
</select>
</code></pre>
<p>which every option i select I want to pass the value to a var in my views.py</p>
<p><em>views.py</em></p>
<pre><code>def my_view(request):
...
num_select = forms.????.get['num_select']
...
return blah blah....
</code></pre>
<p>I hope i have provided enough details for you to assist me. Not sure what else i can add. I have been going through pages of docs without success. I know how to get vars from views.py to html templates, but not vise-versa. </p>
<p>Help is greatly appreciated. </p>
| 0 | 2016-10-07T03:18:14Z | 39,908,897 | <p>Yes, you don't need models for this at all, what you need is a simple <a href="https://docs.djangoproject.com/en/1.10/topics/forms/" rel="nofollow">django form</a>. </p>
<pre><code>CHOICES = ( (1,"10"), (2,"20"), ...)
class MyForm(forms.form):
...
num_select = forms.ChoiceField(choices = CHOICES)
...
</code></pre>
<p>Then in your view</p>
<pre><code>from myapp.forms import MyForm
def my_view(request):
if request.method = 'POST':
form = MyForm(request.POST)
if form.is_valid():
num_select = form.cleaned_data['num_select']
</code></pre>
<p>This is of course a rather stripped down version of it, for additional information refer to the link above.</p>
<p>If you don't want to use a form either, you can just access <code>request.POST</code> directly, but then what's the point of using Django? you might as well use PHP</p>
| 1 | 2016-10-07T03:26:44Z | [
"python",
"html",
"django",
"templates",
"html-select"
]
|
pandas update dataframe by another dataframe with group by columns | 39,908,914 | <p>I have two dataframe like this </p>
<pre><code>df1 = pd.DataFrame({'A': ['1', '2', '3', '4','5'],
'B': ['1', '1', '1', '1','1'],
'C': ['A', 'A1', 'A2', 'A3','A4'],
'D': ['B0', 'B1', 'B2', 'B3','B4'],
'E': ['A', 'A', 'S', 'S','S']})
df2 = pd.DataFrame({'A': ['1', '6', '9', '4'],
'C': ['c', 'c1', 'c2', 'c3'],
'D': ['d1', 'd1', 'd2', 'd3']})
</code></pre>
<p>and I want to update df1's C,D columns by df2 when they get same column values in A (if df1['A']==df2['A'] then df1['C']=df2['C'] and df1['D']=df2['D'])</p>
<p>the answer should be like this</p>
<pre><code> A B C D E
0 1 1 c d1 A
1 2 1 A1 B1 A
2 3 1 A2 B2 S
3 4 1 c3 d3 S
4 5 1 A4 B4 S
</code></pre>
<p>I tried <code>df1.update(df2)</code> but it just overwrite df1 by df2</p>
<pre><code>>df1.update(df2)
> A B C D E
0 1 1 c d1 A
1 6 1 c1 d1 A
2 9 1 c2 d2 S
3 4 1 c3 d3 S
4 5 1 A4 B4 S
</code></pre>
<p>and I tried <code>pd.merge(df1, df2,how='inner' ,on=['A'])</code> still not what I want </p>
<pre><code> A B C_x D_x E C_y D_y
0 1 1 A B0 A c d1
1 4 1 A3 B3 S c3 d3
</code></pre>
<p>can anyone give me some suggestion?
Thank you</p>
| 2 | 2016-10-07T03:30:40Z | 39,909,146 | <p>I think this will be more space efficient:</p>
<h2>Edit To Add</h2>
<p>This may be more efficient:</p>
<pre><code>In [22]: df1,df2 = df1.align(df2,join='left',axis=0)
In [23]: df1
Out[23]:
A B C D E
0 1 1 A B0 A
1 2 1 A1 B1 A
2 3 1 A2 B2 S
3 4 1 A3 B3 S
4 5 1 A4 B4 S
In [24]: df2
Out[24]:
A C D
0 1 c d1
1 6 c1 d1
2 9 c2 d2
3 4 c3 d3
4 NaN NaN NaN
</code></pre>
<p>Now you can do find a boolean array where the columns are equal, and use <code>loc</code> based assignment to modify <code>df1</code> inplace without needed the extra columns:</p>
<pre><code>In [26]: equal_rows = df1.A == df2.A
In [27]: df1.loc[equal_rows]
Out[27]:
A B C D E
0 1 1 A B0 A
3 4 1 A3 B3 S
In [28]: df1.loc[equal_rows,['C','D']] = df2.loc[equal_rows,['C','D']]
In [29]: df1
Out[29]:
A B C D E
0 1 1 c d1 A
1 2 1 A1 B1 A
2 3 1 A2 B2 S
3 4 1 c3 d3 S
4 5 1 A4 B4 S
</code></pre>
<p>And if you really need df2 as it was originally:</p>
<pre><code>In [30]: df2.dropna(how='all',axis=0, inplace=True)
In [31]: df2
Out[31]:
A C D
0 1 c d1
1 6 c1 d1
2 9 c2 d2
3 4 c3 d3
</code></pre>
<h2>Original Answer</h2>
<p>Here is a clunky way that is not space efficient:</p>
<pre><code>In [13]: merged = pd.merge(df1,df2,how='left', on=['A'])
In [14]: merged
Out[14]:
A B C_x D_x E C_y D_y
0 1 1 A B0 A c d1
1 2 1 A1 B1 A NaN NaN
2 3 1 A2 B2 S NaN NaN
3 4 1 A3 B3 S c3 d3
4 5 1 A4 B4 S NaN NaN
In [15]: merged.fillna({'C_y':df1.C,'D_y':df1.D},inplace=True)
Out[15]:
A B C_x D_x E C_y D_y
0 1 1 A B0 A c d1
1 2 1 A1 B1 A A1 B1
2 3 1 A2 B2 S A2 B2
3 4 1 A3 B3 S c3 d3
4 5 1 A4 B4 S A4 B4
In [16]: merged.drop(['C_x','D_x'],axis=1,inplace=True)
In [17]: merged
Out[17]:
A B E C_y D_y
0 1 1 A c d1
1 2 1 A A1 B1
2 3 1 S A2 B2
3 4 1 S c3 d3
4 5 1 S A4 B4
</code></pre>
<p>And if you want the original names:</p>
<pre><code>In [20]: merged.rename(columns={"C_y":'C','D_y':'D'},inplace=True)
In [21]: merged
Out[21]:
A B E C D
0 1 1 A c d1
1 2 1 A A1 B1
2 3 1 S A2 B2
3 4 1 S c3 d3
4 5 1 S A4 B4
</code></pre>
| 1 | 2016-10-07T03:58:45Z | [
"python",
"pandas"
]
|
How to get elements of webpage that load after initial webpage? | 39,909,063 | <p>I'm trying to download stock option data from Yahoo Finance (<a href="https://finance.yahoo.com/quote/GOOG/options?p=GOOG" rel="nofollow">here's Google as an example</a>) with <code>requests.get</code>, which doesn't seem to be downloading everything. I'm trying to get the dropdown of dates with an XPath but even <code>//option</code> doesn't return anything even though Chrome DevTools says there are 13 instances!</p>
<p>I expect this has something to do with the fact that the parts of the site that actually matter are being loaded <em>after</em> all the navigation bars and such, and I don't know how to get all of it. Could you please suggest a method for getting the text of each item in the date dropdown menu?</p>
| 0 | 2016-10-07T03:50:00Z | 39,909,172 | <p>If you open the dev console and refresh the page again (caches might need to be purged), you can see some requests with type <code>xhr</code>.</p>
<p>They are usually initiated by JavaScript programs and will load some data besides those provided by HTML body.</p>
<p>That's what you can look into.</p>
| 0 | 2016-10-07T04:02:45Z | [
"python",
"html",
"python-3.x",
"xpath",
"web-scraping"
]
|
How to Crawl Website Content by Python | 39,909,065 | <p>I'm studying Python. I want to get content on one URL . Get all text in one title on the website and save it to file .txt. Can you show me some code example? </p>
| -1 | 2016-10-07T03:50:17Z | 39,909,741 | <p>By <code>Get all text in one title on the website</code> I assume you mean get the title of the page?</p>
<p>Firstly, you'll need BeautifulSoup</p>
<p>If you have <code>pip</code>, use</p>
<p><code>pip install beautifulsoup4</code></p>
<p>Now onto the code:</p>
<pre><code>from bs4 import BeautifulSoup
from requests import get
r = get(url).text
soup = BeautifulSoup(r, 'html.parser')
title = soup.title.string #I save the title to a variable rather then jus
with open('url.txt', 'w') as f:
f.write(title)
</code></pre>
<p>Now, where ever you have the script saved, will have a file called <code>url.txt</code> containing the URL.</p>
| 0 | 2016-10-07T05:02:29Z | [
"python",
"python-3.x",
"web",
"website",
"web-crawler"
]
|
Regex: How to extract a particular pattern individually from a text? | 39,909,109 | <p>I am trying to extract a pattern using regular expression from a text shown bellow.</p>
<pre><code>to_timestamp('02-04-09 00:00:00.000000000','RR-MM-DD HH24:MI:SS.FF'),'REP00061 ',to_timestamp('08-05-30 07:27:36.000000000','RR-MM-DD HH24:MI:SS.FF'),
</code></pre>
<p>How can I write a regex in Python to extract following patterns individually?</p>
<pre><code>to_timestamp('02-04-09 00:00:00.000000000','RR-MM-DD HH24:MI:SS.FF')
to_timestamp('08-05-30 07:27:36.000000000','RR-MM-DD HH24:MI:SS.FF')
</code></pre>
| 0 | 2016-10-07T03:55:14Z | 39,909,229 | <p>basically using pythex.org you can create your regex with ease.</p>
<p>for example :</p>
<pre><code>m = re.findall(r'(to_timestamp\(\'.*?\',\'.*? .*?\'\))',str)
</code></pre>
<p>the findall in the re module will create a list of all the matches.</p>
| 1 | 2016-10-07T04:08:25Z | [
"python",
"regex"
]
|
How can I only parse/split this list with multiple colons in each element? Create dictionary | 39,909,214 | <p>I have the following Python list:</p>
<pre><code>list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EY:EE:KJERWEWERKJWE']
</code></pre>
<p>I would like to take the entries of this list and create a dictionary of key-values pairs that looks like</p>
<pre><code>dictionary_list1 = {'EW':'G:B<<LADHFSSFAFFF', 'CB':'E:OWTOWTW', 'PP':'E:A,A<F<AF', 'GR':'A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX':'F:-111', 'DS':'f:115.5', 'MW':'AA:0', 'MA':'A:0XT:i:0', 'EW':'EE:KJERWEWERKJWE'}
</code></pre>
<p>How does one parse/split the list above <code>list1</code> to do this? My first instinct was to try <code>try1 = list1.split(":")</code>, but then I think it is impossible to retrieve the "key" for this list, as there are multiple colons <code>:</code></p>
<p>What is the most pythonic way to do this? </p>
| 4 | 2016-10-07T04:07:02Z | 39,909,245 | <p>You can specify a maximum number of times to split with the second argument to <a href="https://docs.python.org/3.5/library/stdtypes.html#str.split" rel="nofollow"><code>split</code></a>.</p>
<pre><code>list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EW:EE:KJERWEWERKJWE']
d = dict(item.split(':', 1) for item in list1)
</code></pre>
<p>Result:</p>
<pre><code>>>> import pprint
>>> pprint.pprint(d)
{'CB': 'E:OWTOWTW',
'DS': 'f:115.5',
'EW': 'EE:KJERWEWERKJWE',
'GR': 'A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7',
'MA': 'A:0XT:i:0',
'MW': 'AA:0',
'PP': 'E:A,A<F<AF',
'SX': 'F:-111'}
</code></pre>
<p>If you'd like to keep track of values for non-unique keys, like <code>'EW:G:B<<LADHFSSFAFFF'</code> and <code>'EW:EE:KJERWEWERKJWE'</code>, you could add keys to a <code>collections.defaultdict</code>:</p>
<pre><code>import collections
d = collections.defaultdict(list)
for item in list1:
k,v = item.split(':', 1)
d[k].append(v)
</code></pre>
<p>Result:</p>
<pre><code>>>> pprint.pprint(d)
{'CB': ['E:OWTOWTW'],
'DS': ['f:115.5'],
'EW': ['G:B<<LADHFSSFAFFF', 'EE:KJERWEWERKJWE'],
'GR': ['A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7'],
'MA': ['A:0XT:i:0'],
'MW': ['AA:0'],
'PP': ['E:A,A<F<AF'],
'SX': ['F:-111']}
</code></pre>
| 5 | 2016-10-07T04:10:02Z | [
"python",
"dictionary",
"split"
]
|
How can I only parse/split this list with multiple colons in each element? Create dictionary | 39,909,214 | <p>I have the following Python list:</p>
<pre><code>list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EY:EE:KJERWEWERKJWE']
</code></pre>
<p>I would like to take the entries of this list and create a dictionary of key-values pairs that looks like</p>
<pre><code>dictionary_list1 = {'EW':'G:B<<LADHFSSFAFFF', 'CB':'E:OWTOWTW', 'PP':'E:A,A<F<AF', 'GR':'A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX':'F:-111', 'DS':'f:115.5', 'MW':'AA:0', 'MA':'A:0XT:i:0', 'EW':'EE:KJERWEWERKJWE'}
</code></pre>
<p>How does one parse/split the list above <code>list1</code> to do this? My first instinct was to try <code>try1 = list1.split(":")</code>, but then I think it is impossible to retrieve the "key" for this list, as there are multiple colons <code>:</code></p>
<p>What is the most pythonic way to do this? </p>
| 4 | 2016-10-07T04:07:02Z | 39,909,368 | <p>You can also use <a href="https://docs.python.org/3/library/stdtypes.html#str.partition" rel="nofollow"><code>str.partition</code></a></p>
<pre><code>list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EW:EE:KJERWEWERKJWE']
d = dict([t for t in x.partition(':') if t!=':'] for x in list1)
# or more simply as TigerhawkT3 mentioned in the comment
d = dict(x.partition(':')[::2] for x in list1)
for k, v in d.items():
print('{}: {}'.format(k, v))
</code></pre>
<p>Output:</p>
<pre><code>MW: AA:0
CB: E:OWTOWTW
GR: A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7
PP: E:A,A<F<AF
EW: EE:KJERWEWERKJWE
SX: F:-111
DS: f:115.5
MA: A:0XT:i:0
</code></pre>
| 2 | 2016-10-07T04:26:06Z | [
"python",
"dictionary",
"split"
]
|
How to convert Multiplication sign into Asterisk sign in python? | 39,909,478 | <p>I have a math solver python program but it can't read "Ã" sign, so It can not solve the equation. Is there any way to convert "Ã" into "*"?</p>
<p><strong>Python shell:</strong></p>
<pre><code>>>> 3 Ã 5
`SyntaxError: invalid character in identifier
>>> 3 * 5
15
>>>
</code></pre>
<p><a href="http://i.stack.imgur.com/fZKi2.png" rel="nofollow">screenshot</a></p>
<p><strong>Update:</strong>
I tried this too, but did not work.</p>
<pre><code> if (parser.getPayload().lower()[:6]=="solve:"):
if ("Ã" in parser.getPayload().lower()):
str.replace("Ã","*")
parser.sendGroupMessage(parser.getTargetID(), str(ast.literal_eval(parser.getPayload()[7:])))
</code></pre>
| 0 | 2016-10-07T04:36:55Z | 39,919,610 | <p>Let's go over your code line by line.</p>
<pre><code>if (parser.getPayload().lower()[:6]=="solve:"):
</code></pre>
<p>Fine I guess, don't know your protocol but makes sense this way.</p>
<pre><code> if ("Ã" in parser.getPayload().lower()):
</code></pre>
<p>Converting to lower case should not be needed. If it were, caching that might be useful. I also wonder whether you need that check, or whether you might as well do the replacement unconditionally, since that makes the code easier and should't be much of a performance problem. It might even help performance since you avoid scanning for the first <code>Ã</code> twice.</p>
<pre><code> str.replace("Ã","*")
</code></pre>
<p><a href="https://docs.python.org/3/library/stdtypes.html#str.replace" rel="nofollow"><code>str.replace</code></a> is a method of the class <code>str</code>, not a function in some module called <code>str</code>. You need to call the <code>replace</code> method on your payload. So either use something like <code>parser.setPayload(parser.getPayload().replace("Ã","*"))</code> or store the payload in a local variable which you can modify.</p>
<pre><code> parser.sendGroupMessage(parser.getTargetID(), str(ast.literal_eval(parser.getPayload()[7:])))
</code></pre>
<p>Are you sure you only want to do this in the case there is a <code>Ã</code> in the input? Anyway, read <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow">the docs for <code>ast.literal_eval</code></a>: it will not evaluate operators. So this is not what you need. If you need to evaluate operators, you may call <code>eval</code>, but if you do, you <strong>must</strong> sanitize your input first to ensure it doesn't do anything evil.</p>
<p>I'd do something like this:</p>
<pre><code>sanitizeRegexp = re.compile(r"\A[0-9+\-*/ ]*\Z") # only allow these
payload = parser.getPayload()
if payload.lower()[:6] == "solve:":
payload = payload[7:] # strip command
payload = payload.replace("Ã", "*")
if sanitizeRegexp.match(payload):
result = str(eval(payload))
else:
result = "Invalid input: " + payload
parser.sendGroupMessage(parser.getTargetID(), result)
</code></pre>
| 0 | 2016-10-07T14:25:46Z | [
"python",
"math",
"character-encoding",
"special-characters",
"identifier"
]
|
Creating a new tmux session from within a session | 39,909,581 | <p>I am using a voice assistant on my RPi, but because of a certain tmux session I have, it won't work.</p>
<p>That is fine, because I came up with an idea to fix this.</p>
<p>Since my voice assistant is written in Python, I thought I could use the <code>os</code> module to do a <code>os.system('tmux kill-session -t Radio')</code>.</p>
<p>This works fine, but when I tried to create the session the session again, using <code>tmux new-session -d -s Radio 'python blah blah'</code>, it doesn't work, because I am trying to create a tmux session from within another.</p>
<p>Upon google, I found various suggestions, all of which didn't really fit my need (nor could be adapted).</p>
<p>What command could I execute from within Python from within a Tmux session, that could create a new tmux session, name it, and auto enter a command, but not be tied to the current session (Meaning I wouldn't have to attach to the voice assistant session to attach to the other one)</p>
| 0 | 2016-10-07T04:47:06Z | 39,909,839 | <p>You'll need to unset the TMUX environment variable</p>
<pre><code># assuming this is the shell inside tmux
$ export TMUX=
# now you can run tmux inside tmux
$ tmux
</code></pre>
<p>So the important line is <code>export TMUX=</code> prior to the inception of tmux.</p>
| 0 | 2016-10-07T05:11:46Z | [
"python",
"raspberry-pi",
"tmux"
]
|
Python listing all files in directory | 39,909,655 | <p>Can anybody help me creating a function which will creating a list all files under certain directory by using pathlib library?</p>
<p>Here, I have a</p>
<p><a href="http://i.stack.imgur.com/jJMwB.png" rel="nofollow"><img src="http://i.stack.imgur.com/jJMwB.png" alt="enter image description here"></a></p>
<p>I have </p>
<ul>
<li><p>c:\desktop\test\A\A.txt</p></li>
<li><p>c:\desktop\test\B\B_1\B.txt</p></li>
<li><p>c:\desktop\test\123.txt</p></li>
</ul>
<p>I expected to have a single list which would have path above, but my code return me nested list.</p>
<p>Here is my code:
from pathlib import Path</p>
<pre><code>def searching_all_files(directory: Path):
file_list = [] # A list for storing files existing in directories
for x in directory.iterdir():
if x.is_file():
file_list.append(x)
else:
file_list.append(searching_all_files(directory/x))
return file_list
p = Path('C:\\Users\\akrio\\Desktop\\Test')
print(searching_all_files(p))
</code></pre>
<p>Hope anybody could correct me. Thank you</p>
| 0 | 2016-10-07T04:54:43Z | 39,909,791 | <pre><code>def searching_all_files(directory: Path):
file_list = [] # A list for storing files existing in directories
for x in directory.iterdir():
if x.is_file():
file_list.append(x)#here should be appended
else:
file_list.extend(searching_all_files(directory/x))# need to be extended
return file_list
</code></pre>
| 0 | 2016-10-07T05:06:20Z | [
"python",
"pathlib"
]
|
Python listing all files in directory | 39,909,655 | <p>Can anybody help me creating a function which will creating a list all files under certain directory by using pathlib library?</p>
<p>Here, I have a</p>
<p><a href="http://i.stack.imgur.com/jJMwB.png" rel="nofollow"><img src="http://i.stack.imgur.com/jJMwB.png" alt="enter image description here"></a></p>
<p>I have </p>
<ul>
<li><p>c:\desktop\test\A\A.txt</p></li>
<li><p>c:\desktop\test\B\B_1\B.txt</p></li>
<li><p>c:\desktop\test\123.txt</p></li>
</ul>
<p>I expected to have a single list which would have path above, but my code return me nested list.</p>
<p>Here is my code:
from pathlib import Path</p>
<pre><code>def searching_all_files(directory: Path):
file_list = [] # A list for storing files existing in directories
for x in directory.iterdir():
if x.is_file():
file_list.append(x)
else:
file_list.append(searching_all_files(directory/x))
return file_list
p = Path('C:\\Users\\akrio\\Desktop\\Test')
print(searching_all_files(p))
</code></pre>
<p>Hope anybody could correct me. Thank you</p>
| 0 | 2016-10-07T04:54:43Z | 39,909,947 | <p>You can use os.listdir(). It will get you everything that's in a directory - files and directories.</p>
<p>If you want just files, you could either filter this down using os.path:</p>
<pre><code>from os import listdir
from os.path import isfile, join
onlyfiles = [files for files in listdir(mypath) if isfile(join(mypath, files))]
</code></pre>
<p>or you could use os.walk() which will yield two lists for each directory it visits - splitting into files and directories for you. If you only want the top directory you can just break the first time it yields</p>
<pre><code>from os import walk
files = []
for (dirpath, dirnames, filenames) in walk(mypath):
files.extend(filenames)
break
</code></pre>
| 1 | 2016-10-07T05:20:05Z | [
"python",
"pathlib"
]
|
Python listing all files in directory | 39,909,655 | <p>Can anybody help me creating a function which will creating a list all files under certain directory by using pathlib library?</p>
<p>Here, I have a</p>
<p><a href="http://i.stack.imgur.com/jJMwB.png" rel="nofollow"><img src="http://i.stack.imgur.com/jJMwB.png" alt="enter image description here"></a></p>
<p>I have </p>
<ul>
<li><p>c:\desktop\test\A\A.txt</p></li>
<li><p>c:\desktop\test\B\B_1\B.txt</p></li>
<li><p>c:\desktop\test\123.txt</p></li>
</ul>
<p>I expected to have a single list which would have path above, but my code return me nested list.</p>
<p>Here is my code:
from pathlib import Path</p>
<pre><code>def searching_all_files(directory: Path):
file_list = [] # A list for storing files existing in directories
for x in directory.iterdir():
if x.is_file():
file_list.append(x)
else:
file_list.append(searching_all_files(directory/x))
return file_list
p = Path('C:\\Users\\akrio\\Desktop\\Test')
print(searching_all_files(p))
</code></pre>
<p>Hope anybody could correct me. Thank you</p>
| 0 | 2016-10-07T04:54:43Z | 39,911,421 | <pre><code>from pathlib import Path
from pprint import pprint
def searching_all_files(directory):
dirpath = Path(directory)
assert(dirpath.is_dir())
file_list = []
for x in dirpath.iterdir():
if x.is_file():
file_list.append(x)
elif x.is_dir():
file_list.extend(searching_all_files(x))
return file_list
pprint(searching_all_files('.'))
</code></pre>
| 0 | 2016-10-07T07:08:56Z | [
"python",
"pathlib"
]
|
Using Python to Read Rows of CSV Files With Column Content containing Comma | 39,909,740 | <p>I am trying to parse this CSV and print out the various columns separately.</p>
<p>However my code is having difficulty doing so possibly due to the commas in the addresses, making it hard to split them into 3 columns.</p>
<p>How can this be done?</p>
<p><strong>Code</strong></p>
<pre><code>with open("city.csv") as f:
for row in f:
print row.split(',')
</code></pre>
<p><strong>Result</strong></p>
<pre><code>['original address', 'latitude', 'longitude\n']
['"2 E Main St', ' Madison', ' WI 53703"', '43.074691', '-89.384168\n']
['"Minnesota State Capitol', ' St Paul', ' MN 55155"', '44.955143', '-93.102307\n']
['"500 E Capitol Ave', ' Pierre', ' SD 57501"', '44.36711', '-100.346342\n']
</code></pre>
<p><strong>city.csv</strong></p>
<pre><code>original address,latitude,longitude
"2 E Main St, Madison, WI 53703",43.074691,-89.384168
"Minnesota State Capitol, St Paul, MN 55155",44.955143,-93.102307
"500 E Capitol Ave, Pierre, SD 57501",44.36711,-100.346342
</code></pre>
| 0 | 2016-10-07T05:02:24Z | 39,909,989 | <p>If you just want to parse the file, I would recommend using <a href="http://pandas.pydata.org/" rel="nofollow">Pandas Library</a> </p>
<pre><code>import pandas as pd
data_frame = pd.read_csv("city.csv")
</code></pre>
<p>which gives you a data frame that looks like this in iPython notebook.
<a href="http://i.stack.imgur.com/ZPW6j.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZPW6j.png" alt="resulting data frame"></a></p>
| 1 | 2016-10-07T05:23:21Z | [
"python",
"python-2.7",
"csv"
]
|
Using Python to Read Rows of CSV Files With Column Content containing Comma | 39,909,740 | <p>I am trying to parse this CSV and print out the various columns separately.</p>
<p>However my code is having difficulty doing so possibly due to the commas in the addresses, making it hard to split them into 3 columns.</p>
<p>How can this be done?</p>
<p><strong>Code</strong></p>
<pre><code>with open("city.csv") as f:
for row in f:
print row.split(',')
</code></pre>
<p><strong>Result</strong></p>
<pre><code>['original address', 'latitude', 'longitude\n']
['"2 E Main St', ' Madison', ' WI 53703"', '43.074691', '-89.384168\n']
['"Minnesota State Capitol', ' St Paul', ' MN 55155"', '44.955143', '-93.102307\n']
['"500 E Capitol Ave', ' Pierre', ' SD 57501"', '44.36711', '-100.346342\n']
</code></pre>
<p><strong>city.csv</strong></p>
<pre><code>original address,latitude,longitude
"2 E Main St, Madison, WI 53703",43.074691,-89.384168
"Minnesota State Capitol, St Paul, MN 55155",44.955143,-93.102307
"500 E Capitol Ave, Pierre, SD 57501",44.36711,-100.346342
</code></pre>
| 0 | 2016-10-07T05:02:24Z | 39,909,992 | <p>You should always use <code>csv</code> module</p>
<pre><code>import csv
with open("city.csv") as f:
csv_reader = csv.reader(f):
for row in csv_reader:
print row
</code></pre>
| 1 | 2016-10-07T05:23:40Z | [
"python",
"python-2.7",
"csv"
]
|
Is it possible to check for global variables in IPython when running a file? | 39,909,760 | <p>I have a file like so:</p>
<pre><code>import pandas a pd
def a_func():
print 'doing stuff'
if __name__ == "__main__":
if 'data' not in globals():
print 'loading data...'
data = pd.read_csv('datafile.csv')
</code></pre>
<p>When I run the file in IPython with <code>run file.py</code>, it always loads the data, but when I print <code>globals.keys()</code> in IPython, I can see the <code>data</code> variable. Is there a way to access the global variables from IPython from within my <code>file.py</code> script, so I don't have to load the data every time I run the script in IPython?</p>
| 2 | 2016-10-07T05:03:32Z | 39,909,953 | <p>Everytime a python file is executed the globals() dictionary is reset by the interpreter. So if you will try to do something like </p>
<pre><code>print globals().keys()
</code></pre>
<p>you can see that 'data' is not in globals. This dictionary gets updated as the program runs. So I don't think you can refer to the globals() of the IPython in the program.</p>
<p>check this <a href="https://docs.python.org/2/faq/programming.html#how-can-i-have-modules-that-mutually-import-each-other" rel="nofollow">link</a> ,according to it, globals are emptied.</p>
| 0 | 2016-10-07T05:20:36Z | [
"python",
"ipython"
]
|
How to print just the content of the help string of a specific argument of ArgParse | 39,909,927 | <p>Is there a way to access the help strings for specific arguments of the argument parser library object? </p>
<p>I want to print the help string content if the option was present on the command line. <em>Not</em> the complete help text that Argument Parser can display via ArgumentParser.print_help .</p>
<p>So something along those lines:</p>
<pre><code>parser = argparse.ArgumentParser()
parser.add_argument("-d", "--do_x", help='the program will do X')
if do_x:
print(parser.<WHAT DO I HAVE TO PUT HERE?>('do_x')
</code></pre>
<p>And this is the required behavior</p>
<p>$program -d</p>
<blockquote>
<p>the program will do X</p>
</blockquote>
| 4 | 2016-10-07T05:19:01Z | 39,910,425 | <p>There is <code>parser._option_string_actions</code> which is mapping between option strings (<code>-d</code> or <code>--do_x</code>) and <a href="https://docs.python.org/3/library/argparse.html#action-classes" rel="nofollow"><code>Action</code> objects</a>. <code>Action.help</code> attribute holds the help string.</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--do_x", action='store_true',
help='the program will do X')
args = parser.parse_args()
if args.do_x:
print(parser._option_string_actions['--do_x'].help)
# OR print(parser._option_string_actions['-d'].help)
</code></pre>
| 3 | 2016-10-07T06:01:55Z | [
"python",
"argparse"
]
|
How to print just the content of the help string of a specific argument of ArgParse | 39,909,927 | <p>Is there a way to access the help strings for specific arguments of the argument parser library object? </p>
<p>I want to print the help string content if the option was present on the command line. <em>Not</em> the complete help text that Argument Parser can display via ArgumentParser.print_help .</p>
<p>So something along those lines:</p>
<pre><code>parser = argparse.ArgumentParser()
parser.add_argument("-d", "--do_x", help='the program will do X')
if do_x:
print(parser.<WHAT DO I HAVE TO PUT HERE?>('do_x')
</code></pre>
<p>And this is the required behavior</p>
<p>$program -d</p>
<blockquote>
<p>the program will do X</p>
</blockquote>
| 4 | 2016-10-07T05:19:01Z | 39,910,688 | <p><code>parser._actions</code> is a list of the <code>Action</code> objects. You can also grab object when creating the parser.</p>
<pre><code>a=parser.add_argument(...)
...
If args.do_x:
print a.help
</code></pre>
<p>Play with <code>argparse</code> in an interactive session. Look at <code>a</code> from such an assignment.</p>
| 2 | 2016-10-07T06:20:34Z | [
"python",
"argparse"
]
|
How do you show an error message when a test does not throw an expected exception? | 39,909,935 | <p>I am new to python. I wanted to test if my code throws an exception. I got the code from here: <a href="http://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception">How do you test that a Python function throws an exception?</a></p>
<pre><code>import mymod
import unittest
class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeCoolException, mymod.myfunc, compulsory_argument)
</code></pre>
<p>Now, I also want to display a message if the exception is not thrown. How do I do that ? The python docs do not mention it clearly. I added the message after "compulsory_argument" and it failed.</p>
<p><strong>EDIT:</strong> I tried the first answer with modifications and got an exception. What is my mistake here ?</p>
<pre><code>import unittest
def sayHelloTo(name):
print("Hello " + name)
class MyTestCase(unittest.TestCase):
def test1(self):
person = "John"
with self.assertRaises(Exception, "My insightful message"):
sayHelloTo(person)
</code></pre>
<p><strong>Error:</strong></p>
<pre><code>Error
Traceback (most recent call last):
File "C:\tests\tester.py", line 9, in test1
with self.assertRaises(Exception, "My insightful message"):
AttributeError: __exit__
</code></pre>
| 0 | 2016-10-07T05:19:27Z | 39,910,294 | <p>As of python 3.3, <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow">assertRaises</a> can be used as a context manager with a message:</p>
<pre><code>import unittest
def sayHelloTo(name):
print("Hello " + name)
class MyTestCase(unittest.TestCase):
def test1(self):
person = "John"
with self.assertRaises(Exception, msg="My insightful message"):
sayHelloTo(person)
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>Results in</p>
<pre><code>Hello John
F
======================================================================
FAIL: test1 (__main__.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "r.py", line 10, in test1
sayHelloTo(person)
AssertionError: Exception not raised : My insightful message
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
</code></pre>
| 2 | 2016-10-07T05:50:38Z | [
"python",
"unit-testing",
"exception"
]
|
How do you show an error message when a test does not throw an expected exception? | 39,909,935 | <p>I am new to python. I wanted to test if my code throws an exception. I got the code from here: <a href="http://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception">How do you test that a Python function throws an exception?</a></p>
<pre><code>import mymod
import unittest
class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeCoolException, mymod.myfunc, compulsory_argument)
</code></pre>
<p>Now, I also want to display a message if the exception is not thrown. How do I do that ? The python docs do not mention it clearly. I added the message after "compulsory_argument" and it failed.</p>
<p><strong>EDIT:</strong> I tried the first answer with modifications and got an exception. What is my mistake here ?</p>
<pre><code>import unittest
def sayHelloTo(name):
print("Hello " + name)
class MyTestCase(unittest.TestCase):
def test1(self):
person = "John"
with self.assertRaises(Exception, "My insightful message"):
sayHelloTo(person)
</code></pre>
<p><strong>Error:</strong></p>
<pre><code>Error
Traceback (most recent call last):
File "C:\tests\tester.py", line 9, in test1
with self.assertRaises(Exception, "My insightful message"):
AttributeError: __exit__
</code></pre>
| 0 | 2016-10-07T05:19:27Z | 39,936,068 | <blockquote>
<p>Now, I also want to display a message if the exception is not thrown. How do I do that ?</p>
</blockquote>
<p>The general philosophy of <em>unittest</em> is for the tests to be silent when they succeed and only become verbose when they fail. Accordingly, the API provides a "msg" keyword argument for the unsuccessful case but does not offer an alternative for the successful case.</p>
<p>That said, another part of the philosophy works in your favor. In general, test cases internally raise an exception when a testcase fails. That means that if you want to display a message when there is a success, you just add another statement <em>after</em> the test:</p>
<pre><code>with self.assertRaises(TypeError, msg='Oh no, I did not get a TypeError')
somecode()
logging.info('Yippee, we got a TypeError!') # Runs after a successful test
</code></pre>
| 0 | 2016-10-08T18:46:22Z | [
"python",
"unit-testing",
"exception"
]
|
How to view the source code of numpy.random.exponential? | 39,910,050 | <p>I want to see if <code>numpy.random.exponential</code> was implemented using F^{-1} (U) method, where F is the c.d.f of exponential distribution and U is uniform distribution. </p>
<p>I tried <code>numpy.source(random.exponential)</code>, but returned '<em>Not available for this object'</em>. Does it mean this function is not written in Python?</p>
<p>I also tried <code>inspect.getsource(random.exponential)</code>, but returned an error saying it's not module, function, etc.</p>
| 3 | 2016-10-07T05:28:28Z | 39,910,139 | <p>numpy's sources are <a href="https://github.com/numpy/numpy" rel="nofollow">at github</a> so you can use github's <a href="https://github.com/numpy/numpy/search?utf8=%E2%9C%93&q=exponential" rel="nofollow">source-search</a>.</p>
<p>As often, these parts of the library are not implemented in pure python.</p>
<p>The python-parts (in regards to your question) are <a href="https://github.com/numpy/numpy/blob/7ccf0e08917d27bc0eba34013c1822b00a66ca6d/numpy/random/mtrand/mtrand.pyx" rel="nofollow">here</a>:</p>
<p>The more relevant code-part is from <a href="https://github.com/numpy/numpy/blob/c90d7c94fd2077d0beca48fa89a423da2b0bb663/numpy/random/mtrand/distributions.c" rel="nofollow">distributions.c</a>:</p>
<pre><code>double rk_standard_exponential(rk_state *state)
{
/* We use -log(1-U) since U is [0, 1) */
return -log(1.0 - rk_double(state));
}
double rk_exponential(rk_state *state, double scale)
{
return scale * rk_standard_exponential(state);
}
</code></pre>
| 5 | 2016-10-07T05:36:53Z | [
"python",
"numpy",
"random"
]
|
How to view the source code of numpy.random.exponential? | 39,910,050 | <p>I want to see if <code>numpy.random.exponential</code> was implemented using F^{-1} (U) method, where F is the c.d.f of exponential distribution and U is uniform distribution. </p>
<p>I tried <code>numpy.source(random.exponential)</code>, but returned '<em>Not available for this object'</em>. Does it mean this function is not written in Python?</p>
<p>I also tried <code>inspect.getsource(random.exponential)</code>, but returned an error saying it's not module, function, etc.</p>
| 3 | 2016-10-07T05:28:28Z | 39,920,776 | <p>A lot of numpy functions are written with C/C++ and Fortran. <code>numpy.source()</code> returns the source code only for objects written in Python. It is written on <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.source.html" rel="nofollow">NumPy website</a>.</p>
<p>You can find all of the NumPy functions on their GitHub page. One that you need is written in C. Here is the link to the <a href="https://github.com/numpy/numpy/blob/master/numpy/random/mtrand/distributions.c" rel="nofollow">file</a>.</p>
| 1 | 2016-10-07T15:23:22Z | [
"python",
"numpy",
"random"
]
|
Python PIL image warping / Affine transformations | 39,910,190 | <p>Using Python PIL I want to transform input images in such a way that they seem to be in perspective. Most of the answers I have found are about rotating etc. The images below show one of the effects I am aiming at. Similarly I would like to do this not only from front to back, but also from left to right and vice versa. Another effect I would like is to warp the image in a way that the center is closer and the edges are more distant.</p>
<p>How should I call <code>im.transform</code> to get this effect? And why? </p>
<p>Input Image:</p>
<p><a href="http://i.stack.imgur.com/dHGcB.png" rel="nofollow"><img src="http://i.stack.imgur.com/dHGcB.png" alt="Input Image"></a></p>
<p>Output Effect:</p>
<p><a href="http://i.stack.imgur.com/GicNm.png" rel="nofollow"><img src="http://i.stack.imgur.com/GicNm.png" alt="Ouput Image"></a></p>
| 0 | 2016-10-07T05:42:55Z | 39,942,374 | <p>I believe you are looking for <a href="https://en.wikipedia.org/wiki/3D_projection" rel="nofollow">perspective transformations</a>. You can do it with Pillow in following way:</p>
<pre><code>transformed = image.transform(
image.size, Image.PERSPECTIVE,
[
a0, a1, a2,
a3, a4, a5,
a6, a7
],
Image.BILINEAR
)
</code></pre>
<p>Where a0-a7 is coefficients used for transformation in this way (from sources, Geometry.c):</p>
<pre><code>xout = (a0 * xin + a1 * yin + a2) / (a6 * xin + a7 * yin + 1);
yout = (a3 * xin + a4 * yin + a5) / (a6 * xin + a7 * yin + 1);
</code></pre>
| 1 | 2016-10-09T10:11:02Z | [
"python",
"python-imaging-library"
]
|
Need help understanding a short python code | 39,910,208 | <p>I want to emphasis that this is not a ask for completing my homework or job: I am studying the LZW algorithm for gif file compression by reading someone's code on <a href="https://github.com/j-s-n/mazes/blob/master/python2/GIF_maze.py" rel="nofollow">github</a>, and got confused by a code block here:</p>
<pre><code>class DataBlock(object):
def __init__ (self):
self.bitstream = bytearray()
self.pos = 0
def encode_bits (self, num, size):
"""
Given a number *num* and a length in bits *size*, encode *num*
as a *size* length bitstring at the current position in the bitstream.
"""
string = bin(num)[2:]
string = '0'*(size - len(string)) + string
for digit in reversed(string):
if len(self.bitstream) * 8 <= self.pos:
self.bitstream.append(0)
if digit == '1':
self.bitstream[-1] |= 1 << self.pos % 8
self.pos += 1
</code></pre>
<p>What I cannot understand is the <code>for</code> loop in the function <code>encode_bits()</code>:</p>
<pre><code>for digit in reversed(string):
if len(self.bitstream) * 8 <= self.pos:
self.bitstream.append(0)
if digit == '1':
self.bitstream[-1] |= 1 << self.pos % 8
self.pos += 1
</code></pre>
<p>Here is my guess (depend on his comment):</p>
<p>The function <code>encode_bits()</code> will turn an input integer <code>num</code> into a binary string of length <code>size</code> (padding zeroes at left if needed) and reverse the string, and append the digits to <code>bitstream</code> one by one. Hence
suppose <code>s=DataBlock()</code>, then <code>s.encode_bits(3, 3)</code> would firstly turn 3 into <code>011</code> (padding a zero at left to make it length 3) and reverse it to <code>110</code>, and then append <code>110</code> to <code>self.bitstream</code>, hence the result should be <code>bytearray('110').</code> But as I run the code the result gives <code>bytearray(b'\x03')</code>, not as expected. Further more, <code>\x03</code> is one byte, not 3 bits, conflicts with his comment, I cannot understand why? </p>
<p>I forgot to add that his code runs and gives correct output hence there's something wrong in my understanding.</p>
| 1 | 2016-10-07T05:44:47Z | 39,911,790 | <p>Try looking at it this way:</p>
<ul>
<li>You will be given a <code>bytearray</code> object (call it <code>x</code> for the moment).</li>
<li>How many bytes are in the object? (Obviously, it's just <code>len(x)</code>.)</li>
<li>How many <em>bits</em> are in the object? (This is an exercise; please calculate the answer.)</li>
</ul>
<p>Once you've done that, suppose we start with no (zero) bytes in <code>x</code>, i.e., <code>x</code> is a <code>bytearray(b'')</code>. How many <em>bytes</em> do we need to add (<code>x.append(...)</code>) in order to store three <em>bits</em>? What if we want to store eight bits? What if we want to store ten bits?</p>
<p>Again, these are exercises. Calculate the answers and you should be enlightened.</p>
<p>(Incidentally, this technique, of compressing some number of sub-objects into some larger space, is called <em>packing</em>. In mathematics the problem is <a href="https://en.wikipedia.org/wiki/Packing_problems" rel="nofollow">generalized</a>, while in computers it is <a href="https://en.wikipedia.org/wiki/Data_structure_alignment" rel="nofollow">often more limited</a>.)</p>
| 0 | 2016-10-07T07:30:26Z | [
"python"
]
|
Why does PyQt's pyuic ignore default margins? | 39,910,217 | <p>In Qt Designer I can see <code>verticalLayout</code> has a default margin (13px), but pyuic5 always gives me <code>self.verticalLayout.setContentsMargins(0, 0, 0, 0)</code>. In <code>uiparser.py:443</code> I found this comment:</p>
<blockquote>
<p>A layout widget should, by default, have no margins.</p>
</blockquote>
<p>and it sets the margins to <code>(0,0,0,0)</code>. Another comment also says:</p>
<blockquote>
<p>A plain QWidget is a layout widget unless it's parent is a
QMainWindow. Note that the corresponding uic test is a little more
complicated as it involves features not supported by pyuic.</p>
</blockquote>
<p>What does this mean? I'm using PyQt-5.7, and here is my ui file:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>configDialog</class>
<widget class="QDialog" name="configDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>566</width>
<height>552</height>
</rect>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="general">
<attribute name="title">
<string>General</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
</code></pre>
| 2 | 2016-10-07T05:45:23Z | 39,922,915 | <p>There is a <a href="http://riverbankcomputing.com/pipermail/pyqt/2015-December/036659.html" rel="nofollow">PyQt mailing list thread</a> on this, which seems to have resulted in the default margins being forced to zero for certain widgets. I don't know whether the behaviour of the C++ uic tool has changed since then, but in Qt-5.7 it certainly doesn't behave the same way as pyuic does.</p>
<p>This can be checked in Qt Designer by selecting View -> View code. When the margins are all set to their default values, the C++ uic tool does not generate a <code>setContentsMargins</code> line at all. And if <strong>one</strong> margin is set, it will set the other values to minus one. When a margin is not set, or set to minus one, the layout will use whatever value is specified by the current style.</p>
<p>In contrast, pyuic always explicitly resets to zero any margin which is not set, or set to minus one - which effectively overrides the current style. It's hard to see how this can be the correct behaviour - so maybe it's a regression?</p>
| 1 | 2016-10-07T17:30:02Z | [
"python",
"qt",
"layout",
"pyqt",
"qt-designer"
]
|
CPython 2.7 + Java | 39,910,350 | <p>My major program is written in Python 2.7 (on Mac) and need to leverage some function which is written in a Java 1.8, I think CPython cannot import Java library directly (different than Jython)?</p>
<p>If there is no solution to call Java from CPython, could I integrate in this way -- wrap the Java function into a Java command line application, Python 2.7 call this Java application (e.g. using <code>os.system</code>) by passing command line parameter as inputs, and retrieve its console output?</p>
<p>regards,
Lin</p>
| 0 | 2016-10-07T05:54:22Z | 39,929,049 | <ul>
<li>If you have lot of dependcieis on Java/JVM, you can consider using <code>Jython</code>.</li>
<li>If you would like to develop a scalable/maintainable application, consider using microservices and keep Java and Python components separate.</li>
<li>If your call to Java is simple and it is easy to capture the output and failure, you can go ahead with this running the system command to invoke Java parts.</li>
</ul>
| 1 | 2016-10-08T05:34:34Z | [
"java",
"python",
"osx",
"python-2.7",
"cpython"
]
|
Determine length of NumberLong in Python | 39,910,423 | <p>I have some documents in my MongoDB collection, some of which contain NumberLong values :</p>
<pre><code>{ "_id" : ObjectId("57e4d18df4733211b613f199"), "parentid" : "P1000016", "phone" : NumberLong("9819733299") }
{ "_id" : ObjectId("57e4d18df4733211b613f19a"), "parentid" : "P1000014", "phone" : "24306574|9920599404||9920840077|865" }
{ "_id" : ObjectId("57e4d18df4733211b613f19b"), "parentid" : "P1000017", "phone" : "25821154|25821188|" }
</code></pre>
<p>I'm importing them into my python code and extracting each number using split (if I have multiple number sets in phone) or otherwise, directly appending to a list.</p>
<p>But I want only those numbers in my list whose length is greater than 6. </p>
<p>So I tried using this:</p>
<pre><code>#Initializing MongoDB client
client = MongoClient()
#Connection
db = client.mumbai
collection = db.mumbaiLive
for post in collection.find():
shops.append(post)
for shop in shops:
phones = shop["phone"].split("|")
for eachPhone in phones:
if (len(eachPhone) < 6):
pass
</code></pre>
<p>It works fine until it encounters a NumberLong value.
When I perform </p>
<p><code>print "len = ", len(eachPhone)</code>, I get </p>
<pre><code>len =
</code></pre>
<p>I even tried converting it into string first but got the same result.</p>
<p>What I want : I want to skip 'pass'ing the NumberLong values using length check or any other method (like determining whether a value is NumberLong or not).</p>
| 0 | 2016-10-07T06:01:28Z | 39,912,136 | <p>Depending on your use case, you can either add a filter to your query, to only return field <code>phone</code> where the value is string by utilising <a href="https://docs.mongodb.com/manual/reference/operator/query/type/#type" rel="nofollow">$type</a></p>
<pre><code>client = MongoClient()
db = client.database
collection = db.collection
for document in collection.find({"phone":{"$type":"string"}}):
print document
</code></pre>
<p>Which would 'skip' passing <code>phone</code> containing <code>NumberLong</code> value to your function. </p>
<p>Alternatively, if you would like to process <code>phone</code> with <code>NumberLong</code> value in a different manner you can utilise Python <a href="https://docs.python.org/2/library/functions.html#isinstance" rel="nofollow">isinstance</a>. See below for an example: </p>
<pre><code>for doc in collection.find():
if isinstance(doc["phones"], long):
print("Number of digits: %s" % len(str(doc["phones"])))
else:
print("Number is not NumberLong")
</code></pre>
<p>If you are using Python 2, you have to detect <code>long</code>. If you are using Python 3, you can just detect <code>int</code> . </p>
| -1 | 2016-10-07T07:50:15Z | [
"python",
"mongodb",
"pymongo"
]
|
Putting a variable value into a input's string | 39,910,547 | <p>Is there anyway to have a variable be in the string of an input?</p>
<pre><code>score = float(input("Test", grade, "-- Enter score: "))
</code></pre>
<p>I keep getting:</p>
<p>TypeError: input expected at most 1 arguments, got 3</p>
| 0 | 2016-10-07T06:10:39Z | 39,910,602 | <p>You are passing 3 strings, should be only one. You're incorrectly concatenating string. Use <code>format</code> for that</p>
<pre><code>score = float(input("Test {} -- Enter score: ".format(grade)))
</code></pre>
| 1 | 2016-10-07T06:14:46Z | [
"python",
"variables",
"input"
]
|
Putting a variable value into a input's string | 39,910,547 | <p>Is there anyway to have a variable be in the string of an input?</p>
<pre><code>score = float(input("Test", grade, "-- Enter score: "))
</code></pre>
<p>I keep getting:</p>
<p>TypeError: input expected at most 1 arguments, got 3</p>
| 0 | 2016-10-07T06:10:39Z | 39,910,699 | <p>You can use % or format to put variable into string:</p>
<pre><code>score = float(input("Test %s -- Enter score: " % grade))
</code></pre>
<p>or </p>
<pre><code>score = float(input("Test {} -- Enter score: ".format(grade)))
</code></pre>
| 0 | 2016-10-07T06:21:39Z | [
"python",
"variables",
"input"
]
|
Putting a variable value into a input's string | 39,910,547 | <p>Is there anyway to have a variable be in the string of an input?</p>
<pre><code>score = float(input("Test", grade, "-- Enter score: "))
</code></pre>
<p>I keep getting:</p>
<p>TypeError: input expected at most 1 arguments, got 3</p>
| 0 | 2016-10-07T06:10:39Z | 39,915,426 | <p>Your error is because the input function received more than 1 argument. It received:</p>
<ol>
<li>"Test"</li>
<li>grade</li>
<li>"-- Enter score: "</li>
</ol>
<p>You need to combine those three elements into one, the best way would be using a formatter (%), allowing Python to interpret it as one string:</p>
<pre><code>score = float(input("Test %d -- Enter score: " % grade))
</code></pre>
| 0 | 2016-10-07T10:47:55Z | [
"python",
"variables",
"input"
]
|
Orders of growth involving both recursion and two inner for loops | 39,910,580 | <p>I have attempted the below question but I am uncertain whether I am correct or not. I have arrived at the conclusion that it is a big theta of n^2 function. My reasoning is that the inner 2 loops for i and for j will amount to a sequence of operations, 0, 1, 2, 3, 4, 5....x -1, which can be translated into (x * x - 1) /2 by the arithmetic operation. However, the outer recursive call kind of trips me up. I am tempted to look at the outer recursive call as yet another while loop but I fought it off because it isn't exactly another while loop or for loop because x also changes. Can someone help me arrive at a better understanding of the below question? </p>
<pre><code> def foo(x):
if x < 1:
return 'boo'
for i in range(x):
for j in range(i):
return foo(i + j)
return foo(x-1)
</code></pre>
<p>REVISION: I just ran this code through my python interpreter and turns out it will be constant time as it is a trick question. The reason being, the return statement will just evaluate to foo(1), and then 'boo' gets outputted no matter what size of n you are at. </p>
<p>But----> What if I were to change my code to the following. Is the run time now theta(n^2) or theta(n^3)? </p>
<pre><code> def foo(x):
if x < 1:
return 'boo'
for i in range(x):
for j in range(i):
print(i + j)
return foo(x-1)
</code></pre>
| 0 | 2016-10-07T06:13:02Z | 39,911,252 | <p><strong>EDIT:</strong> First there was <code>i+i</code> in question but now there is <code>i+j</code> so now my answer is wrong.</p>
<hr>
<p>When <code>x < 1</code> it prints 'boo' - nothing intersting.</p>
<p>When <code>x >= 1</code> then you can reach loops</p>
<pre><code>for i in range(x):
for j in range(i):
return foo(i+i)
</code></pre>
<p>so let <code>x = 1</code> and you have</p>
<pre><code>for i in range(1):
for j in range(i):
return foo(i+i)
</code></pre>
<p>so let <code>i = 0</code> - and you have </p>
<pre><code> for j in range(0):
</code></pre>
<p>and it will newer run </p>
<p>so let <code>i = 1</code> - and you have </p>
<pre><code> for j in range(1):
</code></pre>
<p>and for <code>j = 0</code> you can run </p>
<pre><code> return foo(2)
</code></pre>
<p>and you return to the beginnig of this description.<br>
And you will again get <code>return foo(2)</code>. Check it on your own. </p>
<p>So for 'x >= 1' you always get <code>return foo(2)</code>.<br>
So you can reduce this code to </p>
<pre><code>def foo(x):
if x < 1:
return 'boo'
return foo(2)
</code></pre>
<p>(you will never reach <code>return foo(x-1)</code>)</p>
<p>You have infinite function.</p>
<p>(I hope I'm right)</p>
| -1 | 2016-10-07T06:59:37Z | [
"python",
"recursion",
"runtime"
]
|
Pandas group and record grouped values | 39,910,677 | <p>I have the following dataset:</p>
<pre><code>Code Value
100004 1
1017 1
1017 3
1071 1
1071 3
3039 1
3397 1
3397 3
</code></pre>
<p>I was able to count the Value using pandasDataFrame.groupby('Code', as_index=False).agg('count')</p>
<p>I would like to count and in the same time to record the values in a new column. I want the result to look like the example bellow</p>
<pre><code>Code NoValues Values
100004 1 1
1017 2 1,3
1071 2 1,3
3039 1 1
3397 2 1,3
</code></pre>
<p>Is it possible to do it with pandas?</p>
| 2 | 2016-10-07T06:20:03Z | 39,910,737 | <p>You can use <code>groupby</code> + <code>agg</code>:</p>
<pre><code>df.Value.groupby(df.Code).agg({'Values': lambda g: list(g), 'NumValues': lambda g: len(g)}).reset_index()
</code></pre>
<p>For example:</p>
<pre><code>df = pd.DataFrame({'Code': [1004, 1004, 1007], 'Value': [1, 2, 8]})
>>> df.Value.groupby(df.Code).agg({'Values': lambda g: list(g), 'NumValues': lambda g: len(g)}).reset_index()
Code NumValues Values
0 1004 2 [1, 2]
1 1007 1 [3]
</code></pre>
| 1 | 2016-10-07T06:24:44Z | [
"python",
"pandas"
]
|
python scripts creating csv file, with Archive check box is checked. How to create a csv file not archive? | 39,910,681 | <p>I am facing a strange problem
Whenever my python scripts are creating any csv file, it is making them "Archive".
I mean in properties, Archive check box is checked.
Because of which it can't be read in later part of same script .
How can i create a csv file not archive?
Please help me resolve this problem.</p>
| -1 | 2016-10-07T06:20:21Z | 39,910,994 | <p>Are you running a Windows OS? If yes, then this is not a problem with the Python CSV library. As about the error encountered while reading the CSV; you may want to re-check your python code for any flaws.</p>
<p>The Archive checkbox is actually an attribute of the file on Windows systems that indicates that the file needs to be backed up. Right click on any other file and you should see "Archive" checked.</p>
<p>Here are a couple of links that would give you more information</p>
<p><a href="https://blogs.msdn.microsoft.com/oldnewthing/20090219-00/?p=19093" rel="nofollow">MSDN Technet discussion on File Attributes</a></p>
<p><a href="https://en.wikipedia.org/wiki/Archive_bit" rel="nofollow">Wikipedia article on Archive bit</a></p>
| 1 | 2016-10-07T06:43:25Z | [
"python"
]
|
Unable to download files from S3 bucket | 39,910,911 | <p>I want to download all files from S3 bucket which are in this path <code>All Buckets /abc/or/uploads</code></p>
<p>I tried with this snippet but only managed to get files in <code>All Buckets /abc</code></p>
<p>Changing the path in <code>bucket_list = bucket.list('or/uploads')</code>
this line is not working? why?</p>
<pre><code>import boto
import sys, os
import logging
bucket_name = 'abc'
conn = boto.connect_s3('XXXXXXXXXXXXXX', 'XXXXXXXXXXXXXXXXX+XXXXXXXXXXXXXX')
bucket = conn.get_bucket(bucket_name)
bucket_list = bucket.list('or/uploads')
for key in bucket.list():
try:
res = key.get_contents_to_filename(key.name)
print "done"
except:
logging.info(key.name + ":" + "FAILED")
</code></pre>
| 2 | 2016-10-07T06:38:11Z | 39,912,007 | <p>Amazon S3 does not have folders/directories. It is a flat file structure.
To maintain the appearance of directories, path names are stored as part of the object Key (filename). </p>
<p>Make sure the place where you are downloading the files, have exact same structure i.e.. <code>/abc/or/uploads</code> </p>
<p>snippet </p>
<pre><code>for key in bucket.list('or/uploads'):
try:
res = key.get_contents_to_filename(key.name)
print "done"
except:
logging.info(key.name + ":" + "FAILED")
</code></pre>
<p><a href="https://stackoverflow.com/questions/31918960/boto3-to-download-all-files-from-a-s3-bucket/31929277#31929277">Source</a> </p>
| 0 | 2016-10-07T07:42:20Z | [
"python",
"amazon-web-services",
"amazon-s3"
]
|
Logging each in/out of each function | 39,910,941 | <p>Currently I typically add a log line to my functions with details of the variables that are inputted and returned. However I am looking for an elegant way around this.</p>
<p>Is there a way to log each input to a function and what is returned using some form of magic methods?</p>
<p>Below is an example,</p>
<pre><code>class exampleclass(object):
def __init__(self,size=False):
self.size = size
def funt1(self,weight=None):
return weight
def funt2(self,shape=None):
return shape
</code></pre>
<p>Here I want to log the returned variable and also what is inputted for each function using the smallest amount of code possible.</p>
| 3 | 2016-10-07T06:40:19Z | 39,911,346 | <p>There is a concept of <a href="https://wiki.python.org/moin/PythonDecorators" rel="nofollow">decorators in python</a>. They help you abstract out the common code you want to inject on any function on your will. Make a decorator named <code>log</code> as follows:</p>
<pre><code>import logging
from functools import wraps
def log(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
logging.debug("args - %s", str(args))
logging.debug("kwargs - %s", str(kwargs))
response = func(self, *args, **kwargs)
logging.debug("response - %s", str(response))
return response
return wrapper
</code></pre>
<p>Now, you can use this decorator for any function as follows:</p>
<pre><code>@log
def funt1(self,weight=None):
return weight
</code></pre>
<p>The above code will log all the arguments & their returned values with just 1 line of code.</p>
<p><a href="http://thecodeship.com/patterns/guide-to-python-function-decorators/" rel="nofollow">Here</a> is a good blog on understanding decorators.</p>
| 3 | 2016-10-07T07:04:32Z | [
"python"
]
|
Update PHP variable without refresh | 39,910,958 | <p>I am new in JSON and PHP programming. I am making a web page that allows to view data from <strong>file.py</strong>, those data will be linked in a <code>gauge</code> and updated <code>second by second</code>.</p>
<pre><code> var gauge1;
var x = <?php echo python /home/usr/Desktop/file.py ?> ;
setInterval(function() {
gauge1.refresh(x);
}, 1000);
};
</code></pre>
<p>I can make the gauge shows just the first reading from "file.py" but is stuck there, the only way to update the gauge is refreshing the page and the new reading is shown in the gauge.</p>
<p>I think the problem is in:</p>
<blockquote>
<p>gauge1.refresh(x);</p>
</blockquote>
<p>because when I write:</p>
<blockquote>
<p>gauge1.refresh(getRandomInt(0,50));</p>
</blockquote>
<p>The gauge always show random data, updating a new <code>random data between 0 and 50</code>.</p>
<p>Is there any solution to make the gauge always shows automatically data from <strong>file.py</strong> without refresh the page?</p>
| -2 | 2016-10-07T06:41:07Z | 39,911,166 | <p>You can use ajax to execute a backend script in a time interval like this .</p>
<pre><code>var x=null;
setInterval(retriveData, 300000);
function retriveData() {
$.ajax({url: "pyData.php", success: function(data){
x=data;
}});
}
</code></pre>
<p>And your Php code like this <strong>(pyData.php)</strong></p>
<pre><code><?php
$command = escapeshellcmd('/home/usr/Desktop/file.py');
$output = shell_exec($command);
echo $output;
?>
</code></pre>
<p>You can execute like this </p>
| 0 | 2016-10-07T06:54:46Z | [
"javascript",
"php",
"python",
"html",
"json"
]
|
Pandas Apply returns matrix instead of single column | 39,911,083 | <p>This is probably a stupid question, but I have been trying for a while and I can't seem to get it to work.</p>
<p>I have a dataframe:</p>
<pre><code> df1 = pd.DataFrame({'Type': ['A','A', 'B', 'F', 'C', 'G', 'A', 'E'], 'Other': [999., 999., 999., 999., 999., 999., 999., 999.]})
</code></pre>
<p>I now want to create a new column based on the column <code>Type</code>. For this I have second dataframe:</p>
<pre><code> df2 = pd.DataFrame({'Type':['A','B','C','D','E','F', 'G'],'Value':[1, 1, 2, 3, 4, 4, 5]})
</code></pre>
<p>that I am using as a lookup table.</p>
<p>When I try something like:</p>
<pre><code> df1.apply(lambda x: df2.Value[df2.Type == x['Type']],axis=1)
</code></pre>
<p>I get a matrix instead of a single column:</p>
<pre><code> Out[21]:
0 1 2 4 5 6
0 1 NaN NaN NaN NaN NaN
1 1 NaN NaN NaN NaN NaN
2 NaN 1 NaN NaN NaN NaN
3 NaN NaN NaN NaN 4 NaN
4 NaN NaN 2 NaN NaN NaN
5 NaN NaN NaN NaN NaN 5
6 1 NaN NaN NaN NaN NaN
7 NaN NaN NaN 4 NaN NaN
</code></pre>
<p>What I want however is this:</p>
<pre><code> 0
0 1
1 1
2 1
3 4
4 2
5 5
6 1
7 4
</code></pre>
<p>What am I doing wrong?</p>
| 1 | 2016-10-07T06:49:47Z | 39,911,986 | <p>You can use <code>map</code> to achieve this:</p>
<pre><code>In [62]:
df1['Type'].map(df2.set_index('Type')['Value'],na_action='ignore')
Out[62]:
0 1
1 1
2 1
3 4
4 2
5 5
6 1
7 4
Name: Type, dtype: int64
</code></pre>
<p>If you modified your <code>apply</code> attempt to the following then it would've worked:</p>
<pre><code>In [70]:
df1['Type'].apply(lambda x: df2.loc[df2.Type == x,'Value'].values[0])
Out[70]:
0 1
1 1
2 1
3 4
4 2
5 5
6 1
7 4
Name: Type, dtype: int64
</code></pre>
<p>If we look at what you tried:</p>
<pre><code>df1.apply(lambda x: df2.Value[df2.Type == x['Type']],axis=1)
</code></pre>
<p>this is trying to compare the 'type' and return the 'value' the problem here is that you're returning a Series with the index of <code>df2</code>, this is confusing pandas and causing the matrix to be returned. You can see this if we hard code 'B' as an example:</p>
<pre><code>In [75]:
df2.Value[df2.Type == 'B']
Out[75]:
1 1
Name: Value, dtype: int64
</code></pre>
| 1 | 2016-10-07T07:41:12Z | [
"python",
"pandas",
"apply"
]
|
How to create a TensorProto in c#? | 39,911,330 | <p>This is a snipped of the c# client I created to query the tensorflow server I set up using this tutorial: <a href="https://tensorflow.github.io/serving/serving_inception.html" rel="nofollow">https://tensorflow.github.io/serving/serving_inception.html</a></p>
<pre><code> var channel = new Channel("TFServer:9000", ChannelCredentials.Insecure);
var request = new PredictRequest();
request.ModelSpec = new ModelSpec();
request.ModelSpec.Name = "inception";
var imgBuffer = File.ReadAllBytes(@"sample.jpg");
ByteString jpeg = ByteString.CopyFrom(imgBuffer, 0, imgBuffer.Length);
var jpgeproto = new TensorProto();
jpgeproto.StringVal.Add(jpeg);
jpgeproto.Dtype = DataType.DtStringRef;
request.Inputs.Add("images", jpgeproto); // new TensorProto{TensorContent = jpeg});
PredictionClient client = new PredictionClient(channel);
</code></pre>
<p>I found out that most classes needed to be generated from proto files using protoc </p>
<p>The only thing which I cant find is how to construct the TensorProto. The error I keep getting is : Additional information: Status(StatusCode=InvalidArgument, Detail="tensor parsing error: images")</p>
<p>There is a sample client (<a href="https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/inception_client.py" rel="nofollow">https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/inception_client.py</a>) byt my Python skills are not sufficient to understand the last bit.</p>
| 1 | 2016-10-07T07:03:20Z | 40,091,359 | <p>I also implemented that client in another language (Java). </p>
<p>Try to change </p>
<pre><code>jpgeproto.Dtype = DataType.DtStringRef;
</code></pre>
<p>to </p>
<pre><code>jpgeproto.Dtype = DataType.DtString;
</code></pre>
<p>You may also need to add a tensor shape with a dimension to your tensor proto. Here's my working solution in Java, should be similar in C#:</p>
<pre><code>TensorShapeProto.Dim dim = TensorShapeProto.Dim.newBuilder().setSize(1).build();
TensorShapeProto shape = TensorShapeProto.newBuilder().addDim(dim).build();
TensorProto proto = TensorProto.newBuilder()
.addStringVal(ByteString.copyFrom(imageBytes))
.setTensorShape(shape)
.setDtype(DataType.DT_STRING)
.build();
ModelSpec spec = ModelSpec.newBuilder().setName("inception").build();
PredictRequest r = PredictRequest.newBuilder()
.setModelSpec(spec)
.putInputs("images", proto).build();
PredictResponse response = blockingStub.predict(r);
</code></pre>
| 0 | 2016-10-17T16:28:39Z | [
"c#",
"python",
"tensorflow"
]
|
Why would a pip installed package's __init__.py NOT have the canonical if __name__ == "__main__":? | 39,911,357 | <p>I am playing around with <a href="http://github.com/getpelican/pelican" rel="nofollow">pelican</a>, the static blog generator, which I have</p>
<ul>
<li><p>cloned from github</p>
<p>$ git clone <a href="https://github.com/getpelican/pelican.git" rel="nofollow">https://github.com/getpelican/pelican.git</a></p></li>
<li><p>installed into my virtualenv as an editable package</p>
<p>$ pip install -r dev_requirements.txt<br>
$ pip install -e .</p></li>
</ul>
<p>Now I would like to run it, and debug it, using pycharm (and later in emacs)</p>
<p>I can't quite figure out how to do that!</p>
<p>I can run pelican from the command line.</p>
<pre><code>$ pelican /blog/content -o /blog/public -s /blog/pelicanconf.py --relative_urls
</code></pre>
<p>But I cannot figure out how to run it from pycharm....</p>
<p>That is, I can set a breakpoint at <code>__init__.py:main()</code> but when pycharm runs <code>__init__.py</code> nothing happens.
Presumably pycharm runs <code>__init__</code> and it loads the various modules and then exits.</p>
<p>Until I add the canonical invocation trope:</p>
<pre><code>if __name__ == "__main__":
main()
</code></pre>
<p>at the bottom of <code>__init__.py</code></p>
<p>And then I can tell pycharm to run the <code>__init__.py</code> script and python enters the debugger at main() as I want.</p>
<hr>
<p>(edited)
So my questions are</p>
<ol>
<li>Why would a python package NOT have that trope at the end of its <code>__init__.py</code>?</li>
<li>How do I configure pycharm so that I can run and debug pelican (or similar python packages) from within it?</li>
</ol>
| 2 | 2016-10-07T07:05:19Z | 39,911,648 | <p>The <a href="https://github.com/getpelican/pelican/blob/master/setup.py" rel="nofollow"><code>pelican/setup.py</code></a> defines several entrypoints:</p>
<pre><code>entry_points = {
'console_scripts': [
'pelican = pelican:main',
'pelican-import = pelican.tools.pelican_import:main',
'pelican-quickstart = pelican.tools.pelican_quickstart:main',
'pelican-themes = pelican.tools.pelican_themes:main'
]
}
</code></pre>
<p>I guess the first one tells that the function <code>pelican.main()</code> is called when you execute the <code>pelican</code> command.</p>
<p>So if you want to run pelican from PyCharm, you probably just have to run the <code>main()</code> function of the <code>pelican/__init__.py</code></p>
<p>You can do that by:</p>
<ul>
<li>creating a simple script which just import and invoke the <code>pelican.main()</code> function</li>
<li>run this script (in debug mode for debugging)</li>
</ul>
| 4 | 2016-10-07T07:21:59Z | [
"python",
"python-2.7",
"pycharm"
]
|
Tensorflow elementwise matrix multiplication (for-loop) error | 39,911,373 | <p>I want to calculate matrix multiplication with Tensorflow. <br>
But it occured errors while numpy usage doesn't make errors. <br>
(Process finished with exit code 139 (interrupted by signal 11: SIGSEGV))</p>
<p><strong>Tensorflow with CPU / GPU : occured the error : Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
With Numpy (Without Tensorflow) : It occurs well</strong></p>
<pre><code>import tensorflow as tf
mport numpy as np
num_doc = 1000 #10000
num_topic = 10
num_user = 20 #8000
cost = 0
#### Tensorflow with CPU ####
with tf.device('/cpu:0'):
a_dk = tf.Variable(tf.random_normal([num_doc,num_topic]))
x_uk = tf.Variable(tf.random_normal([num_user,num_topic]))
x_dk = tf.Variable(tf.random_normal([num_doc,num_topic]))
for u in range(num_user):
print u
for d in range(num_doc):
for k in range(num_topic):
cost = cost + a_dk[d,k] * x_uk[u,k] * x_dk[d,k]
#### Tensorflow with GPU ####
a_dk = tf.Variable(tf.random_normal([num_doc,num_topic]))
x_uk = tf.Variable(tf.random_normal([num_user,num_topic]))
x_dk = tf.Variable(tf.random_normal([num_doc,num_topic]))
for u in range(num_user):
print u
for d in range(num_doc):
for k in range(num_topic):
cost = cost + a_dk[d,k] * x_uk[u,k] * x_dk[d,k]
#### Numpy ####
a_dk = np.random.randn(num_doc, num_topic)
x_uk = np.random.randn(num_user, num_topic)
x_dk = np.random.randn(num_doc, num_topic)
for u in range(num_user):
print u
for d in range(num_doc):
for k in range(num_topic):
cost = cost + a_dk[d,k] * x_uk[u,k] * x_dk[d,k]
</code></pre>
<p>I used i7-4k / 16GB ram / GTX-1070(8GB) <br>
<strong>And I need a for-loop elementwise matrix multiplication solution with Tensorflow.</strong> <br>
(Actually, My problem is more complex than above code. So it is hard to makes it vectorization) <br></p>
<p>Thank you in advance !!</p>
| -1 | 2016-10-07T07:05:50Z | 39,947,305 | <p>You have a few errors in what you pasted. You aren't importing numpy correctly.</p>
<p>for tensorflow you need to create a session. </p>
<pre><code>with tf.Session() as sess:
... cpu or gpu code here...
print(sess.run([cost]))
</code></pre>
<p>for numpy it as built in element wise multiplication</p>
<pre><code>result = np.multiply(A,B)
</code></pre>
<p>Just use that. You can also index into A, B when calling it</p>
<pre><code>result = np.multiply(A[i,:],B[:,i])
</code></pre>
| 0 | 2016-10-09T18:53:27Z | [
"python",
"tensorflow"
]
|
update query execution in python | 39,911,430 | <p>I am executing this query on sql developer and it is working fine</p>
<pre><code>update TABLE_X set COL_SID='19' where ID='1';
</code></pre>
<p>But when I am doing this via python code </p>
<pre><code>cur=conn.cursor()
updt_query='update TABLE_X set COL_SID=? where ID=?'
cur.execute(updt_query,('19','1'))
cur.close()
</code></pre>
<p>I am getting error</p>
<pre><code>cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number
</code></pre>
<p>Please let me know where I am doing the mistake.</p>
| 0 | 2016-10-07T07:09:09Z | 39,911,500 | <p>Could be the ID are number and not string so you should use </p>
<pre><code> cur.execute(updt_query,(19,1))
</code></pre>
| 0 | 2016-10-07T07:13:21Z | [
"python",
"sql",
"oracle"
]
|
update query execution in python | 39,911,430 | <p>I am executing this query on sql developer and it is working fine</p>
<pre><code>update TABLE_X set COL_SID='19' where ID='1';
</code></pre>
<p>But when I am doing this via python code </p>
<pre><code>cur=conn.cursor()
updt_query='update TABLE_X set COL_SID=? where ID=?'
cur.execute(updt_query,('19','1'))
cur.close()
</code></pre>
<p>I am getting error</p>
<pre><code>cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number
</code></pre>
<p>Please let me know where I am doing the mistake.</p>
| 0 | 2016-10-07T07:09:09Z | 39,911,716 | <p>I got a better way</p>
<pre><code>cur=conn.cursor()
updt_query='update TABLE_X set COL_SID=:cs where ID=:id'
cur.execute(updt_query,{cs:'19',id:'1'})
cur.close()
</code></pre>
<p>Its done ! Thanks!</p>
| 0 | 2016-10-07T07:25:53Z | [
"python",
"sql",
"oracle"
]
|
Binary Tree Traversal - Preorder - visit to parent | 39,911,442 | <p>I'm trying to understand the recursive implementation of preorder traversal as shown in this link <a href="http://interactivepython.org/runestone/static/pythonds/Trees/TreeTraversals.html" rel="nofollow">http://interactivepython.org/runestone/static/pythonds/Trees/TreeTraversals.html</a></p>
<pre><code>def preorder(tree):
if tree:
print(tree.getRootVal())
preorder(tree.getLefChild())
preorder(tree.getRightChild())
</code></pre>
<p>I understand how pre-order works, however what I'm flustered with is the recursive implementation shown above. I still can't figure out how after traversing through all the left children the algorithm goes back to the nearest ancestor(parent). I've tried working this out on paper but it still doesn't click. </p>
| -2 | 2016-10-07T07:09:43Z | 39,911,679 | <p><code>preorder(tree.getLefChild())</code> goes through all the left children for the current tree. That method then returns, just like all other methods, then continues on with the parent's right children. </p>
<p>A quick visualization </p>
<pre><code>def preorder(tree):
if tree:
print(tree.getRootVal())
preorder(tree.getLefChild()) # Expand this
preorder(tree.getRightChild())
</code></pre>
<p>Becomes...</p>
<pre><code>def preorder(tree):
if tree:
print(tree.getRootVal())
# Entering recursion ...
if (tree.getLefChild()):
print(tree.getLefChild().getRootVal())
preorder(tree.getLefChild().getLefChild()) # And so on...
preorder(tree.getLefChild().getRightChild())
# Exiting recursion...
preorder(tree.getRightChild())
</code></pre>
| 0 | 2016-10-07T07:23:16Z | [
"python",
"recursion",
"binary-tree"
]
|
How are the commit timestamps generated in cvs2git/cvs2svn? | 39,911,698 | <p>I am converting a very old and huge CVS repository to Git using cvs2git via Cygwin. It works fine and I started testing the new repository. I found no bigger peculiarities. But I wonder how the timestamps of a commit/change set are determined.</p>
<p>So far I determined, that the timestamps between certain CVS revisions differ by 1 or 2 hours plus x, where x is a time from some seconds or minutes (most cases) up two 15 minutes. Many timestamps only differ by whole hours (x=0).</p>
<p>I guess this has to do something with the "timestamp error correction" I found to be a cvs2svn feature (<a href="http://www.mcs.anl.gov/~jacob/cvs2svn/features.html" rel="nofollow">http://www.mcs.anl.gov/~jacob/cvs2svn/features.html</a>). Maybe it has something to do with time zones, also.</p>
<p>The results of my tests show, that all commits with only one file in the change set differ by whole hours. That supports my "time zone hypothesis". But it also leads me to the question how the timestamp of change sets with multiple files is determined.</p>
<p>I tried to go through the code and found out (with help from Google) that there is a "COMMIT_THRESHOLD" in the config.py of the cvs2svn_lib. It is used for fuzzing the file based commits in the CVS together, I guess. Although the code looks written well, my lack of technical understanding of CVS, SVN and Git revision storage makes it hard for me to understand.</p>
<p>Therefore, I would be grateful if someone could answer the following questions:</p>
<ul>
<li>How does cvs2svn/cvs2git determine a commit timestamp of change sets with multiple files?</li>
<li>How does the "timestamp error correction" cvs2svn/cvs2git work? (For me the functional background is more important than the technical.)</li>
</ul>
<p>Kind regards</p>
<p>Edit:</p>
<p>As someone considered this question as "too broad", I am afraid I did not make my point clear enough. So I would like to give a concrete (while fictional) example:</p>
<p>cvs2git found 3 file changes for one change set. They where committed on the same day (let's say on 30th February 2016). But their times differ:</p>
<ul>
<li>File 1: 12:34:56</li>
<li>File 2: 12:35:38</li>
<li>File 3: 12:36:09</li>
</ul>
<p>If it was only file 1, I would think, that cvs2git uses 2016-02-30T12:34:56 as timestamp for the Git commit. But which timestamp is chosen, when the commits for all 3 files belong to one change set?</p>
<p>Related to this, when my repository is converted the times seem to be adjusted by exactly 1 or 2 hours, too. This also happens when there is only one file in the change set. I guess it is some kind of time zone adjustment. So I would like to know, why the "timestamp error correction" changed my timestamps, to check whether I accept these changes or not. I did some statistics on the converted Git repository and the commit times seem ok to me in principle; but that is not enough for me.</p>
| 0 | 2016-10-07T07:24:52Z | 40,013,821 | <p>You ask two questions:</p>
<ol>
<li><p>How are timestamps generated for commits touching multiple files?</p>
<p>For commits that modify files, cvs2svn/cvs2git takes the newest timestamp from among the file-level commits that comprise the commit. However, if that timestamp is earlier than the timestamp of the previous commit or more than one day after the time of conversion, it instead chooses a timestamp one second after that of the previous commit.</p>
<p>For commits that involve branching or tagging (for which CVS doesn't record timestamps at all), the timestamp is set to be one second after the timestamp of the previous commit.</p></li>
<li><p>Why are timestamps sometimes off by an integral number of hours?</p>
<p>CVS records timestamps in UTC without recording a timezone, and cvs2svn/cvs2git uses those timestamps as-is without trying to guess a timezone. So the timestamps should be correct, but are expressed in UTC.</p>
<p><code>git log</code> has a <code>--date</code> option that can be used to ask that dates be displayed in the local timezone.</p></li>
</ol>
<p>The cvs2svn project file <a href="http://cvs2svn.tigris.org/source/browse/cvs2svn/trunk/doc/design-notes.txt?revision=5206&view=markup" rel="nofollow"><code>doc/design-notes.txt</code></a> documents the algorithms used by cvs2svn/cvs2git in quite some detail.</p>
| 1 | 2016-10-13T06:32:38Z | [
"python",
"git",
"timestamp",
"cvs2svn",
"cvs2git"
]
|
Trying to view User Profile in Django, but Page Not Found when searching URLs | 39,911,741 | <p>I am trying to view a user profile for my website with the Detail CBV. Below is the code for views.py, urls.py, models.py and profile.html.</p>
<p>A user exists with the username "brian_weber", but for some reason when I navigate to this link: <a href="http://0.0.0.0:8000/accounts/profile/brian_weber" rel="nofollow">http://0.0.0.0:8000/accounts/profile/brian_weber</a> the page is not found. My app is called "accounts".</p>
<p>If someone could point me in the right direction to get the view to show up with the url, that would be greatly appreciated! I have searched around Stack Overflow, but nothing has worked that I tried.</p>
<p>Thanks in advance,</p>
<p>Brian</p>
<p><strong>views.py</strong> </p>
<pre><code>from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.contrib.auth import login, logout, authenticate
from django.http import HttpResponseRedirect
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse, reverse_lazy
from django.views import generic
from braces.views import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from . import forms
from . import models
class LoginView(generic.FormView):
form_class = AuthenticationForm
success_url = reverse_lazy('home')
template_name = "accounts/login.html"
def get_form(self, form_class=None):
if form_class is None:
form_class = self.get_form_class()
return form_class(self.request, **self.get_form_kwargs())
def form_valid(self, form):
login(self.request, form.get_user())
return super().form_valid(form)
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse('home'))
class SignUp(SuccessMessageMixin, generic.CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy("login")
template_name = "accounts/signup.html"
success_message = "Your profile has been successfully created. Please log into your account."
class UserProfile(LoginRequiredMixin, generic.DetailView):
model = models.UserProfile
template_name = "profile.html"
class UserProfileUpdate(LoginRequiredMixin, generic.UpdateView):
model = models.UserProfile
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^logout/$', views.logout_view, name="logout"),
url(r'^signup/$', views.SignUp.as_view(), name="signup"),
url(r'^profile/(?P<username>[a-zA-Z0-9]+)$',
views.UserProfile.as_view(),
name="profile"),
url(r'^profile/update/(?P<username>[a-zA-Z0-9]+)$',
views.UserProfileUpdate.as_view(),
name="update_profile"),
]
</code></pre>
<p><strong>models.py</strong></p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
company = models.CharField(max_length=40, null=True)
position = models.CharField(max_length=40, null=True)
bio = models.CharField(max_length=140, blank=True, default="")
avatar = models.ImageField(blank=True, null=True, upload_to="avatars",
height_field=None, width_field=None)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
</code></pre>
| 0 | 2016-10-07T07:27:15Z | 39,912,215 | <p>Your mistake is very small, the regular expression provided in url for profile, <code>(?P<username>[a-zA-Z0-9]+)</code> does not match <code>brian_weber</code> because of the <code>_</code>.</p>
<p>You can simply update the regex to match <code>_</code> too.</p>
<pre><code>username_regex = r'[a-zA-Z0-9_]+'
urlpatterns = [
url(r'^logout/$', views.logout_view, name="logout"),
url(r'^signup/$', views.SignUp.as_view(), name="signup"),
url(r'^profile/(?P<username>{username})$'.format(username=username_regex),
views.UserProfile.as_view(),
name="profile"),
url(r'^profile/update/(?P<username>{username})$'.format(username=username_regex),
views.UserProfileUpdate.as_view(),
name="update_profile"),
]
</code></pre>
| 2 | 2016-10-07T07:54:29Z | [
"python",
"django",
"django-views",
"django-class-based-views",
"user-profile"
]
|
Functions in python 3 | 39,911,985 | <p>I'm struggling with functions in python 3. How can I make the below code print out the result in degrees Celsius? Is the indentation wrong, or has it to do with me not defining Celsius outside the function in the first place? Does this mean I do not have to use functions for simple tasks or is it better to do so anyway?</p>
<pre><code>print ("Welkom bij mijn Fahrenheit naar Celsius converteerprogramma!")
fahrenheit = int(input("Voer aantal graden Fahrenheit in "))
def converter_fahrenheit(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
print (fahrenheit, "graden Fahrenheit is omgerekend ","%.2f" % celsius,"graden Celsius")
</code></pre>
| 1 | 2016-10-07T07:41:10Z | 39,912,052 | <p>Quite a few changes needed, yes you had the indentation wrong for the print statement. But that's not all see how the code is ordered now</p>
<pre><code>def converter_fahrenheit(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
print (fahrenheit, "graden Fahrenheit is omgerekend ","%.2f" % celsius,"graden Celsius")
print ("Welkom bij mijn Fahrenheit naar Celsius converteerprogramma!")
fahrenheit = int(input("Voer aantal graden Fahrenheit in "))
converter_fahrenheit(fahrenheit)
</code></pre>
<p>Defining the function first, makes it possible for you to actually call the function without an error being thrown. Yes, you were not calling the function at all!</p>
| 1 | 2016-10-07T07:44:59Z | [
"python"
]
|
Functions in python 3 | 39,911,985 | <p>I'm struggling with functions in python 3. How can I make the below code print out the result in degrees Celsius? Is the indentation wrong, or has it to do with me not defining Celsius outside the function in the first place? Does this mean I do not have to use functions for simple tasks or is it better to do so anyway?</p>
<pre><code>print ("Welkom bij mijn Fahrenheit naar Celsius converteerprogramma!")
fahrenheit = int(input("Voer aantal graden Fahrenheit in "))
def converter_fahrenheit(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
print (fahrenheit, "graden Fahrenheit is omgerekend ","%.2f" % celsius,"graden Celsius")
</code></pre>
| 1 | 2016-10-07T07:41:10Z | 39,912,516 | <p>You can do this by defining your function <code>converter_fahrenheit()</code> first then taking the input and finally calling the function after having the input. You haven't called the function to get the value of <code>celsius</code> and it's the main issue.
The code should be like in this way:</p>
<pre><code>def converter_farenheit(farenheit):
celsius=(farenheit-32)*5/9
print(farenheit,"is the temperature in farenheit and in Celsius ","%.2f" %celsius)
converter_farenheit(farenheit=int(input("Enter the temperature in Farenheit ")))
</code></pre>
<p>Please mark the indentation well too. :)</p>
| 1 | 2016-10-07T08:10:53Z | [
"python"
]
|
Functions in python 3 | 39,911,985 | <p>I'm struggling with functions in python 3. How can I make the below code print out the result in degrees Celsius? Is the indentation wrong, or has it to do with me not defining Celsius outside the function in the first place? Does this mean I do not have to use functions for simple tasks or is it better to do so anyway?</p>
<pre><code>print ("Welkom bij mijn Fahrenheit naar Celsius converteerprogramma!")
fahrenheit = int(input("Voer aantal graden Fahrenheit in "))
def converter_fahrenheit(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
print (fahrenheit, "graden Fahrenheit is omgerekend ","%.2f" % celsius,"graden Celsius")
</code></pre>
| 1 | 2016-10-07T07:41:10Z | 39,912,769 | <p>You seem to have misunderstood how functions work. When you write something like:</p>
<pre><code>def converter_farenheit(farenheit):
some_code
</code></pre>
<p>The code inside doesn't actually get run until you call the function by calling it later in the program. You've already called a few functions like <code>int</code> and <code>input</code> and <code>print</code> in your program, and using <code>converter_farenheit</code> looks basically the same.</p>
<p>Further, if you want to get a value back out of a function, you need it to <code>return</code> something, which passes it back out of the function allowing you to assign variables to its value, so <code>converter_farenheit</code> should really look like</p>
<pre><code>def converter_fahrenheit(fahrenheit):
return (fahrenheit - 32) * 5/9
</code></pre>
<p>Which means you can write</p>
<pre><code>def converter_fahrenheit(fahrenheit):
return (fahrenheit - 32) * 5/9
fahrenheit = # some code to grab input goes here
celsius = converter_farenheit(farenheit)
</code></pre>
<p>Giving <code>celsius</code> the value you expect it to. You asked whether you should avoid using functions for simple tasks, but in fact you should write as many simple functions as possible. As your programs get more complex, you'll find that lots of short, simple functions each doing a small, specific job are very easy for you to reason about and test.</p>
| 1 | 2016-10-07T08:26:19Z | [
"python"
]
|
MultiIndex look up all indices that have a given value for a given level | 39,912,657 | <p>I am using a <code>pandas.Series</code> with a <code>MultiIndex</code> for a bidirectional weighted lookup. I thought it should be easy to also find the corresponding other levels for a given level using the MultiIndex, but I cannot find a simple function <code>other</code> that does something like the following:</p>
<pre><code>>>> index=pandas.MultiIndex.from_tuples(
... [(0, 0),(1,2),(3,4),(5,6),(5,7),(8,0),(9,0)],
... names=["concept", "word"])
>>> other(index, "word", 0)
{0, 8, 9}
>>> other(index, "concept", 3)
{4}
>>> other(index, "word", 6)
{5}
</code></pre>
<p>I'm happy to specify level numbers instead of level names and to get any iterable out, not necessarily a set. I only have a 2-level multi-index, so I don't care about how to generalize to a higher-level multi-indices, or even whether it does generalize.</p>
<p>I would be slightly unhappy if this involves iterating over all entries in the MultiIndex and comparing them, because I thought indices are somewhat like multi-key hash tables.</p>
| 2 | 2016-10-07T08:20:06Z | 39,913,283 | <p>How about this:</p>
<pre><code>>>> index.get_level_values('concept').values[index.get_level_values('word').values == 0]
array([0, 8, 9])
>>> index.get_level_values('concept').values[index.get_level_values('word').values == 6]
array([5])
>>> index.get_level_values('word').values[index.get_level_values('concept').values == 3]
array([4])
</code></pre>
<hr>
<p>Note that you can easily transform a numpy array to a set:</p>
<pre><code>>>> set(np.array([1, 2, 3]))
{1, 2, 3}
</code></pre>
<p>and wrapping all of the above into some function <code>other</code> shouldn't be very difficult.</p>
| 1 | 2016-10-07T08:54:28Z | [
"python",
"pandas",
"indexing",
"multi-index"
]
|
MultiIndex look up all indices that have a given value for a given level | 39,912,657 | <p>I am using a <code>pandas.Series</code> with a <code>MultiIndex</code> for a bidirectional weighted lookup. I thought it should be easy to also find the corresponding other levels for a given level using the MultiIndex, but I cannot find a simple function <code>other</code> that does something like the following:</p>
<pre><code>>>> index=pandas.MultiIndex.from_tuples(
... [(0, 0),(1,2),(3,4),(5,6),(5,7),(8,0),(9,0)],
... names=["concept", "word"])
>>> other(index, "word", 0)
{0, 8, 9}
>>> other(index, "concept", 3)
{4}
>>> other(index, "word", 6)
{5}
</code></pre>
<p>I'm happy to specify level numbers instead of level names and to get any iterable out, not necessarily a set. I only have a 2-level multi-index, so I don't care about how to generalize to a higher-level multi-indices, or even whether it does generalize.</p>
<p>I would be slightly unhappy if this involves iterating over all entries in the MultiIndex and comparing them, because I thought indices are somewhat like multi-key hash tables.</p>
| 2 | 2016-10-07T08:20:06Z | 39,915,353 | <p><strong>Approach 1:</strong></p>
<p>You could build up a custom function using a vectorized approach as shown:</p>
<pre><code>def other(index, slicing, value):
arr = np.column_stack(index.values.tolist())
return (np.delete(arr, slicing, axis=0)[0][arr[slicing]==value])
</code></pre>
<p><em>Usage:</em></p>
<pre><code>other(index, slicing=index.names.index('word'), value=0)
# array([0, 8, 9])
</code></pre>
<p><em>Timings:</em></p>
<pre><code>%timeit other(index, slicing=index.names.index('word'), value=0)
10000 loops, best of 3: 43.9 µs per loop
</code></pre>
<hr>
<p><strong>Approach 2:</strong></p>
<p>If you want to use an inbuilt method which gives you the result by mere plugging in values to the respective args, you could opt for <a href="https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.MultiIndex.get_loc_level.html#pandas.MultiIndex.get_loc_level" rel="nofollow"><code>get_loc_level</code></a> which gives you the integer location slice corresponding to a label, like so:</p>
<p><em>Demo:</em></p>
<pre><code>index.get_loc_level(key=3, level='concept')[1].ravel()
# array([4], dtype=int64)
index.get_loc_level(key=0, level='word')[1].ravel()
# array([0, 8, 9], dtype=int64)
index.get_loc_level(key=6, level='word')[1].ravel()
# array([5], dtype=int64)
</code></pre>
<p><em>Timings:</em></p>
<pre><code>%timeit index.get_loc_level(key=0, level='word')[1].ravel()
10000 loops, best of 3: 129 µs per loop
</code></pre>
<p>So, you get a 3x boost using a custom function rather than implementing using
the built-in methods for the 2-level multi-index <code>DF</code> given.</p>
| 1 | 2016-10-07T10:42:21Z | [
"python",
"pandas",
"indexing",
"multi-index"
]
|
Reading sequential user input to an array in python | 39,912,937 | <p>I am very new to python, so apologise in advance if this question is straightforward.</p>
<p>I am writing a script in python that needs to ask the user for input sequentially (the input will all be floats), and then it needs to write that input to a list. The rest of the code will then do stuff with the list.</p>
<p>This is my first attempt:</p>
<pre><code>num_array = list()
a1 = raw_input('Enter percentage of A (in decimal form): ')
a2 = raw_input('Enter percentage of B (in decimal form): ')
a3 = raw_input('Enter percentage of C (in decimal form): ')
li = ['a1', 'a2', 'a3']
for s in li:
num_array.append(float(s))
</code></pre>
<p>It all works except when we get down to reading the values into the array. Then I get the error:</p>
<pre><code> num_array.append(float(s))
ValueError: invalid literal for float(): a1
</code></pre>
<p>I suspect that for a regular Python-coder the error is obvious, but this is literally the first time I'm using it :-) It's awesome, btw!</p>
<p>Any help would be much appreciated. As soon as it's running I will add things to deal with nonstandard inputs etc. </p>
| 0 | 2016-10-07T08:36:09Z | 39,913,059 | <p>It should be:</p>
<pre><code>li = [a1, a2, a3]
for s in li:
num_array.append(float(s))
</code></pre>
<p>You want to refer to <code>a1</code> the variable and not <code>"a1"</code> the string</p>
<p>Note you could combine everything into your loop:</p>
<pre><code>num_list = []
for c in ("A","B","C"):
num_list.append(float(raw_input('Enter percentage of {} (in decimal form): '.format(c))))
</code></pre>
<p>This will raise a <code>ValueError</code> if <code>raw_input</code> is not a valid <code>float</code> though.</p>
| 0 | 2016-10-07T08:42:25Z | [
"python",
"arrays",
"variables",
"input"
]
|
Reading sequential user input to an array in python | 39,912,937 | <p>I am very new to python, so apologise in advance if this question is straightforward.</p>
<p>I am writing a script in python that needs to ask the user for input sequentially (the input will all be floats), and then it needs to write that input to a list. The rest of the code will then do stuff with the list.</p>
<p>This is my first attempt:</p>
<pre><code>num_array = list()
a1 = raw_input('Enter percentage of A (in decimal form): ')
a2 = raw_input('Enter percentage of B (in decimal form): ')
a3 = raw_input('Enter percentage of C (in decimal form): ')
li = ['a1', 'a2', 'a3']
for s in li:
num_array.append(float(s))
</code></pre>
<p>It all works except when we get down to reading the values into the array. Then I get the error:</p>
<pre><code> num_array.append(float(s))
ValueError: invalid literal for float(): a1
</code></pre>
<p>I suspect that for a regular Python-coder the error is obvious, but this is literally the first time I'm using it :-) It's awesome, btw!</p>
<p>Any help would be much appreciated. As soon as it's running I will add things to deal with nonstandard inputs etc. </p>
| 0 | 2016-10-07T08:36:09Z | 39,913,412 | <p>Instead of using <code>str</code> type in <code>li</code> list, use the variables as: </p>
<pre><code> li = [a1, a2, a3]
</code></pre>
<p>Still your loop might raise <code>ValueError</code> if the value you are passing with <code>raw_input()</code> could not be convert into <code>float</code>. Better way to convert each item in <code>list</code> to <code>float</code> is:</p>
<p>via. <em>List Comprehension</em> as:</p>
<pre><code> num_list = [float(item) for item in [a1, a2, a3]]
</code></pre>
<p>OR, via <code>map()</code> as:</p>
<pre><code> num_list = map(float, [a1, a2, a3])
</code></pre>
| 0 | 2016-10-07T09:01:56Z | [
"python",
"arrays",
"variables",
"input"
]
|
Reading sequential user input to an array in python | 39,912,937 | <p>I am very new to python, so apologise in advance if this question is straightforward.</p>
<p>I am writing a script in python that needs to ask the user for input sequentially (the input will all be floats), and then it needs to write that input to a list. The rest of the code will then do stuff with the list.</p>
<p>This is my first attempt:</p>
<pre><code>num_array = list()
a1 = raw_input('Enter percentage of A (in decimal form): ')
a2 = raw_input('Enter percentage of B (in decimal form): ')
a3 = raw_input('Enter percentage of C (in decimal form): ')
li = ['a1', 'a2', 'a3']
for s in li:
num_array.append(float(s))
</code></pre>
<p>It all works except when we get down to reading the values into the array. Then I get the error:</p>
<pre><code> num_array.append(float(s))
ValueError: invalid literal for float(): a1
</code></pre>
<p>I suspect that for a regular Python-coder the error is obvious, but this is literally the first time I'm using it :-) It's awesome, btw!</p>
<p>Any help would be much appreciated. As soon as it's running I will add things to deal with nonstandard inputs etc. </p>
| 0 | 2016-10-07T08:36:09Z | 39,913,956 | <pre><code>a = input ("enter the value of a")
b = input ("enter the value of b")
c = input {"enter the value of c")
l = [a,b,c]
num_array = []
for i in l:
if type(i)==int
i=float(i)
num_array.append(i)
print l,num_array
</code></pre>
| -1 | 2016-10-07T09:30:11Z | [
"python",
"arrays",
"variables",
"input"
]
|
List project RhodeCode | 39,913,076 | <p>my problem is the following one: I would want to list all the projects which are present on a RhodeCode instance through Python package. However, I do not find the necessary information within the documentation. Is it someone would have a solution?</p>
| 0 | 2016-10-07T08:43:28Z | 39,913,571 | <p>RhodeCode has a JSON-RPC api. You can use python requests lib to fetch all list of projects, read the JSON and then iterate over the results.</p>
<p>The JSON api call to make is get_repos. Check out RhodeCode docs on the API topic, and how to call it. Also if you need more detailed example how to call the API, look at the open-source CLI script here (all in Python):</p>
<p><a href="https://code.rhodecode.com/rhodecode-tools-ce/files/dc1eb60fcd9cadb8be52a56d56d561d731e09d0b/rhodecode_tools/lib/api.py#L218" rel="nofollow">https://code.rhodecode.com/rhodecode-tools-ce/files/dc1eb60fcd9cadb8be52a56d56d561d731e09d0b/rhodecode_tools/lib/api.py#L218</a></p>
| 0 | 2016-10-07T09:10:22Z | [
"python",
"scripting",
"package",
"rhodecode"
]
|
Unable to parse XML response and obtain elements | 39,913,114 | <p>This is my XML response from a <code>http</code> request </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Dataset name="aggregations/g/ds083.2/2/TP"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xml.opendap.org/ns/DAP2"
xsi:schemaLocation="http://xml.opendap.org/ns/DAP2
http://xml.opendap.org/dap/dap2.xsd" >
<Attribute name="NC_GLOBAL" type="Container">
<Attribute name="Originating_or_generating_Center" type="String">
<value>US National Weather Service, National Centres for Environmental Prediction (NCEP)</value>
</Attribute>
<Attribute name="Originating_or_generating_Subcenter" type="String">
<value>0</value>
</Attribute>
<Attribute name="GRIB_table_version" type="String">
<value>2,1</value>
</Attribute>
<Attribute name="Type_of_generating_process" type="String">
<value>Forecast</value>
</Attribute>
<Attribute name="Analysis_or_forecast_generating_process_identifier_defined_by_originating_centre" type="String">
<value>Analysis from GDAS (Global Data Assimilation System)</value>
</Attribute>
<Attribute name="file_format" type="String">
<value>GRIB-2</value>
</Attribute>
<Attribute name="Conventions" type="String">
<value>CF-1.6</value>
</Attribute>
<Attribute name="history" type="String">
<value>Read using CDM IOSP GribCollection v3</value>
</Attribute>
<Attribute name="featureType" type="String">
<value>GRID</value>
</Attribute>
<Attribute name="_CoordSysBuilder" type="String">
<value>ucar.nc2.dataset.conv.CF1Convention</value>
</Attribute>
</Attribute>
<Array name="time1">
<Attribute name="units" type="String">
<value>Hour since 2007-12-06T12:00:00Z</value>
</Attribute>
<Attribute name="standard_name" type="String">
<value>time</value>
</Attribute>
<Attribute name="long_name" type="String">
<value>GRIB forecast or observation time</value>
</Attribute>
<Attribute name="calendar" type="String">
<value>proleptic_gregorian</value>
</Attribute>
<Attribute name="_CoordinateAxisType" type="String">
<value>Time</value>
</Attribute>
<Float64/>
<dimension name="time1" size="10380"/>
</Array>
</Dataset>
</code></pre>
<p>I am trying to parse this XML content using Python 3.5</p>
<pre><code>from xml.etree import ElementTree
response = requests.get("http://rda.ucar.edu/thredds/dodsC/aggregations/g/ds083.2/2/TP.ddx?time1")
tree = ElementTree.fromstring(response.content)
attr = tree.find("Attribute")
print(attr)
</code></pre>
<p>When I print this I get a <code>None</code>. What am I doing wrong? I also want to access the "Array" tag but that also returns <code>None</code>.</p>
| 0 | 2016-10-07T08:45:25Z | 39,913,767 | <p>As stated in <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml-with-namespaces" rel="nofollow">the doc</a>, due to the <code>xmlns="http://xml.opendap.org/ns/DAP2"</code>attribute of the Dataset root tag, all tag names you're looking for have to be prefixed by <code>{http://xml.opendap.org/ns/DAP2}</code>.</p>
<pre><code># should find something
tree.find("{http://xml.opendap.org/ns/DAP2}Attribute")
</code></pre>
<p>Reading this section of the ElementTree doc will also show you how to make something more readable with a dictionnary of namespaces.</p>
| 1 | 2016-10-07T09:21:06Z | [
"python",
"xml",
"python-3.x",
"xml-parsing",
"httprequest"
]
|
Unable to parse XML response and obtain elements | 39,913,114 | <p>This is my XML response from a <code>http</code> request </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Dataset name="aggregations/g/ds083.2/2/TP"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xml.opendap.org/ns/DAP2"
xsi:schemaLocation="http://xml.opendap.org/ns/DAP2
http://xml.opendap.org/dap/dap2.xsd" >
<Attribute name="NC_GLOBAL" type="Container">
<Attribute name="Originating_or_generating_Center" type="String">
<value>US National Weather Service, National Centres for Environmental Prediction (NCEP)</value>
</Attribute>
<Attribute name="Originating_or_generating_Subcenter" type="String">
<value>0</value>
</Attribute>
<Attribute name="GRIB_table_version" type="String">
<value>2,1</value>
</Attribute>
<Attribute name="Type_of_generating_process" type="String">
<value>Forecast</value>
</Attribute>
<Attribute name="Analysis_or_forecast_generating_process_identifier_defined_by_originating_centre" type="String">
<value>Analysis from GDAS (Global Data Assimilation System)</value>
</Attribute>
<Attribute name="file_format" type="String">
<value>GRIB-2</value>
</Attribute>
<Attribute name="Conventions" type="String">
<value>CF-1.6</value>
</Attribute>
<Attribute name="history" type="String">
<value>Read using CDM IOSP GribCollection v3</value>
</Attribute>
<Attribute name="featureType" type="String">
<value>GRID</value>
</Attribute>
<Attribute name="_CoordSysBuilder" type="String">
<value>ucar.nc2.dataset.conv.CF1Convention</value>
</Attribute>
</Attribute>
<Array name="time1">
<Attribute name="units" type="String">
<value>Hour since 2007-12-06T12:00:00Z</value>
</Attribute>
<Attribute name="standard_name" type="String">
<value>time</value>
</Attribute>
<Attribute name="long_name" type="String">
<value>GRIB forecast or observation time</value>
</Attribute>
<Attribute name="calendar" type="String">
<value>proleptic_gregorian</value>
</Attribute>
<Attribute name="_CoordinateAxisType" type="String">
<value>Time</value>
</Attribute>
<Float64/>
<dimension name="time1" size="10380"/>
</Array>
</Dataset>
</code></pre>
<p>I am trying to parse this XML content using Python 3.5</p>
<pre><code>from xml.etree import ElementTree
response = requests.get("http://rda.ucar.edu/thredds/dodsC/aggregations/g/ds083.2/2/TP.ddx?time1")
tree = ElementTree.fromstring(response.content)
attr = tree.find("Attribute")
print(attr)
</code></pre>
<p>When I print this I get a <code>None</code>. What am I doing wrong? I also want to access the "Array" tag but that also returns <code>None</code>.</p>
| 0 | 2016-10-07T08:45:25Z | 39,913,781 | <p>The XML document uses namespaces so you need to support that in your code. There is an explanation and example code in the <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces" rel="nofollow"><code>etree</code> documentation</a>.</p>
<p>Basically you can do this:</p>
<pre><code>import requests
from xml.etree import ElementTree
response = requests.get('http://rda.ucar.edu/thredds/dodsC/aggregations/g/ds083.2/2/TP.ddx?time1')
tree = ElementTree.fromstring(response.content)
attr = tree.find("{http://xml.opendap.org/ns/DAP2}Attribute")
>>> print(attr)
<Element '{http://xml.opendap.org/ns/DAP2}Attribute' at 0x7f147a292458>
# or declare the namespace like this
ns = {'dap2': 'http://xml.opendap.org/ns/DAP2'}
attr = tree.find("dap2:Attribute", ns)
>>> print(attr)
<Element '{http://xml.opendap.org/ns/DAP2}Attribute' at 0x7f147a292458>
</code></pre>
| 1 | 2016-10-07T09:21:27Z | [
"python",
"xml",
"python-3.x",
"xml-parsing",
"httprequest"
]
|
How to parse some optional elements present in XML document using python script? | 39,913,239 | <p>I have xml document collected from below link</p>
<p><a href="http://ieeexplore.ieee.org/gateway/ipsSearch.jsp?py=2000&hc=100" rel="nofollow">http://ieeexplore.ieee.org/gateway/ipsSearch.jsp?py=2000&hc=100</a></p>
<p>I am parsing <code>Title</code>, <code>Abstract</code>, <code>Author</code> and <code>Affiliation</code> from this xml document and creating separate text files. Some documents have abstract element but few don't have. I have written a python script which is used to parse required fields but do not work if any of the above mentioned element is not present. plz suggest any possible way to skip such docs:) </p>
<pre><code>import xmltodict
for i in range (1000):
with open('C:/Python27/Major Project/2000 ipsSearch.jsp.xml') as fd:
fout = open(str(i)+".txt","w") ## Flush old records from output file
doc = xmltodict.parse(fd.read())
w = doc['root']['document'][i]['rank']
x = doc['root']['document'][i]['title']
y = doc['root']['document'][i]['abstract']
z = doc['root']['document'][i]['authors']
a = doc['root']['document'][i]['affiliations']
fout.write(str(w)+"\n"+str(x)+" "+str(y)+"\n"+str(z)+"\n"+str(a))
</code></pre>
<p>getting error when there is no <code>abstract</code> element present in any <code>document</code>.</p>
| -1 | 2016-10-07T08:51:46Z | 39,914,144 | <p>Play the safe way - check if the element is present first, otherwise assign an empty string.</p>
<p>Now, since the parsed XML appears as dictionary you can use the <code>in</code> operator to check for that, and the ternary <code>if...else</code> operator to default the cases where you cant find an <code>abstract</code>:</p>
<pre><code> ...
y = doc['root']['document'][i]['abstract'] if 'abstract' in doc['root']['document'][i] else ''
z = doc['root']['document'][i]['authors'] if 'authors' in doc['root']['document'][i] else ''
...
</code></pre>
<p>Same goes for all elements.</p>
| 0 | 2016-10-07T09:40:43Z | [
"python",
"xml",
"parsing"
]
|
Error handling when accessing API | 39,913,367 | <p>I am trying to access an API (Scopus) through python, downloading multiple abstracts within the for loop below:</p>
<pre><code>for t in eid:
url = "http://api.elsevier.com/content/abstract/eid/"+str(t)+"?view=FULL"
# url = "http://api.elsevier.com/content/abstract/eid/2-s2.0-84934272190?view=FULL"
resp2 = requests.get(url,
headers={'Accept':'application/json',
'X-ELS-APIKey': MYAPIKEY})
retrieval = resp2.json()
dep = retrieval['abstracts-retrieval-response']['item']['bibrecord']['head']['author-group']
sub = retrieval['abstracts-retrieval-response']['subject-areas']['subject-area']
iD = retrieval['abstracts-retrieval-response']['coredata']['intid']
date = retrieval['abstracts-retrieval-response']['coredata']['prism:coverDate']
department.append(dep)
subj.append(sub)
ident.append(iD)
dates.append(date)
</code></pre>
<p>However, upon doing so I keep receiving the following errors along the lines of below (always at different points of the for loop too).
I've been told that error handling is a way around this, but being new to Python I have no idea what this is. Can anyone help? Thanks</p>
<p>EDIT: Here is the whole error message which should include all of the correct information (sorry that it is long)</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py", line 142, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py", line 91, in create_connection
raise err
File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py", line 81, in create_connection
sock.connect(sa)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 578, in urlopen
chunked=chunked)
File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 362, in _make_request
conn.request(method, url, **httplib_request_kw)
File "C:\Users\User\Anaconda3\lib\http\client.py", line 1106, in request
self._send_request(method, url, body, headers)
File "C:\Users\User\Anaconda3\lib\http\client.py", line 1151, in _send_request
self.endheaders(body)
File "C:\Users\User\Anaconda3\lib\http\client.py", line 1102, in endheaders
self._send_output(message_body)
File "C:\Users\User\Anaconda3\lib\http\client.py", line 934, in _send_output
self.send(msg)
File "C:\Users\User\Anaconda3\lib\http\client.py", line 877, in send
self.connect()
File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py", line 167, in connect
conn = self._new_conn()
File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py", line 151, in _new_conn
self, "Failed to establish a new connection: %s" % e)
requests.packages.urllib3.exceptions.NewConnectionError: <requests.packages.urllib3.connection.HTTPConnection object at 0x000002058C7E1C18>: Failed to establish a new connection: [WinError 10053] An established connection was aborted by the software in your host machine
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\User\Anaconda3\lib\site-packages\requests\adapters.py", line 403, in send
timeout=timeout
File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 623, in urlopen
_stacktrace=sys.exc_info()[2])
File "C:\Users\User\Anaconda3\lib\site-packages\requests\packages\urllib3\util\retry.py", line 281, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
requests.packages.urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='api.elsevier.com', port=80): Max retries exceeded with url: /content/abstract/eid/2-s2.0-84978766692?view=FULL (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x000002058C7E1C18>: Failed to establish a new connection: [WinError 10053] An established connection was aborted by the software in your host machine',))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
File "C:\Users\User\Anaconda3\lib\site-packages\requests\api.py", line 71, in get
return request('get', url, params=params, **kwargs)
File "C:\Users\User\Anaconda3\lib\site-packages\requests\api.py", line 57, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\User\Anaconda3\lib\site-packages\requests\sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\User\Anaconda3\lib\site-packages\requests\sessions.py", line 585, in send
r = adapter.send(request, **kwargs)
File "C:\Users\User\Anaconda3\lib\site-packages\requests\adapters.py", line 467, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='api.elsevier.com', port=80): Max retries exceeded with url: /content/abstract/eid/2-s2.0-84978766692?view=FULL (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x000002058C7E1C18>: Failed to establish a new connection: [WinError 10053] An established connection was aborted by the software in your host machine',))
</code></pre>
| 0 | 2016-10-07T08:58:57Z | 39,913,699 | <p>Unfortunately you haven't included 'the above exception' that is mentioned in your output.</p>
<p>But in general, when an exceptional situation, such as an error, happens during execution of a piece of code, you can catch that exception and deal with it. An exception is an object with information on board about what went wrong. Exception handling in general is a big subject and you might start reading at: <a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">https://docs.python.org/3/tutorial/errors.html</a></p>
<p>An example of dealing with an exception is just reporting the circumstances and the exception. This could already give you insight in what went wrong:</p>
<pre><code>for t in eid:
try:
url = "http://api.elsevier.com/content/abstract/eid/"+str(t)+"?view=FULL"
# url = "http://api.elsevier.com/content/abstract/eid/2-s2.0-84934272190?view=FULL"
resp2 = requests.get(url,
headers={'Accept':'application/json',
'X-ELS-APIKey': MYAPIKEY})
retrieval = resp2.json()
dep = retrieval['abstracts-retrieval-response']['item']['bibrecord']['head']['author-group']
sub = retrieval['abstracts-retrieval-response']['subject-areas']['subject-area']
iD = retrieval['abstracts-retrieval-response']['coredata']['intid']
date = retrieval['abstracts-retrieval-response']['coredata']['prism:coverDate']
department.append(dep)
subj.append(sub)
ident.append(iD)
dates.append(date)
except Exception as exception:
print (url) # 'print' will only work on a console
print (exception)
</code></pre>
<p>[EDIT]</p>
<p>I've taken a look at the error message and it seems that the server that you're trying to connect to, closed the connection. See also <a href="http://stackoverflow.com/questions/1472876/why-is-host-aborting-connection">Why is host aborting connection?</a> although the cause may be completely different. Try the code above to find out if this happens all the time or only with certain URL's</p>
<p>[/EDIT]</p>
<p>To build in some retries, use:</p>
<pre><code>import time
nrOfTries = 10
for t in eid:
for count in range (nrOfTries):
try:
url = "http://api.elsevier.com/content/abstract/eid/"+str(t)+"?view=FULL"
# url = "http://api.elsevier.com/content/abstract/eid/2-s2.0-84934272190?view=FULL"
resp2 = requests.get(url,
headers={'Accept':'application/json',
'X-ELS-APIKey': MYAPIKEY})
retrieval = resp2.json()
dep = retrieval['abstracts-retrieval-response']['item']['bibrecord']['head']['author-group']
sub = retrieval['abstracts-retrieval-response']['subject-areas']['subject-area']
iD = retrieval['abstracts-retrieval-response']['coredata']['intid']
date = retrieval['abstracts-retrieval-response']['coredata']['prism:coverDate']
department.append(dep)
subj.append(sub)
ident.append(iD)
dates.append(date)
break # Don't do the else
except Exception as exception:
print ('Problem accessing: {}' .format (url))
print (exception)
time.sleep (2) # Seconds
else: # Done after for-loop exhausted, but not if 'break' was encountered
print ('Gave up accessing: {}' .format (url))
</code></pre>
<p>N.B. I haven't tested this, but it should convey the general idea.
The 'sleep' is to allow the server to catch its breath...</p>
| 0 | 2016-10-07T09:17:05Z | [
"python",
"scopus"
]
|
Why does pandas.Series.corr return Nan whereas numpy or scipy compute a number? | 39,913,479 | <p>I try to compute correlation between two pandas series. This is what I get from numpy or scipy :</p>
<pre><code>scipy.stats.pearsonr(xfarines["400"].values, yfarines["PROTREF"].values)
(0.71564870605278108, 2.9185934338775347e-23)
pd.np.corrcoef(xfarines["400"].values, yfarines["PROTREF"].values)
array([[ 1. , 0.71564871],
[ 0.71564871, 1. ]])
</code></pre>
<p>But this is what pandas gives me :</p>
<pre><code>s = xfarines["400"]
s.corr(yfarines["PROTREF"])
nan
</code></pre>
<p>Looking at this question,
<a href="http://stackoverflow.com/questions/29042603/pandas-df-corr-returns-nan-despite-data-fed-having-populated-data">pandas df.corr() returns NaN despite data fed having populated data</a>
I check if the dtypes are ok and it seems it is :</p>
<pre><code>s.describe()
count 140.000000
mean 0.304078
std 0.057225
min 0.197300
25% 0.250300
50% 0.318500
75% 0.346850
max 0.408600
Name: 400, dtype: float64
yfarines["PROTREF"].describe()
count 140.000000
mean 12.619143
std 2.547644
min 7.600000
25% 10.975000
50% 12.100000
75% 14.590000
max 18.200000
Name: PROTREF, dtype: float64
</code></pre>
<p>Thus I do not understand where the problem comes from ?</p>
| 0 | 2016-10-07T09:05:03Z | 39,915,520 | <p>Strange that you mention numpy (v 1.8.0) but use the scipy import which may be different. This is what numpy does</p>
<pre><code>>>> a
array([[ 3.00000000, 0.17157288],
[ 3.00000000, 1.58578644],
[ 3.00000000, 3.00000000],
[ 3.00000000, 4.41421356],
[ 3.00000000, 5.82842712]])
>>> np.corrcoef(a[:,0], a[:,1],rowvar=0, bias=0, ddof=None)
array([[ nan, nan],
[ nan, 1.00000000]]
</code></pre>
<p>Perhaps people with newer version can confirm what it returns, but at least for a vertical line's points that is what is given.
For a horizontal line's points you get</p>
<pre><code>>>> b = np.array([a[:,1],a[:,0]]).T
>>> b
array([[ 0.17157288, 3.00000000],
[ 1.58578644, 3.00000000],
[ 3.00000000, 3.00000000],
[ 4.41421356, 3.00000000],
[ 5.82842712, 3.00000000]])
>>> np.corrcoef(b[:,0], b[:,1],rowvar=0, bias=0, ddof=None)
array([[ 1.00000000, nan],
[ nan, nan]])
</code></pre>
| 0 | 2016-10-07T10:53:38Z | [
"python",
"pandas",
"numpy",
"correlation"
]
|
Fill in missing values using climatology data except for current year | 39,913,543 | <pre><code>df.groupby([df.index.month, df.index.day])[vars_rs].transform(lambda y: y.fillna(y.median()))
</code></pre>
<p>I am filling missing values in a dataframe with median values from climatology. The days range from Jan 1 2010 to Dec 31st 2016. However, I only want to fill in missing values for days before current date (say Oct 1st 2016). How do I modify the statement?</p>
| 0 | 2016-10-07T09:08:33Z | 39,914,991 | <p>Use <code>np.where</code>, example:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A':['a','a','b','b','c','c'],'B':[1,2,3,4,5,6],'C':[1,np.nan,np.nan,np.nan,np.nan,np.nan]})
df.ix[:,'C'] = np.where((df.A != 'c')&(df.B < 4)&(pd.isnull(df.C)),-99,df.ix[:,'C'])
</code></pre>
<p>Like this you can directly modify the desired column using boolean expressions and all columns.</p>
<p>Original dataframe:</p>
<pre><code> A B C
0 a 1 1.0
1 a 2 NaN
2 b 3 NaN
3 b 4 NaN
4 c 5 NaN
5 c 6 NaN
</code></pre>
<p>Modified dataframe:</p>
<pre><code> A B C
0 a 1 1.0
1 a 2 -99.0
2 b 3 -99.0
3 b 4 NaN
4 c 5 NaN
5 c 6 NaN
</code></pre>
| 1 | 2016-10-07T10:22:12Z | [
"python",
"pandas"
]
|
Fill in missing values using climatology data except for current year | 39,913,543 | <pre><code>df.groupby([df.index.month, df.index.day])[vars_rs].transform(lambda y: y.fillna(y.median()))
</code></pre>
<p>I am filling missing values in a dataframe with median values from climatology. The days range from Jan 1 2010 to Dec 31st 2016. However, I only want to fill in missing values for days before current date (say Oct 1st 2016). How do I modify the statement?</p>
| 0 | 2016-10-07T09:08:33Z | 39,916,202 | <p>The algorithm would be:</p>
<ol>
<li>Get a part of the data frame which contains only rows filtered by date with a boolean mask</li>
<li>Perform required replacements on it</li>
<li>Append the rest of the initial data frame to the end of the resulting data frame.</li>
</ol>
<p>Dummy data:</p>
<pre><code>df = pd.DataFrame(np.zeros((5, 2)),columns=['A', 'B'],index=pd.date_range('2000',periods=5,freq='M'))
A B
2000-01-31 0.0 0.0
2000-02-29 0.0 0.0
2000-03-31 0.0 0.0
2000-04-30 0.0 0.0
2000-05-31 0.0 0.0
</code></pre>
<p>The code</p>
<pre><code>vars_rs = ['A', 'B']
mask = df.index < '2000-03-31'
early = df[mask]
early = early.groupby([early.index.month, early.index.day])[vars_rs].transform(lambda y: y.replace(0.0, 1)) # replace with your code
result = early.append(df[~mask])
</code></pre>
<p>So the result is</p>
<pre><code> A B
2000-01-31 1.0 1.0
2000-02-29 1.0 1.0
2000-03-31 0.0 0.0
2000-04-30 0.0 0.0
2000-05-31 0.0 0.0
</code></pre>
| 1 | 2016-10-07T11:31:40Z | [
"python",
"pandas"
]
|
Login in to AJAX form using scrapy | 39,913,636 | <p>I am trying to logging in to the page <a href="http://www.kumhoepos.com.au/epos/index.jsp" rel="nofollow">http://www.kumhoepos.com.au/epos/index.jsp</a> which is java scripted. I am trying this but not successful.</p>
<pre><code>class ElementSpider(scrapy.Spider):
name = 'epos'
start_urls = ['http://www.kumhoepos.com.au/epos/index.jsp']
def parse(self, response):
yield scrapy.FormRequest.from_response(response,
formdata={'user_id': 'myid', 'pass': 'mypassword'},
callback = self.after_login)
def after_login(self, response):
if "Password incorrect" in response.body:
print "hey"
self.log("Login failed", level=log.ERROR)
elif "Unregistered ID" in response.body:
print "hello"
self.log("Login failed", level=log.ERROR)
# We've successfully authenticated, let's have some fun!
else:
print response.body
url_pass = 'http://www.kumhoepos.com.au/epos/login.do?action=logincheck'
yield scrapy.Request(url="http://www.kumhoepos.com.au/epos/manage/sicus.do?action=list",
callback=self.parse_1)
def parse_1(self, response):
print response.body
x = response.xpath('//div[@id="contents_wrapper"]/div[@class="contents_top"]/h1/text()').extract()
print x
table = response.xpath('//table[@class="tbl_type02"]/tbody/tr//td//text()').extract()
print table
</code></pre>
<p>And the output is-</p>
<pre><code>D:\xampp\htdocs\py\test1>scrapy crawl epos -L WARNING
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or
g/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<form name='signForm' method='post'>
<input type=hidden name="user_id" />
<input type=hidden name="pass" />
</form>
<script type="text/javascript">
document.signForm.action = "/epos/login.do?action=login";
document.signForm.user_id.value = 'myid';
document.signForm.pass.value = 'mypassword';
document.signForm.target = "_parent";
document.signForm.submit();
</script>
</body>
</html>
<script language='javascript'>
alert('Session has been terminated. Go to the login page.');
if(window.opener && !window.opener.closed )
{
opener.parent.location.href = '/epos/';
self.close();
}else{
parent.location.href='/epos/';
}
</script>
[]
[]
</code></pre>
<p>Please suggest how to handle java-scripted form. </p>
| 0 | 2016-10-07T09:14:05Z | 39,915,784 | <p>The Scrapy does not support on-page JS evaluation.
The submit button triggers JS <a href="http://view-source:http://www.kumhoepos.com.au/epos/index.jsp" rel="nofollow">login()</a> function:</p>
<pre><code>function login()
{
var cookie_user_id ='KHTIRE_USER_ID';
var f = document.loginForm;
if(isNull(f.user_id, 'Please input your id.')) return false;
if(isNull(f.pass, 'Please input your password.')) return false;
if(f.chk_save.checked){
setCookie(cookie_user_id, f.user_id.value, 5);
}else{
deleteCookie(cookie_user_id) ;
}
f.target = "indexIfrm";
f.submit();
}
</code></pre>
<p>Inside of that function cookie is handled by page's JS function <a href="http://view-source:http://www.kumhoepos.com.au/epos/index.jsp" rel="nofollow">setCookie</a>:</p>
<pre><code>function setCookie( cookieName, cookieValue, expireDate )
{
var today = new Date();
today.setDate( today.getDate() + parseInt( expireDate ) );
document.cookie = cookieName + "=" + escape( cookieValue ) + "; path=/; expires=" + today.toGMTString() + ";";
}
</code></pre>
<p>Most likely you should not only imitate a form submission, but also set browser cookies. How? - imitate a cookie jar like <a href="http://scraping.pro/http-cookie-handler-curl/" rel="nofollow">here in php</a>. </p>
<p><code>f.target="indexIfrm"</code> points to the iframe where the submit response will be loaded<a href="http://www.w3schools.com/tags/att_form_target.asp" rel="nofollow"> [docs]</a>.
So, check server ajax response and extract what you need from JS-stuffed response...
See for example a response that I've got for a wrong {id/password} from that ajax form submission:</p>
<pre><code><script language='javascript' type="">
alert('Unregistered ID. Please apply to the administrator...');
</script>
<script type="text/javascript">
parent.loginForm.user_id.focus();
</script>
</code></pre>
<p>Read <a href="http://scraping.pro/javascript-protected-content-scrape/" rel="nofollow">more here</a> of how to handle JS-stuffed web pages.</p>
| -1 | 2016-10-07T11:08:58Z | [
"python",
"web-scraping",
"scrapy"
]
|
How can I convert a int type to time type | 39,913,642 | <p>I want to convert 20161017(int type) to 20161017(time type)</p>
<p>I try</p>
<pre><code>import time
a=20161017
b = time.strftime('%Y%m%d',a)
print(b)
</code></pre>
<p>but It cannot work</p>
<p>additional question</p>
<p>in int type, i use 20161017 - 10000 = 20151017
how can i do this in 20161017(time type)?</p>
| -1 | 2016-10-07T09:14:22Z | 39,913,663 | <p>strptime takes string as argument. So you have to first convert your <code>a</code> to string. And you should also use str<strong>p</strong>time instead of str<strong>f</strong>time</p>
<pre><code>b = time.strptime(str(a), '%Y%m%d')
</code></pre>
<p>as for your additional question. There is <code>dateutil.relativedelta</code> for that.</p>
<pre><code>from dateutil.relativedelta import relativedelta
c = b - relativedelta(year=1)
</code></pre>
| 1 | 2016-10-07T09:15:25Z | [
"python",
"time"
]
|
BeautifulSoup - Extract text with tags as text | 39,913,686 | <p>Lets say i have the html</p>
<pre><code><div>Hey</div><div>This is <b>some text<b/>, right here. <a>Link<a/></div>
</code></pre>
<p>and the code</p>
<pre><code>soup = BeautifulSoup(html)
texts = soup.findAll(text=True)
</code></pre>
<p>print() will return</p>
<pre><code>['Hey', 'This is ', 'some text', ', right here.', 'Link']
</code></pre>
<p>for texts.</p>
<p>How could I exclude tags like 'b' (that only contain text), so I could get the desired output which is</p>
<pre><code>['Hey', 'This is <b>some text<b/>, right here.', 'Link']
</code></pre>
<p>Also preferably <strong>not</strong> strings but equivalent NavigableStrings or similar.</p>
<p>In other words, how can I exclude some tags from navigating the tree? </p>
| 0 | 2016-10-07T09:16:10Z | 39,913,741 | <p>based on updated OP's question:</p>
<pre><code>eDiv = soup.findAll("div")
if eDiv.find("b") is None:
tag = eDiv.text
else:
tag = eDiv
</code></pre>
<p>now you can append this into list.</p>
| -1 | 2016-10-07T09:19:49Z | [
"python",
"beautifulsoup"
]
|
How can i get my program to return the password strength | 39,913,740 | <p>I'm struggling with my password rater program. How can i make sure that when i insert a password, my program returns the password strength. When i run this program it says that password_strength is stored at .....) is the return that i call at the end of my program wrong?</p>
<pre><code>print ("Welcome to this password rater program")
print ("Your password needs to have a minimum of 6 characters with a maximum of 20 characters.")
print ("Your password can contain lowercase and uppercase characters, numbers and special characters")
print("")
password = input("Please insert your password: ")
def check_len(password):
l = len(password)
if 6 < l < 20:
x = check_char(password, l)
else:
x = 0
return x
def check_char(password, l):
for i in range(l):
ascii = ord(password[i])
num = 0
upper = 0
symbols = 0
lower = 0
space = 0
if 96 < ascii < 123:
lower = 15
elif 47 < ascii < 58:
num = 25
elif 64 < ascii < 91:
upper = 25
elif ascii == 32:
space = 30
else:
symbols = 25
total = ((lower + num + upper + space + symbols) * len(password))
return total
def password_strength(total):
if total >= 1000:
print("Your chosen password is Very strong")
elif 700 < total < 999:
print("Your chosen password is strong")
elif 500 < total < 699:
print("your chosen password is medium")
elif total <= 500:
print("Your chosen password is weak")
return total
strength = check_len(password)
print(password_strength(strength))
</code></pre>
| 1 | 2016-10-07T09:19:46Z | 39,914,143 | <p>You never call your python functions. </p>
<pre><code>def potatis():
print("Hello yu!")
</code></pre>
<p>defines a function, but you also need to call the function <code>potatis()</code> for the code inside to actually run.</p>
| 1 | 2016-10-07T09:40:37Z | [
"python",
"python-3.x"
]
|
How can i get my program to return the password strength | 39,913,740 | <p>I'm struggling with my password rater program. How can i make sure that when i insert a password, my program returns the password strength. When i run this program it says that password_strength is stored at .....) is the return that i call at the end of my program wrong?</p>
<pre><code>print ("Welcome to this password rater program")
print ("Your password needs to have a minimum of 6 characters with a maximum of 20 characters.")
print ("Your password can contain lowercase and uppercase characters, numbers and special characters")
print("")
password = input("Please insert your password: ")
def check_len(password):
l = len(password)
if 6 < l < 20:
x = check_char(password, l)
else:
x = 0
return x
def check_char(password, l):
for i in range(l):
ascii = ord(password[i])
num = 0
upper = 0
symbols = 0
lower = 0
space = 0
if 96 < ascii < 123:
lower = 15
elif 47 < ascii < 58:
num = 25
elif 64 < ascii < 91:
upper = 25
elif ascii == 32:
space = 30
else:
symbols = 25
total = ((lower + num + upper + space + symbols) * len(password))
return total
def password_strength(total):
if total >= 1000:
print("Your chosen password is Very strong")
elif 700 < total < 999:
print("Your chosen password is strong")
elif 500 < total < 699:
print("your chosen password is medium")
elif total <= 500:
print("Your chosen password is weak")
return total
strength = check_len(password)
print(password_strength(strength))
</code></pre>
| 1 | 2016-10-07T09:19:46Z | 39,914,145 | <p>Well first of all, you tell python to print the function, not the evaluation of the function. This is why you get that message.</p>
<p>Also, you never call any of the functions you wrote. To get a working program
after the declaration of all definitions is the following:</p>
<p>Call the check_len definition:</p>
<pre><code>strength = check_len(password)
</code></pre>
<p>This definition doesn't return any value though. You could change it to:</p>
<pre><code>def check_len(password):
l = len(password)
if 6 < l < 16:
x = check_char(password, l)
else:
x = 0
return x
</code></pre>
<p>To have it return the score/strength.</p>
<p>Finally you should process the score using your 'password_strength' definition:</p>
<pre><code>password_strength(strength)
</code></pre>
<p>In this line there is no need to print, because the printing statements are in the definition itself. If you want to print the final score as well though, you could make it into the following line:</p>
<pre><code> print(password_strength(strength))
</code></pre>
<p>One more debug thingy: your check_char definition doesn't take any arguments.
You could solve this by changing it into:</p>
<pre><code>def check_char(password, l):
</code></pre>
<p>Final code:
print ("Welcome to this password rater program")
print ("Your password needs to have a minimum of 6 characters with a maximum of 16 characters.")
print ("Your password can contain lowercase and uppercase characters, numbers and special characters")
print ("")</p>
<pre><code>password = raw_input("Please insert your password: ")
def check_len(password):
l = len(password)
if 6 < l < 16:
x = check_char(password, l)
else:
x = 0
return x
def check_char(password, l):
for i in range(l):
ascii = ord(password[i])
num = 0
upper = 0
symbols = 0
lower = 0
space = 0
if 96 < ascii < 123:
lower = 15
elif 47 < ascii < 58:
num = 25
elif 64 < ascii < 91:
upper = 25
elif ascii == 32:
space = 30
else:
symbols = 25
total = ((lower + num + upper + space + symbols) * len(password))
return total
def password_strength(total):
if total >= 1000:
print("Your chosen password is Very strong")
elif 700 < total < 999:
print("Your chosen password is strong")
elif 500 < total < 699:
print("your chosen password is medium")
elif total <= 500:
print("Your chosen password is weak")
return total
strength = check_len(password)
print(password_strength(strength)) `
</code></pre>
| 3 | 2016-10-07T09:40:44Z | [
"python",
"python-3.x"
]
|
ImportError when configuring python's logging module with a dict and custom handler | 39,913,749 | <p>I've written a custom logging handler for python's logging package. This handler may or may not work, but this is beyond the scope of the question.</p>
<p>I'm trying to specify the handler using a configuration dict. However the logging package seems to be unable to find the correct class. This is the relevant section of my config dict:</p>
<pre><code>"file": {
"class": "iis.logging.LockingFileHandler",
.
.
.
}
</code></pre>
<p>Which is defined in a file <code>configuration/development.py</code>. It is imported and passed to <code>logging.config.dictConfig</code> in a file <code>iis/__init__.py</code>. <code>LockingFileHandler</code> is defined in a file <code>iis/logging.py</code>. Both <code>configuration</code> and <code>iis</code> are in my path.</p>
<p>When I run flask (which imports <code>iis/__init__</code>, I get the following error message:</p>
<pre><code>Traceback (most recent call last):
File "/usr/lib64/python3.5/logging/config.py", line 384, in resolve
self.importer(used)
ImportError: No module named 'iis.logging.LockingFileHandler'; 'iis.logging' is not a package
</code></pre>
<p>Followed by a bunch of exceptions caused by this one. I suspect that I am mising some trick here. Any ideas?</p>
| 0 | 2016-10-07T09:20:20Z | 39,915,471 | <p>I think I well victim to Python's confusing(!) import sematics. The module <code>iis.logging</code> was shaddowing the global <code>logging</code> module (somehow). Renaming to <code>iss.log</code> did the trick.</p>
| 0 | 2016-10-07T10:50:49Z | [
"python",
"logging",
"flask",
"python-3.5"
]
|
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have to manually copy a bunch of libraries into your virtualenv, since <code>--always-copy</code> doesn't work as expected) and generally slow.</p>
<p>There's (in theory) <a href="https://wiki.python.org/moin/BuildStatically">a way</a> to build python itself statically.</p>
<p>I wonder if I could pack interpreter with my code into one binary and run my application as module. Something like that: <code>./mypython -m myapp run</code> or <code>./mypython -m gunicorn -c ./gunicorn.conf myapp.wsgi:application</code>.</p>
| 22 | 2016-10-07T09:24:20Z | 39,994,355 | <p>Freeze options:</p>
<ul>
<li><a href="https://pypi.python.org/pypi/bbfreeze/1.1.3" rel="nofollow">https://pypi.python.org/pypi/bbfreeze/1.1.3</a></li>
<li><a href="http://cx-freeze.sourceforge.net/" rel="nofollow">http://cx-freeze.sourceforge.net/</a></li>
</ul>
<p>However, your target server should have the environment you want -> you should be able to 'create' it. If it doesn't, you should build your software to match the environment. </p>
<p>I found this handy guide on how to install custom version of python to a virtualenv, assuming you have ssh access: <a href="http://stackoverflow.com/a/5507373/5616110">http://stackoverflow.com/a/5507373/5616110</a></p>
<p>In virtualenv, you should be able to pip install anything and you shouldn't need to worry about sudo privileges. Of course, having those and access to package manager like apt makes everything a lot easier.</p>
| 0 | 2016-10-12T08:51:20Z | [
"python",
"build"
]
|
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have to manually copy a bunch of libraries into your virtualenv, since <code>--always-copy</code> doesn't work as expected) and generally slow.</p>
<p>There's (in theory) <a href="https://wiki.python.org/moin/BuildStatically">a way</a> to build python itself statically.</p>
<p>I wonder if I could pack interpreter with my code into one binary and run my application as module. Something like that: <code>./mypython -m myapp run</code> or <code>./mypython -m gunicorn -c ./gunicorn.conf myapp.wsgi:application</code>.</p>
| 22 | 2016-10-07T09:24:20Z | 40,057,486 | <p>You're probably looking for something like Freeze, which is able to compile your Python application with all its libraries into a static binary:</p>
<p><a href="https://pypi.python.org/pypi/cx_Freeze" rel="nofollow">PyPi page of Freeze</a></p>
<p><a href="https://wiki.python.org/moin/Freeze" rel="nofollow">Python Wiki page of Freeze</a></p>
<p><a href="http://cx-freeze.sourceforge.net/" rel="nofollow">Sourceforge page of Freeze</a></p>
| 0 | 2016-10-15T09:45:07Z | [
"python",
"build"
]
|
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have to manually copy a bunch of libraries into your virtualenv, since <code>--always-copy</code> doesn't work as expected) and generally slow.</p>
<p>There's (in theory) <a href="https://wiki.python.org/moin/BuildStatically">a way</a> to build python itself statically.</p>
<p>I wonder if I could pack interpreter with my code into one binary and run my application as module. Something like that: <code>./mypython -m myapp run</code> or <code>./mypython -m gunicorn -c ./gunicorn.conf myapp.wsgi:application</code>.</p>
| 22 | 2016-10-07T09:24:20Z | 40,057,634 | <p>There are two ways you could go about to solve your problem</p>
<ol>
<li>Use a static builder, like freeze, or pyinstaller, or py2exe</li>
<li>Compile using cython</li>
</ol>
<p>I will explain how you can go about doing it using the second, since the first method is not cross platform and version, and has been explained in other answers. Also, using programs like pyinstaller typically results in huge file sizes, where as using cython will result in a file that's KBs in size</p>
<p>First, install cython. Then, rename your python file (say test.py) into a pyx file </p>
<pre><code>$ sudo pip install cython
$ mv test.py test.pyx
</code></pre>
<p>Then, you can use cython along with GCC to compile it (Cython generates a C file out of a Python .pyx file, and then GCC compiles the C file)
(in reference to <a href="http://stackoverflow.com/a/22040484/5714445">http://stackoverflow.com/a/22040484/5714445</a>)</p>
<pre><code>$ cython test.pyx --embed
$ gcc -Os -I /usr/include/python3.5m -o test test.c -lpython3.5m -lpthread -lm -lutil -ldl
</code></pre>
<p>NOTE: Depending on your version of python, you might have to change the last command. To know which version of python you are using, simply use</p>
<pre><code>$ python -V
</code></pre>
<p>You will now have a binary file 'test', which is what you are looking for</p>
<p>NOTE: Cython is used to use C-Type Variable definitions for static memory allocation to speed up Python programs. In your case however, you will still be using traditional Python definitions.</p>
<p>NOTE2: If you are using additional libraries (like opencv, for example), you might have to provide the directory to them using -L and then specify the name of the library using -l in the GCC Flags. For more information on this, please refer to GCC flags</p>
| 11 | 2016-10-15T10:00:42Z | [
"python",
"build"
]
|
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have to manually copy a bunch of libraries into your virtualenv, since <code>--always-copy</code> doesn't work as expected) and generally slow.</p>
<p>There's (in theory) <a href="https://wiki.python.org/moin/BuildStatically">a way</a> to build python itself statically.</p>
<p>I wonder if I could pack interpreter with my code into one binary and run my application as module. Something like that: <code>./mypython -m myapp run</code> or <code>./mypython -m gunicorn -c ./gunicorn.conf myapp.wsgi:application</code>.</p>
| 22 | 2016-10-07T09:24:20Z | 40,077,889 | <p>To freeze your python executable and ship it along your code, embed it in an empty shell app. Follow the instructions how to embed python in an application from the <a href="https://docs.python.org/3/extending/embedding.html#embedding-python-in-another-application" rel="nofollow">official documentation</a>. You can start building a sample app directly from the C sample code they give on the web page. </p>
<p>Make that program execute your python application through the embedded python. Ship the program, the embedded python you used and your python program. Execute that program.</p>
| 0 | 2016-10-17T03:03:30Z | [
"python",
"build"
]
|
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have to manually copy a bunch of libraries into your virtualenv, since <code>--always-copy</code> doesn't work as expected) and generally slow.</p>
<p>There's (in theory) <a href="https://wiki.python.org/moin/BuildStatically">a way</a> to build python itself statically.</p>
<p>I wonder if I could pack interpreter with my code into one binary and run my application as module. Something like that: <code>./mypython -m myapp run</code> or <code>./mypython -m gunicorn -c ./gunicorn.conf myapp.wsgi:application</code>.</p>
| 22 | 2016-10-07T09:24:20Z | 40,099,944 | <p>You might wish to investigate <a href="http://nuitka.net/" rel="nofollow">Nuitka</a>. It takes python source code and converts it in to C++ API calls. Then it compiles into an executable binary (ELF on Linux). It has been around for a few years now and supports a wide range of Python versions.</p>
<p>You will probably also get a performance improvement if you use it. Recommended.</p>
| 0 | 2016-10-18T05:06:17Z | [
"python",
"build"
]
|
Is there a way to compile python application into static binary? | 39,913,847 | <p>What I'm trying to do is ship my code to a remote server, that may have different python version installed and/or may not have packages my app requires.</p>
<p>Right now to achieve such portability I have to build relocatable virtualenv with interpreter and code. That approach has some issues (for example, you have to manually copy a bunch of libraries into your virtualenv, since <code>--always-copy</code> doesn't work as expected) and generally slow.</p>
<p>There's (in theory) <a href="https://wiki.python.org/moin/BuildStatically">a way</a> to build python itself statically.</p>
<p>I wonder if I could pack interpreter with my code into one binary and run my application as module. Something like that: <code>./mypython -m myapp run</code> or <code>./mypython -m gunicorn -c ./gunicorn.conf myapp.wsgi:application</code>.</p>
| 22 | 2016-10-07T09:24:20Z | 40,135,113 | <p>If you are on a Mac you can use py2app to create a .app bundle, which starts your Django app when you double-click on it.</p>
<p>I described how to bundle Django and CherryPy into such a bundle at <a href="https://moosystems.com/articles/14-distribute-django-app-as-native-desktop-app-01.html" rel="nofollow">https://moosystems.com/articles/14-distribute-django-app-as-native-desktop-app-01.html</a></p>
<p>In the article I use pywebview to display your Django site in a local application window.</p>
| 0 | 2016-10-19T15:01:53Z | [
"python",
"build"
]
|
Selecting a column vector from a matrix in Python | 39,914,049 | <p>I would like to index a column vector in a matrix in Python/numpy and have it returned as a column vector and not a 1D array.</p>
<pre><code>x = np.array([[1,2],[3,4]])
x[:,1]
>array([2, 4])
</code></pre>
<p>Giving </p>
<p><code>np.transpose(x[:,1])</code></p>
<p>is not a solution. Following the <code>numpy.transpose</code> documentation, this will return a row vector (1-D array).</p>
| 2 | 2016-10-07T09:35:07Z | 39,914,077 | <p>Few options -</p>
<pre><code>x[:,[1]]
x[:,None,1]
x[:,1,None]
x[:,1][:,None]
x[:,1].reshape(-1,1)
x[None,:,1].T
</code></pre>
| 4 | 2016-10-07T09:36:10Z | [
"python",
"numpy",
"matrix",
"indexing"
]
|
looping over product to compute a serie in python | 39,914,160 | <p>I'm just gonna compute the result of below serie in python:</p>
<p>The formula</p>
<p><a href="http://i.stack.imgur.com/vxNE0.gif" rel="nofollow"><img src="http://i.stack.imgur.com/vxNE0.gif" alt="enter image description here"></a></p>
<p>So, here is my function to compute:</p>
<pre><code> def compute(limit):
pi = 1
for i in range(1,limit):
pi = pi * ((4*(i**2))//(4*(i**2)-1))
print(2*pi)
compute(10000) /*returns 2*/
</code></pre>
<p>I know it is a silly question. But could you address the problem with this snippet?</p>
| 1 | 2016-10-07T09:41:33Z | 39,914,253 | <p>You have <code>//</code> and not <code>/</code>, you wanted division, but made floor division</p>
<pre><code>def compute(limit):
pi = 1
for i in range(1,limit):
pi = pi * ((4*(i**2))/(4*(i**2)-1)) # you had here //
print(2*pi)
compute(10000)
</code></pre>
<p>Output:</p>
<pre><code>3.1415141108281714
</code></pre>
| 0 | 2016-10-07T09:45:41Z | [
"python"
]
|
looping over product to compute a serie in python | 39,914,160 | <p>I'm just gonna compute the result of below serie in python:</p>
<p>The formula</p>
<p><a href="http://i.stack.imgur.com/vxNE0.gif" rel="nofollow"><img src="http://i.stack.imgur.com/vxNE0.gif" alt="enter image description here"></a></p>
<p>So, here is my function to compute:</p>
<pre><code> def compute(limit):
pi = 1
for i in range(1,limit):
pi = pi * ((4*(i**2))//(4*(i**2)-1))
print(2*pi)
compute(10000) /*returns 2*/
</code></pre>
<p>I know it is a silly question. But could you address the problem with this snippet?</p>
| 1 | 2016-10-07T09:41:33Z | 39,914,341 | <p>Change one of the 4s into a float by putting a . after it and change the // into /. It makes python interpret everything as floats:</p>
<pre><code>def compute(limit):
pi = 1
for i in range(1,limit):
pi = pi * ((4.*(i**2))/(4*(i**2)-1))
print(2*pi)
compute(10000)
</code></pre>
| 0 | 2016-10-07T09:50:36Z | [
"python"
]
|
looping over product to compute a serie in python | 39,914,160 | <p>I'm just gonna compute the result of below serie in python:</p>
<p>The formula</p>
<p><a href="http://i.stack.imgur.com/vxNE0.gif" rel="nofollow"><img src="http://i.stack.imgur.com/vxNE0.gif" alt="enter image description here"></a></p>
<p>So, here is my function to compute:</p>
<pre><code> def compute(limit):
pi = 1
for i in range(1,limit):
pi = pi * ((4*(i**2))//(4*(i**2)-1))
print(2*pi)
compute(10000) /*returns 2*/
</code></pre>
<p>I know it is a silly question. But could you address the problem with this snippet?</p>
| 1 | 2016-10-07T09:41:33Z | 39,914,546 | <p>As others have already mentioned, <code>//</code> is integer division. No matter whether you're dividing floats or integers, the result will always be an integer. Pi is not an integer, so you should use float division: <code>/</code> and tell Python explicitly that you really want a float by converting one of the numbers to float<sup>*</sup>. For example, you could do <code>4</code> -> <code>4.</code> (notice the dot).</p>
<p>You could do the same thing in a more clear way using <a href="https://docs.python.org/3/library/functools.html" rel="nofollow"><code>functools</code></a> and <a href="https://docs.python.org/2/library/operator.html" rel="nofollow"><code>operator</code></a> modules and a generator expression. </p>
<pre><code>import functools
import operator
def compute(limit):
return 2 * functools.reduce(operator.mul, ((4.*(i**2)/(4*(i**2)-1) for i in range(1, limit + 1))
</code></pre>
<p><sub>* Python 3 does float division with <code>4/(something)</code> even without this, but Python 2.7 will need <code>from __future__ import division</code> to divide as freely as Python 3, otherwise the division will result in an integer in any way.</sub></p>
| 1 | 2016-10-07T10:01:01Z | [
"python"
]
|
Combining databases: identifying common records -- most efficient way | 39,914,198 | <p>I have a set of 20 sqlite databases (50 tables each and roughly 100 thousand records total per DB).
I want to combine these 20 databases into one master DB.
The concept is to have an additional column, which indicates for which domain the record is applicable.</p>
<hr>
<p>For example:</p>
<p><strong>Table A</strong></p>
<pre><code>FRUIT | COLOR | SHAPE
----------------------
apple | red | round
banana| yellow | curved
</code></pre>
<p><strong>Table B</strong></p>
<pre><code>FRUIT | COLOR | SHAPE
----------------------
apple | red | round
banana| yellow | curved
</code></pre>
<p><strong>Table C</strong></p>
<pre><code>FRUIT | COLOR | SHAPE
----------------------
apple | red | round
banana| blue | straight
</code></pre>
<p>These tables (A, B and C) would be combined into a master table:</p>
<p><strong>Master Table</strong></p>
<pre><code>FRUIT | COLOR | SHAPE | DOMAIN
---------------------------------
apple | red | round | 0b111
banana| yellow | curved | 0b110
banana| blue | straight| 0b001
</code></pre>
<hr>
<p>I have the databases in text file format (i.e. tab seperated lists). I use Python to import them into my sqlite DB.
How would I <em>most efficiently</em> do this merging process?</p>
<p>I have two ideas:</p>
<ol>
<li><p>Import the first DB into the master DB. When importing the next DB, check if the complete record exists. If yes, run an SQL UPDATE query on the applicability column. If not, create new record using INSERT.</p></li>
<li><p>For each type of table load each of the 20 domain-tables in python and see, if a record exists on every domain or a subset. Then import the record with the applicability into the master DB. </p></li>
</ol>
<p>I would like to know if there is an efficient way of performing these operations. Due to the size of each database and the requirement of having to do this import multiple times, I need to speed up the process as much as possible.</p>
| 0 | 2016-10-07T09:43:11Z | 39,914,929 | <p>Making individual selects and updates for each record*domain is way slower than merging records in memory.</p>
<p>Load 20 tables into memory. Make complete list of records in memory. Bulk insert into DB.</p>
<p>Probably speed-efficient way for merge would be like this:</p>
<p>Load (key,value)->(domain code, null for now) into one set, and separately key->value into domain-table dictionary.</p>
<p>Then go through (key,value) set, look up for value in each domain dictionary and form domain code in master dictionary.</p>
<p>Then go through result of previous step and perform bulk insert, commiting once per about 1000 records.</p>
| 0 | 2016-10-07T10:20:06Z | [
"python",
"database",
"performance",
"sqlite3"
]
|
What is the reason that a java method cannot return more than one value? | 39,914,362 | <p>As you know in python, a function can returns more than one value</p>
<p>eg:</p>
<pre><code>def myfun():
return 1, 2, 3
</code></pre>
<p>And we can call it in this way:</p>
<pre><code>a, b, c= myfun()
</code></pre>
<p>But in JAVA, we have cannot return more that one value, so we have to create one object containing the values that we want to return:</p>
<pre><code>class MyObject {
private Integer a;
private Integer b;
private Integer c;
public Integer getA() {
return a;
}
public void setA(Integer a) {
this.a = a;
}
public Integer getB() {
return b;
}
public void setB(Integer b) {
this.b = b;
}
public Integer getC() {
return c;
}
public void setC(Integer c) {
this.c = c;
}
}
</code></pre>
<p>and our function will return this object</p>
<p>eg:</p>
<pre><code>public MyObject myfun(){
MyObject myObject = new MyObject();
myObject.setA(1);
myObject.setB(2);
myObject.setC(3);
return myObject;
}
</code></pre>
<p>ÙAnd we call it in this way:</p>
<pre><code>obj = myfun();
Integer a = obj.getA();
Integer b = obj.getB();
Integer c = obj.getC();
</code></pre>
<p>Another solution is to return an array containing all the values that should be returned</p>
<p>But the both methods are ugly in coding, is there any limitation in JAVA so a method cannot returns more than one value?</p>
| -1 | 2016-10-07T09:51:28Z | 39,914,403 | <p>Strictly speaking, Python does not return more than one value either. <code>1, 2, 3</code> is a tuple; it's just that Python's syntax supports automatically unpacking that tuple into separate variables.</p>
| 10 | 2016-10-07T09:53:28Z | [
"java",
"python"
]
|
What is the reason that a java method cannot return more than one value? | 39,914,362 | <p>As you know in python, a function can returns more than one value</p>
<p>eg:</p>
<pre><code>def myfun():
return 1, 2, 3
</code></pre>
<p>And we can call it in this way:</p>
<pre><code>a, b, c= myfun()
</code></pre>
<p>But in JAVA, we have cannot return more that one value, so we have to create one object containing the values that we want to return:</p>
<pre><code>class MyObject {
private Integer a;
private Integer b;
private Integer c;
public Integer getA() {
return a;
}
public void setA(Integer a) {
this.a = a;
}
public Integer getB() {
return b;
}
public void setB(Integer b) {
this.b = b;
}
public Integer getC() {
return c;
}
public void setC(Integer c) {
this.c = c;
}
}
</code></pre>
<p>and our function will return this object</p>
<p>eg:</p>
<pre><code>public MyObject myfun(){
MyObject myObject = new MyObject();
myObject.setA(1);
myObject.setB(2);
myObject.setC(3);
return myObject;
}
</code></pre>
<p>ÙAnd we call it in this way:</p>
<pre><code>obj = myfun();
Integer a = obj.getA();
Integer b = obj.getB();
Integer c = obj.getC();
</code></pre>
<p>Another solution is to return an array containing all the values that should be returned</p>
<p>But the both methods are ugly in coding, is there any limitation in JAVA so a method cannot returns more than one value?</p>
| -1 | 2016-10-07T09:51:28Z | 39,914,420 | <p>That Python function is only returning one value.</p>
<pre><code>>>> def myfun():
... return 1, 2, 3
...
>>> a = myfun()
>>> type(a)
<class 'tuple'>
</code></pre>
<p>As you can see, it's a container, just like you need in Java.</p>
| 8 | 2016-10-07T09:54:30Z | [
"java",
"python"
]
|
Python: Matplotlib open interactive figures | 39,914,370 | <p>since I like the interactive figures of matlab (*.fig). I wrote a small program for saving interactive figures in Python. I use pickle to dump a matplotlib.pyplot figure in a name.pyfig file:</p>
<pre><code> output = open('name.pyfig', 'wb')
pickle.dump(plt.gcf(), output)
output.close()
</code></pre>
<p>To open the figure I use:</p>
<pre><code> f = open('name.pyfig','rb')
pickle.load(f)
f.close()
</code></pre>
<p>Now I'd like to implement the following: I want to open the figure by double clicking on the name.pyfig file in the windows file explorer.</p>
<p>Since name.pyfig only contains the data of the figure, I wrote a python script openfig.py to open the figure by using </p>
<pre><code> python openfig.py name.pyfig
</code></pre>
<p>in CMD which is working quite well. To be able to run the openfig.py by double-clicking on the pyfig file I associate the pyfig extension with a bat file (open with - choose default program) calling the code from above which is also working, as long as the bat file is in the same folder! For some reason, it is not possible to select the bat file as default program for the pyfig file if it is located somewhere else!</p>
<p>Any solution?
Ge</p>
<p>System:
Python Version 2.7.9
Win 7 Enterprise</p>
| 2 | 2016-10-07T09:51:56Z | 39,915,987 | <p>You need to give the full absolute path if you want to put the bat file somewhere else.</p>
<pre><code>f = open('C:\full\path\to\folder\name.pyfig','rb')
</code></pre>
| 0 | 2016-10-07T11:20:58Z | [
"python",
"matplotlib",
"save",
"interactive",
"figure"
]
|
Python: Matplotlib open interactive figures | 39,914,370 | <p>since I like the interactive figures of matlab (*.fig). I wrote a small program for saving interactive figures in Python. I use pickle to dump a matplotlib.pyplot figure in a name.pyfig file:</p>
<pre><code> output = open('name.pyfig', 'wb')
pickle.dump(plt.gcf(), output)
output.close()
</code></pre>
<p>To open the figure I use:</p>
<pre><code> f = open('name.pyfig','rb')
pickle.load(f)
f.close()
</code></pre>
<p>Now I'd like to implement the following: I want to open the figure by double clicking on the name.pyfig file in the windows file explorer.</p>
<p>Since name.pyfig only contains the data of the figure, I wrote a python script openfig.py to open the figure by using </p>
<pre><code> python openfig.py name.pyfig
</code></pre>
<p>in CMD which is working quite well. To be able to run the openfig.py by double-clicking on the pyfig file I associate the pyfig extension with a bat file (open with - choose default program) calling the code from above which is also working, as long as the bat file is in the same folder! For some reason, it is not possible to select the bat file as default program for the pyfig file if it is located somewhere else!</p>
<p>Any solution?
Ge</p>
<p>System:
Python Version 2.7.9
Win 7 Enterprise</p>
| 2 | 2016-10-07T09:51:56Z | 39,958,604 | <p>Nevermind, I manually added a registry entry which worked fine:</p>
<pre><code> Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\pyfig_auto_file]
@=""
[HKEY_CLASSES_ROOT\pyfig_auto_file\DefaultIcon]
@="path_to_ico_file"
[HKEY_CLASSES_ROOT\pyfig_auto_file\shell]
[HKEY_CLASSES_ROOT\pyfig_auto_file\shell\open]
[HKEY_CLASSES_ROOT\pyfig_auto_file\shell\open\command]
@="\"path_to_bat_file\"\"%1\""
</code></pre>
<p>Ge</p>
| 0 | 2016-10-10T12:44:41Z | [
"python",
"matplotlib",
"save",
"interactive",
"figure"
]
|
indent is broken after saving back updated json dict to file | 39,914,524 | <p>I have a nested dictionary with many items in a json file:</p>
<pre><code>{
"Create Code For Animals": {
"mammals": {
"dog": {
"color": "brown",
"name": "John",
"legs": "four",
"tail": "yes"
},
"cat": {
"color": "blue",
"name": "Johnny",
"legs": "four",
"tail": "yes"
},
"donkey": {
"color": "grey",
"name": "Mickey",
"legs": "four",
"tail": "yes"
}
</code></pre>
<p>I want to replace the name in each one of the animals, then save it back to the file, <strong>AND</strong> keep the indent as it was (as shown).
I'm using the following 2 methods for loading and dumping the original and updated dictionary. </p>
<p>All is working well (for changing the value and saving it back to the file) except the indent (format) of the lines is ruined after saving the file and the file is saved as one long line (with '\n' shown after the updated value). </p>
<p>I've tried using 'pickle' (as seen in one of the posts here), but this didn't work, made a mess of all the data in the file. </p>
<pre><code> def loadJson(self, jsonFilename):
with open(FILE_PATH + '\\' + jsonFilename, 'r') as f:
return json.load(f)
def writeJson(self, jsonFilename, jsonDict):
with open(FILE_PATH + '\\' + jsonFilename, 'w') as f:
return json.dump(jsonDict, f)
</code></pre>
<p>Any help will do. </p>
| 4 | 2016-10-07T09:59:49Z | 39,914,589 | <p>json.dumps and dump have a parameter called indent</p>
<pre><code>If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation. Since the default item separator is ``', '``, the
output might include trailing whitespace when ``indent`` is specified.
You can use ``separators=(',', ': ')`` to avoid this
</code></pre>
<p>Something like this would do:</p>
<pre><code>json.dump(jsonDict,f,indent=4)
</code></pre>
| 4 | 2016-10-07T10:02:31Z | [
"python",
"json",
"dictionary"
]
|
How to convert "\uxxxx\uxxxx" to u'\Uxxxxxxxx'? | 39,914,531 | <p>I have a text file who is filled with unicode characters as <code>"\ud83d\udca5"</code> but python don't seem to like them.<br>
But if I replace it by <code>u'\U0001f4a5'</code> which seems to be his python escape style (<a href="http://www.charbase.com/1f4a5-unicode-collision-symbol" rel="nofollow">Charbase</a>), it works.</p>
<p>Is there a solution to convert them all into the <code>u"\Uxxxxxxxx"</code> escape format than python can understand ?</p>
<p>Thanks.</p>
| 0 | 2016-10-07T10:00:12Z | 39,915,220 | <p>You're mixing up Unicode and encoded strings. <code>u'\U0001f4a5'</code> is a Unicode object, Python's internal datatype for handling strings. (In Python 3, the <code>u</code> is optional since now <em>all</em> strings are Unicode objects).</p>
<p>Files, on the other hand, use encodings. UTF-8 is the most common one, but it's just one means of storing a Unicode object in a byte-oriented file or stream. When opening such a file, you need to specify the encoding so Python can translate the bytes into meaningful Unicode objects.</p>
<p>In your case, it seems you need to open file using the <code>UTF-16</code> codec instead of <code>UTF-8</code>. </p>
<pre><code>with open("myfile.txt", encoding="utf-16") as f:
s = f.read()
</code></pre>
<p>will give you the proper contents if the codec is in fact <code>UTF-16</code>. If it doesn't look right, try <code>"utf-16-le"</code> or <code>"utf-16-be"</code>.</p>
| 0 | 2016-10-07T10:35:13Z | [
"python",
"python-3.x",
"unicode",
"escaping",
"unicode-escapes"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.