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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Command failed: tar xzf android-sdk_r20-linux.tgz | 38,562,910 | <p>I was trying to build kivy app to android and got this error</p>
<pre><code># Check configuration tokens
# Ensure build layout
# Check configuration tokens
# Preparing build
# Check requirements for android
# Install platform
# Apache ANT found at /home/ali/.buildozer/android/platform/apache-ant-1.9.4
# Android SDK is missing, downloading
# Unpacking Android SDK
# Command failed: tar xzf android-sdk_r20-linux.tgz
#
# Buildozer failed to execute the last command
# If the error is not obvious, please raise the log_level to 2
# and retry the latest command.
# In case of a bug report, please add a full log with log_level = 2
</code></pre>
<p>command</p>
<pre><code>$ buildozer android_new debug
</code></pre>
<p>log:
<a href="http://paste.ubuntu.com/20850804/">http://paste.ubuntu.com/20850804/</a></p>
<p>want any details? request in the comments</p>
| 6 | 2016-07-25T08:28:13Z | 38,613,838 | <p>I figured it out!</p>
<p>the problem was some google services are not available where i live due to USA sanctions on my country (Sudan) and the returned response is html (not in gzip format).</p>
<p>the solution is to use vpn.</p>
| 2 | 2016-07-27T13:05:40Z | [
"android",
"python",
"kivy",
"buildozer"
] |
How to get sum of numbers having exactly 2 one's in their binary representation in a range? | 38,562,982 | <p>I want to find out the sum of numbers in a range say N which has exactly 2 ones in its binary representation.I wrote the code as:</p>
<pre><code>N = int(raw_input())
sum1 = 0
for i in range(1, N + 1):
if bin(i)[2:].count('1') == 2:
sum1 = sum1 + i
</code></pre>
<p>This code takes a lot of time. Is there any faster way to do this calculation? </p>
| 0 | 2016-07-25T08:32:02Z | 38,563,347 | <p>Try this code:</p>
<pre><code>def two_bit_numbers(N):
bit0 = 0
bit1 = 1
while True:
n = (1<<bit1) + (1<<bit0)
if n > N:
break
yield n
bit0 += 1
if bit0 == bit1:
bit1 += 1
bit0 = 0
N = 100
sum1 = 0
for i in two_bit_numbers(N):
# print i, bin(i)
sum1 += i
print sum1
</code></pre>
| 4 | 2016-07-25T08:52:09Z | [
"python",
"python-2.7"
] |
How to get sum of numbers having exactly 2 one's in their binary representation in a range? | 38,562,982 | <p>I want to find out the sum of numbers in a range say N which has exactly 2 ones in its binary representation.I wrote the code as:</p>
<pre><code>N = int(raw_input())
sum1 = 0
for i in range(1, N + 1):
if bin(i)[2:].count('1') == 2:
sum1 = sum1 + i
</code></pre>
<p>This code takes a lot of time. Is there any faster way to do this calculation? </p>
| 0 | 2016-07-25T08:32:02Z | 38,564,208 | <p>If we look at how to find number that have two '1' when written in binary, we get to two cases : </p>
<ul>
<li>We have an element > 1 with 1 '1' in binary representation and we add 1 to it</li>
<li>We have an element that has two '1' in binary representation, and we multiply it by 2.</li>
</ul>
<p>So, to look for the number of element matching this case, you could just do :</p>
<pre><code>num = int(raw_input())
def get_numbers(N):
sum1 = []
sum2 = []
i = 2
while i < N:
# we add the elements of case 2
sum1.extend(sum2)
# we add the element of case 1
sum1.append(i+1)
sum2 = [2*x for x in sum1 if x > i]
# we check for the elements with one more number when written in binary
i *= 2
# sum1 now contains all elements with two '1' in binary between 0 and the power of 2 above N.
# we remove the elements above N
sum1 = [x for x in sum1 if x <= N]
# we sort the list
sum1.sort()
# we take the length of the list, of the number of elements with two '1' in binary between 0 and N
return sum1
print(get_numbers(num))
</code></pre>
<p>This should be faster, as we do not test every number between 0 and N, and have a log2(N) complexity.</p>
<p>Do not hesitate if you have any question about my method.</p>
<p>This method is slower than the one in the other answer (around 2 times slower)</p>
| -1 | 2016-07-25T09:33:14Z | [
"python",
"python-2.7"
] |
pip permission issue on OS X | 38,562,987 | <p>I can't automatically update <strong>pip</strong> because it alway show error with permission:</p>
<pre><code>OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/site-packages/pkg_resources/__init__.py'
</code></pre>
<p>Command for update:</p>
<blockquote>
<p>sudo -H pip freeze --local | grep -v '^-e' | cut -d = -f 1 | xargs pip install -U</p>
</blockquote>
<p>How to solve this issue?</p>
| 0 | 2016-07-25T08:32:23Z | 38,563,095 | <p>The <code>sudo</code> command doesn't apply to the whole pipe; it only applies to the first <code>pip freeze</code> command.</p>
<p>You'll need to use <code>sudo</code> on the <code>xargs</code> command too:</p>
<pre><code>sudo -H pip freeze --local | grep -v '^-e' | cut -d = -f 1 | xargs sudo -H pip install -U
</code></pre>
<p>Alternatively, use <code>sudo</code> to create a new sub-shell and run your pipe in that:</p>
<pre><code>sudo -H bash -c 'pip freeze --local | grep -v \'^-e\' | cut -d = -f 1 | xargs pip install -U'
</code></pre>
| 1 | 2016-07-25T08:38:36Z | [
"python",
"osx",
"pip"
] |
OpenCV-Python cv2.CV_CAP_PROP_POS_FRAMES error | 38,563,079 | <p>Currently, I am use opencv 3.1.0, and I encountered the following error when executing the following code:</p>
<pre><code>post_frame = cap.get(cv2.CV_CAP_PROP_POS_FRAMES)
</code></pre>
<p>I got the following error Message:</p>
<p>File "videoOperation.py", line 37, in
pos_frame = cap.get(cv2.CV_CAP_PROP_POS_FRAMES)
AttributeError: 'module' object has no attribute 'CV_CAP_PROP_POS_FRAMES'</p>
<p>The code should be write in the following format when using OpenCV 2.X:</p>
<pre><code>post_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
</code></pre>
<p>Refer from <a href="http://stackoverflow.com/questions/30013009/opencv-3-0-0-dev-python-bindings-not-working-properly">opencv 3.0.0-dev python bindings not working properly</a>, I know that </p>
<blockquote>
<p>the cv2.cv submodule got removed in opencv3.0, also some constants were changed</p>
</blockquote>
<p>But the cv2.CV_CAP_PROP_POS_FRAMES didn't work for me, So what and i suppose to do?</p>
| 0 | 2016-07-25T08:37:38Z | 38,566,846 | <p>You're looking for this:</p>
<pre><code>post_frame = cap.get(cv2.CAP_PROP_POS_FRAMES)
</code></pre>
| 0 | 2016-07-25T11:43:03Z | [
"python",
"opencv",
"image-processing",
"constants",
"video-capture"
] |
OpenCV-Python cv2.CV_CAP_PROP_POS_FRAMES error | 38,563,079 | <p>Currently, I am use opencv 3.1.0, and I encountered the following error when executing the following code:</p>
<pre><code>post_frame = cap.get(cv2.CV_CAP_PROP_POS_FRAMES)
</code></pre>
<p>I got the following error Message:</p>
<p>File "videoOperation.py", line 37, in
pos_frame = cap.get(cv2.CV_CAP_PROP_POS_FRAMES)
AttributeError: 'module' object has no attribute 'CV_CAP_PROP_POS_FRAMES'</p>
<p>The code should be write in the following format when using OpenCV 2.X:</p>
<pre><code>post_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
</code></pre>
<p>Refer from <a href="http://stackoverflow.com/questions/30013009/opencv-3-0-0-dev-python-bindings-not-working-properly">opencv 3.0.0-dev python bindings not working properly</a>, I know that </p>
<blockquote>
<p>the cv2.cv submodule got removed in opencv3.0, also some constants were changed</p>
</blockquote>
<p>But the cv2.CV_CAP_PROP_POS_FRAMES didn't work for me, So what and i suppose to do?</p>
| 0 | 2016-07-25T08:37:38Z | 38,568,807 | <p>Try typing this instead of yours:</p>
<pre><code>post_frame = cap.get(1) #CAP_PROP_POS_FRAMES = 1
</code></pre>
<p>If you type <code>help('cv2')</code> in the Python shell you will find some modifications to the syntax.These are not all the <code>Data</code>. Just an illustration.</p>
<pre><code>CAP_PROP_PAN = 33
CAP_PROP_POS_AVI_RATIO = 2
CAP_PROP_POS_FRAMES = 1
CAP_PROP_POS_MSEC = 0
CAP_PROP_PVAPI_BINNINGX = 304
CAP_PROP_PVAPI_BINNINGY = 305
CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302
</code></pre>
| 0 | 2016-07-25T13:15:05Z | [
"python",
"opencv",
"image-processing",
"constants",
"video-capture"
] |
Error while updating column in mysql using python | 38,563,131 | <p>Basically what my code does is simply update the database I have created where all the column are of 'varchar' format. My code is able to create a new entry when the time frame is '10:00-10:15'. However, when it is unable to update it when the time frame becomes '10:15-10:30' or basically any other time frame. My code is below:</p>
<pre><code>import time
import MySQLdb
from MySQLdb import *
import datetime
import json
date = time.localtime()
year_mon_date_day = [date.tm_year, date.tm_mon, date.tm_mday, date.tm_wday]
column = ''
if date.tm_hour==10:
if date.tm_min<=15:
column = "10:00-10:15"
elif date.tm_min<=30:
column = "10:15-10:30"
elif date.tm_min <= 45:
column = "10:30-10:45"
elif date.tm_min <= 60:
column = "10:45-11:00"
elif date.tm_hour==11:
if date.tm_min<=15:
column = "11:00-11:15"
elif date.tm_min<=30:
column = "11:15-11:30"
elif date.tm_min <= 45:
column = "11:30-11:45"
elif date.tm_min <= 60:
column = "11:45-12:00"
elif date.tm_hour==12:
if date.tm_min<=15:
column = "12:00-12:15"
elif date.tm_min<=30:
column = "12:15-12:30"
elif date.tm_min <= 45:
column = "12:30-12:45"
elif date.tm_min <= 60:
column = "12:45-01:00"
elif date.tm_hour==13:
if date.tm_min<=15:
column = "01:00-01:15"
elif date.tm_min<=30:
column = "01:15-01:30"
elif date.tm_min <= 45:
column = "01:30-01:45"
elif date.tm_min <= 60:
column = "01:45-02:00"
else:
pass
db = MySQLdb.connect(host='localhost', user='root', passwd='4747',db='traffic_record')
cursor=db.cursor()
if column == "10:00-10:15":
query = '''INSERT INTO `traffic_record`.`RoadA` ( `Date`,`Day`,`''' + column + '''`) VALUES ('%s','%s','%s')'''
value = (year_mon_date_day,date.tm_wday, 9)
else:
query = '''UPDATE `traffic_record`.`RoadA` SET `''' + column + '''`=`%s` WHERE `Date`=''' + str(year_mon_date_day) + '''`'''
value = (3)
cursor.execute(query, value)
db.commit()
db.close()
</code></pre>
<p>My code gives following error when I try to run it in any other time frame other than '10:00-10:15'. I receive the following error:</p>
<pre><code>/usr/bin/python2.7 /home/sparsha/PycharmProjects/MachineLearning/fill_table.py
Traceback (most recent call last):
File "/home/sparsha/PycharmProjects/MachineLearning/fill_table.py", line 83, in <module>
cursor.execute(query, value)
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: 'int' object is not iterable
Process finished with exit code 1
</code></pre>
<p>I am unable to solve it. Any help will be highly appreciated. Thanks.</p>
| 0 | 2016-07-25T08:40:39Z | 38,563,161 | <p>You should set your value as an iterable:</p>
<pre><code>value = (3,)
# ^
</code></pre>
<p>What you have <code>(3)</code> is an integer with a grouping parenthesis. The parenthesis does not make the integer an iterable. But adding that comma makes it a singleton tuple which is what you want.</p>
| 0 | 2016-07-25T08:42:12Z | [
"python",
"mysql"
] |
Timing out a function in windows(python) | 38,563,164 | <p>I want to implement a function which should be able to timeout a function after particular time.</p>
<p>In Linux, SIGALRM is there to use, but in windows i could not find any thing like that. </p>
<p>Is there any way i can achieve this in windows?
Can it be done without decorator??</p>
<p>Please Note Am a newbie in python.</p>
| 0 | 2016-07-25T08:42:18Z | 38,563,273 | <p>Unfortunately this isn't something natively built into windows. What you can do is a workaround whereby you create your own thread handler. </p>
<p><a href="http://stackoverflow.com/questions/8420422/python-windows-equivalent-of-sigalrm">Described in a previous question here</a></p>
| 0 | 2016-07-25T08:48:50Z | [
"python"
] |
Inception v3 retraining error (flower example) | 38,563,173 | <p>I'm currently facing a weird bug with the flower retraining example (<a href="https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html</a>).</p>
<p>Tensorflow Release 0.9 was installed from source and I tried to run the image_retraining python script (it does start and create a few bottlenecks
but then the following error message appears).</p>
<p>Might anyone have an idea what the problem could be? I didn't find any similar posts to this.</p>
<pre><code>E tensorflow/core/kernels/check_numerics_op.cc:157] abnormal_detected_host @0x10007200300 = {1, 0} activation input is not finite.
Traceback (most recent call last):
File "examples/image_retraining/retrain.py", line 888, in <module>
tf.app.run()
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 30, in run
sys.exit(main(sys.argv))
File "examples/image_retraining/retrain.py", line 798, in main
jpeg_data_tensor, bottleneck_tensor)
File "examples/image_retraining/retrain.py", line 456, in cache_bottlenecks
jpeg_data_tensor, bottleneck_tensor)
File "examples/image_retraining/retrain.py", line 414, in get_or_create_bottleneck
bottleneck_tensor)
File "examples/image_retraining/retrain.py", line 331, in run_bottleneck_on_image
{image_data_tensor: image_data})
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 382, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 655, in _run
feed_dict_string, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 723, in _do_run
target_list, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 743, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: activation input is not finite. : Tensor had NaN values
[[Node: conv_1/CheckNumerics = CheckNumerics[T=DT_FLOAT, message="activation input is not finite.", _device="/job:localhost/replica:0/task:0/gpu:0"](conv_1/batchnorm)]]
Caused by op u'conv_1/CheckNumerics', defined at:
File "examples/image_retraining/retrain.py", line 888, in <module>
tf.app.run()
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 30, in run
sys.exit(main(sys.argv))
File "examples/image_retraining/retrain.py", line 769, in main
create_inception_graph())
File "examples/image_retraining/retrain.py", line 312, in create_inception_graph
RESIZED_INPUT_TENSOR_NAME]))
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/importer.py", line 274, in import_graph_def
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2297, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1231, in __init__
self._traceback = _extract_stack()
</code></pre>
| 1 | 2016-07-25T08:43:11Z | 38,652,873 | <p>This is a bug in TensorFlow that I have also encountered (I'm using 2x GTX 1080 in Ubuntu 14.04) </p>
<p>One option is to install Cuda 8.0. However, Cuda 8.0 isn't fully supported and you may encounter other issues.</p>
<p>Another way to work around this if you are just experimenting is to build it and run it on CPUs only, at least for the bottleneck generation phase.</p>
<pre><code>bazel build -c opt --copt=-mavx tensorflow/examples/image_retraining:retrain
bazel-bin/tensorflow/examples/image_retraining/retrain --image_dir ~/flower_photos
</code></pre>
<p>As you probably know, if you've built TensorFlow with GPU support and then run this:</p>
<pre><code>python tensorflow/examples/image_retraining/retrain.py --image_dir ~/flower_photos
</code></pre>
<p>it will run with GPU support and then you'll probably hit the same error.</p>
<p>I've opened an issue here:
<a href="https://github.com/tensorflow/tensorflow/issues/3560" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/3560</a></p>
<p>Until they fix it, the workaround works as long as you don't have a large number of categories to classify for.</p>
| 0 | 2016-07-29T07:25:05Z | [
"python",
"tensorflow"
] |
Python's equivalent of Java's Set.add()? | 38,563,245 | <p>Java's <code>Set.add</code> function will return a boolean value, which is <code>true</code> if the set did not already contain the specified element.</p>
<p>Python's <code>Set.add</code> does not have a return value.</p>
<p>Seems like in Python if I want to do the same thing, I have to check if it is in the set first and then add it if not.</p>
<p>Is there a simpler way to do that (preferably a one-liner)?</p>
<p>Ref:<br>
<a href="https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)" rel="nofollow">https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)</a>
<a href="https://docs.python.org/2/library/sets.html#sets.Set" rel="nofollow">https://docs.python.org/2/library/sets.html#sets.Set</a></p>
| 1 | 2016-07-25T08:47:22Z | 38,563,291 | <p>No, Python's set implementation has no such method; as you noted you'll have to test for presence separately:</p>
<pre><code>if obj not in setobj:
setobj.add(obj)
</code></pre>
<p>or, what I usually do:</p>
<pre><code>if obj in setobj:
return # or break out of a loop, etc.
# handle the case where the set doesn't have the object yet.
</code></pre>
<p>You can always subclass the <code>set</code> type:</p>
<pre><code>class SetWithPresenceCheck(set):
def add(self, value):
not_present = value not in self
super(SetWithPresenceCheck, self).add(value)
return not_present
</code></pre>
<p>Note that the real reason <code>Set.add()</code> returns a boolean is to make adding and testing an <em>atomic operation</em>; implementations of the interface can (optionally) make the method synchronised and let callers avoid race conditions. Python's built-in set doesn't make any thread-safety promises <em>anyway</em>.</p>
| 2 | 2016-07-25T08:49:34Z | [
"java",
"python",
"set"
] |
Python's equivalent of Java's Set.add()? | 38,563,245 | <p>Java's <code>Set.add</code> function will return a boolean value, which is <code>true</code> if the set did not already contain the specified element.</p>
<p>Python's <code>Set.add</code> does not have a return value.</p>
<p>Seems like in Python if I want to do the same thing, I have to check if it is in the set first and then add it if not.</p>
<p>Is there a simpler way to do that (preferably a one-liner)?</p>
<p>Ref:<br>
<a href="https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)" rel="nofollow">https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)</a>
<a href="https://docs.python.org/2/library/sets.html#sets.Set" rel="nofollow">https://docs.python.org/2/library/sets.html#sets.Set</a></p>
| 1 | 2016-07-25T08:47:22Z | 38,563,374 | <p>The union operator is much faster than add anyway.</p>
<pre><code>>>> set_a = set('pqrs')
>>> set_b = ['t', 'u', 'v']
>>> set_a |= set(set_b)
>>> set_a
set(['p','q','r','s','t','u','v'])
</code></pre>
| -1 | 2016-07-25T08:53:34Z | [
"java",
"python",
"set"
] |
Python's equivalent of Java's Set.add()? | 38,563,245 | <p>Java's <code>Set.add</code> function will return a boolean value, which is <code>true</code> if the set did not already contain the specified element.</p>
<p>Python's <code>Set.add</code> does not have a return value.</p>
<p>Seems like in Python if I want to do the same thing, I have to check if it is in the set first and then add it if not.</p>
<p>Is there a simpler way to do that (preferably a one-liner)?</p>
<p>Ref:<br>
<a href="https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)" rel="nofollow">https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)</a>
<a href="https://docs.python.org/2/library/sets.html#sets.Set" rel="nofollow">https://docs.python.org/2/library/sets.html#sets.Set</a></p>
| 1 | 2016-07-25T08:47:22Z | 38,563,459 | <p>maybe with ternary conditional operator : </p>
<pre><code>the_set.add(what_ever) or True if what_ever not in the_set else False
</code></pre>
<p>This will return False if <code>what_ever</code> was in the set, True if it wasn't</p>
| -1 | 2016-07-25T08:57:39Z | [
"java",
"python",
"set"
] |
Python's equivalent of Java's Set.add()? | 38,563,245 | <p>Java's <code>Set.add</code> function will return a boolean value, which is <code>true</code> if the set did not already contain the specified element.</p>
<p>Python's <code>Set.add</code> does not have a return value.</p>
<p>Seems like in Python if I want to do the same thing, I have to check if it is in the set first and then add it if not.</p>
<p>Is there a simpler way to do that (preferably a one-liner)?</p>
<p>Ref:<br>
<a href="https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)" rel="nofollow">https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)</a>
<a href="https://docs.python.org/2/library/sets.html#sets.Set" rel="nofollow">https://docs.python.org/2/library/sets.html#sets.Set</a></p>
| 1 | 2016-07-25T08:47:22Z | 38,563,651 | <p>If you want a one-liner, you could use <code>or</code> to add the element only if it is not present, and <code>not</code> to inverse the returned value and at the same time coerce to <code>bool</code>:</p>
<pre><code>>>> s = set()
>>> not(42 in s or s.add(42))
True
>>> not(42 in s or s.add(42))
False
</code></pre>
<p>However, since that one-liner might not very easy to grasp, and you have to write the value to be inserted twice, you should probably make it a function, and then it does not matter much how many lines it uses.</p>
<pre><code>def in_or_add(s, x):
return not(x in s or s.add(x))
</code></pre>
| 3 | 2016-07-25T09:06:16Z | [
"java",
"python",
"set"
] |
Python list notation, Numpy array notation: predictions[predictions < 1e-10] = 1e-10 | 38,563,377 | <p>I am trying to find out operation applied on list. I have list/array name predictions and and executing following set of instruction.</p>
<pre><code>predictions[predictions < 1e-10] = 1e-10
</code></pre>
<p>This code snippet is from a Udacity Machine Learning assignment that uses Numpy. </p>
<p>It was used in the following manner: </p>
<pre><code>def logprob(predictions, labels):
"""Log-probability of the true labels in a predicted batch."""
predictions[predictions < 1e-10] = 1e-10
return np.sum(np.multiply(labels, -np.log(predictions))) / labels.shape[0]
</code></pre>
<p>As pointed out by @MosesKoledoye and various others, it is actually a Numpy array. (Numpy is a Python library)</p>
<p>What does this line do?</p>
| 5 | 2016-07-25T08:53:40Z | 38,563,484 | <p>All elements of the array, for which the condition (element < 1e-10) is true, are set to 1e-10.
Practically you are setting a minimum value.</p>
| 1 | 2016-07-25T08:58:39Z | [
"python",
"python-3.x",
"numpy"
] |
Python list notation, Numpy array notation: predictions[predictions < 1e-10] = 1e-10 | 38,563,377 | <p>I am trying to find out operation applied on list. I have list/array name predictions and and executing following set of instruction.</p>
<pre><code>predictions[predictions < 1e-10] = 1e-10
</code></pre>
<p>This code snippet is from a Udacity Machine Learning assignment that uses Numpy. </p>
<p>It was used in the following manner: </p>
<pre><code>def logprob(predictions, labels):
"""Log-probability of the true labels in a predicted batch."""
predictions[predictions < 1e-10] = 1e-10
return np.sum(np.multiply(labels, -np.log(predictions))) / labels.shape[0]
</code></pre>
<p>As pointed out by @MosesKoledoye and various others, it is actually a Numpy array. (Numpy is a Python library)</p>
<p>What does this line do?</p>
| 5 | 2016-07-25T08:53:40Z | 38,563,615 | <p>As pointed out by @MosesKoledoye, <code>predictions</code> is most likely a <code>numpy</code> array. </p>
<p>A boolean array would then be generated using <code>predictions < 1e-10</code>. At all indices where the boolean array set by the condition is <code>True</code>, the value will be changed to <code>1e-10</code>, ie. 10<sup>-10</sup>.</p>
<p>Example:</p>
<pre><code> >>> a = np.array([1,2,3,4,5]) #define array
>>> a < 3 #define boolean array through condition
array([ True, True, False, False, False], dtype=bool)
>>> a[a<3] #select elements using boolean array
array([1, 2])
>>> a[a<3] = -1 #change value of elements which fit condition
>>> a
array([-1, -1, 3, 4, 5])
</code></pre>
<p>The reason this might be done in the code could be to prevent division by zero or to prevent negative numbers messing up things by instead inserting a very small number. </p>
| 4 | 2016-07-25T09:04:56Z | [
"python",
"python-3.x",
"numpy"
] |
OpenCV + Python - NameError: name 'imSize' is not defined | 38,563,440 | <p>I am using <code>OpenCV</code> for image processing. In which, I am getting these errors please suggest what to do, below is my code:</p>
<pre><code>import dicom
import Image
import ImageOps
meta=dicom.read_file("E:\A_SHIVA\ANANADAN\IM_0.dcm")
imHeight=meta.Rows
imWidth=meta.Columns
imSize=(imWidth,imHeight)
TT=Image.frombuffer("L",imSize,meta.PixelData,"raw","L",0,1)
TT.save("testOUTPUT.tiff","TIFF",compression="none")
</code></pre>
<p>The error is below:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\sairamsystem\AppData\Local\Enthought\Canopy\User\lib\site-packages\IPython\core\interactiveshell.py", line 3066, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-8-640c37dc4648>", line 1, in <module>
TT=Image.frombuffer('L',imSize,meta.PixelData,"raw","L",0,1)
NameError: name 'imSize' is not defined
</code></pre>
| -1 | 2016-07-25T08:56:52Z | 38,566,188 | <p>The code is fine. It worked for me. The name error exception happened because it could not find imSize variable, which means it never got made. This can only happen when you haven't read the Dicom file properly, so try changing the path and printing the variable 'meta' to see if it has any value. After reading the file also print and check if meta.Rows and meta.Columns are having the correct values or not.</p>
| 0 | 2016-07-25T11:10:15Z | [
"python",
"opencv"
] |
Default python unittests returns false positives | 38,563,477 | <p>I have a python 2.7 project in visual studio using the python tools plugin.</p>
<p>I have created a basic test generated by the Visual studio template,</p>
<pre><code>import unittest
class Test_test1(unittest.TestCase):
def test_A(self):
self.fail("Not implemented")
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>The issue I am getting is that if i run the tests through test explorer they pass even though they include the self.fail.</p>
<p>If I debug the tests they will fail without hitting a break on any line of the file.</p>
<p>Has anyone had this issue before or know what could be causing this issue?</p>
| 0 | 2016-07-25T08:58:24Z | 38,568,990 | <p>I have solved this issue now, the only solution I could find was to uninstall then reinstall the python tools for visual studio.</p>
| 0 | 2016-07-25T13:24:21Z | [
"python",
"visual-studio",
"python-2.7",
"python-unittest",
"test-explorer"
] |
SVN/ PySVN: Get path to last changed files | 38,563,570 | <p>TL;DR Having an url to a SVN repo, how can I substract all the paths to the files that have been changed since a given revision number?</p>
<p>Long Story: I have a script that downloads some files from a SVN repo. It does so every 'n' hours.
But if I only changed one file, I do not need to re-download everything again, just that file.
I've tried to check every file with PySVN to see if the revision number has changed, but it takes too long (for a folder with 6 files it takes ~20 seconds).
Is there any way I can improve this?</p>
<p>I am working in Python with PySVN. I've seen that pysvn.Client.log has 'changed_paths' attribute, but it seems that I do not know how to handle it :\
This program runs on both Linux and windows, so the solution must be cross-platform (if possible)</p>
| 0 | 2016-07-25T09:02:43Z | 38,568,744 | <p>The summary makes me think that your are trying to re-invent a bicycle. Just checkout and update a working copy instead of exporting the data. That's the task of working copy and the update command.</p>
<p>BTW, I'd better use the <a href="http://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/swig/python/" rel="nofollow">official SWIG Python bindings</a> instead of PySVN.</p>
| 0 | 2016-07-25T13:12:29Z | [
"python",
"svn",
"pysvn"
] |
SVN/ PySVN: Get path to last changed files | 38,563,570 | <p>TL;DR Having an url to a SVN repo, how can I substract all the paths to the files that have been changed since a given revision number?</p>
<p>Long Story: I have a script that downloads some files from a SVN repo. It does so every 'n' hours.
But if I only changed one file, I do not need to re-download everything again, just that file.
I've tried to check every file with PySVN to see if the revision number has changed, but it takes too long (for a folder with 6 files it takes ~20 seconds).
Is there any way I can improve this?</p>
<p>I am working in Python with PySVN. I've seen that pysvn.Client.log has 'changed_paths' attribute, but it seems that I do not know how to handle it :\
This program runs on both Linux and windows, so the solution must be cross-platform (if possible)</p>
| 0 | 2016-07-25T09:02:43Z | 38,973,462 | <p>use pysvn.Client().log() to find all the changes. For example:</p>
<pre><code>all_logs = pysvn.Client().log( path,
revision_start=pysvn.Revision( opt_revision_kind.head ),
revision_end=pysvn.Revision( opt_revision_kind.number, last_revision ),
discover_changed_paths=True )
</code></pre>
<p>This will always return atleast one log for the last_revision. You can either just ignore that or use last_revision+1 and catch the error from svn about missing revision.</p>
<p>pysvn.Client().update() will figure of the smartest way to get changes into your working copy.</p>
<p>Remember that you can checkout only a part of the whole repo by a combination of selecting which folder to start with and then using the depth feature to only get the folder you need. For example:</p>
<pre><code>pysvn.Client().checkout( URL, path, depth=pysvn.depth.files )
</code></pre>
<p>Then you only need to use update() to keep the files updated.</p>
<p>Barry Scott author of pysvn.</p>
| 1 | 2016-08-16T11:14:51Z | [
"python",
"svn",
"pysvn"
] |
How to link Spark output to Logstash input | 38,563,851 | <p>I have a Spark Streaming job outputting some logs which are currently stored in HDFS, and I want to process them with logstash. Unfortunately it seems that although there is a plugin to write in hdfs for logstash, it is imposible to actually <strong>read</strong> from hdfs with it.</p>
<p>I have search a solution to link the two parts but in so far as in Spark streaming for python api, the only way to store something is to write it in hdfs as a text file, so I have to read from hdfs !
I cannot save them locally because Spark runs on a cluster, and I don't want to fetch all the data from each node.</p>
<p>Currently I run an extremely dirty script that copies the content the hdfs directory localy each 2 seconds. But this solution is clearly not satisfying.</p>
<p>Does anybody know a software that could help me to send the output of Spark to Logstash ?</p>
<p>Thanks in advance !</p>
<p><strong>EDIT :</strong> I use Python & Spark 1.6.0</p>
| 0 | 2016-07-25T09:14:44Z | 38,568,981 | <p>This seems like a perfect job to use <a href="http://kafka.apache.org/" rel="nofollow">Kafka</a> for. In your Spark Streaming job, write to Kafka, then consume the record from Logstash. </p>
<pre><code>stream.foreachRDD { rdd =>
rdd.foreachPartition { partition =>
val producer = createKafkaProducer()
partition.foreach { message =>
val record = ... // convert message to record
producer.send(record)
}
producer.close()
}
}
</code></pre>
| 0 | 2016-07-25T13:24:02Z | [
"python",
"apache-spark",
"hdfs",
"logstash",
"spark-streaming"
] |
The value on plot is not updated | 38,563,896 | <p>The value on the plot will be not updated. In my own class, I have one integrated from our community friends.The Plot won't show generated values!How could I turn on autoscale ?Further, I would like that x-axis to be moved during the program execute. For example, it shows always a last 10 seconds.</p>
<pre><code>import Tkinter,time
root = Tkinter.Tk
class InterfaceApp(root):
def __init__ (self, parent):
root.__init__(self,parent)
self.parent = parent
self.initialize()
self.on_stop()
def initialize(self):
self.min_x = 0
self.max_x = 10
self.xdata = []
self.ydata = []
self.on_launch()
# Frame and LabelFrame create
frInst = Tkinter.Frame(bg='', colormap='new')
frBut = Tkinter.Frame(bg='', colormap='new')
grInst = Tkinter.LabelFrame(frInst, text='Choose an Instruments', padx=5, pady=5)
grSet = Tkinter.LabelFrame(frInst, text='Settings', padx=5, pady=7)
# Create Settings and Buttons
self.but_start = Tkinter.Button(frBut, text='Start', command=lambda: self.on_start(), width=10)
self.but_stop = Tkinter.Button(frBut, text='Stop', command=lambda: self.on_stop(), width=10)
self.but_quit = Tkinter.Button(frBut, text='Quit', command=lambda: self.on_quit(), width=10)
# Grid
frInst.grid(row=0)
frBut.grid(row=3)
grInst.grid(row=0)
grSet.grid(row=0, column=1)
# Power Supply Grid
self.but_start.grid(row=2, column=1, sticky='W')
self.but_stop.grid(row=2, column=2, sticky='W')
self.but_quit.grid(row=2, column=3, sticky='W')
# Function
def on_quit(self):
self.W_kSMU("output off")
self.quit()
self.destroy()
def on_start(self):
self.running = True
self.but_start.configure(state='disabled')
self.but_stop.configure(state='normal')
self.Run()
def Run(self):
self.timer = randint(0,100)
self.t_volt = randint(0,100)
self.xdata.append(self.timer)
self.ydata.append(self.t_volt)
self.on_running(self.xdata, self.ydata)
time.sleep(1)
self.read_ps = 3
if self.running:
self.after(5000, self.Run)
def on_launch(self):
#Set up plot
self.figure, self.ax = plt.subplots()
self.lines, = self.ax.plot([],[], 'o')
#Autoscale on unknown axis and known lims on the other
self.ax.set_autoscaley_on(True)
self.ax.set_xlim(self.min_x, self.max_x)
#Other stuff
self.ax.grid()
def on_running(self, xdata, ydata):
#Update data (with the new _and_ the old points)
self.lines.set_xdata(xdata)
self.lines.set_ydata(ydata)
#Need both of these in order to rescale
self.ax.relim()
self.ax.autoscale_view()
#We need to draw *and* flush
self.figure.canvas.draw()
self.figure.canvas.flush_events()
def on_stop(self):
self.but_start.configure(state='normal')
self.but_stop.configure(state='disabled')
self.running = False
if __name__ == "__main__":
app = InterfaceApp(None)
app.title("MPW")
app.mainloop()
</code></pre>
<p>and code from our friends: <a href="http://stackoverflow.com/a/15742183/6403009">http://stackoverflow.com/a/15742183/6403009</a></p>
| 0 | 2016-07-25T09:16:49Z | 38,564,264 | <p>I was looking at the code, is the line "plt.subplots()" correct? and there is another thing, in th following line, you write: "self.lines, =" maybe the comma should be off,can you confirm it?
Good luck!</p>
| 0 | 2016-07-25T09:36:05Z | [
"python",
"class",
"canvas",
"plot",
"tkinter"
] |
Default behavior of maplotlib imshow() | 38,563,948 | <p>In matplotlib, when using <code>imshow()</code>, the default behavior is to display the image with bilinear interpolation. </p>
<p>I know I can change this explicitly by calling <code>imshow(...,interpolation='none')</code>. But this is cumbersome for many calls to <code>imshow</code>. </p>
<p>How do I change the default behavior, to e.g, <code>interpolation='none'</code>?</p>
| 1 | 2016-07-25T09:20:02Z | 38,564,020 | <p>Found it!
Apparently, there's a dictionary controlling many aspects of matplotlib, called
<code>rcParams</code>. Straight from <a href="http://matplotlib.org/users/customizing.html#dynamic-rc-settings" rel="nofollow">the matplotlib docs</a>:</p>
<pre><code>import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'
</code></pre>
<p>In my case, I had to set:</p>
<pre><code>rcParams['image.interpolation']='none'
</code></pre>
| 1 | 2016-07-25T09:23:24Z | [
"python",
"matplotlib",
"imshow"
] |
Is it possible to display hyperlinks in a Tkinter message widget? | 38,563,981 | <p>I am creating a news feed program that uses the Feedparser module to read the Yahoo! RSS API, write key data to a text file, and then display the data organised in a Tkinter GUI.</p>
<p>I was enquiring if it is possible to have clickable hyperlinks in a text file/Tkinter message widget.</p>
<p>My current thinking is that you could write code that runs in the following fashion:</p>
<ul>
<li>If item in the text file includes 'http', make it a hyperlink.</li>
</ul>
<p>If anyone knows of a Pythonic way to achieve this, or knows if it is not in fact possible, please contribute.</p>
<p>Thank you for your time, here is my code:</p>
<pre><code>def news_feed(event):
''' This function creates a new window within the main window, passes an event(left mouse click), and creates a text heading'''
root = Toplevel(window)
# Create a text heading and define its placement within the grid
menu_heading = Label(root, text = 'News feed', font = 'bold')
menu_heading.grid(row = 0, column = 0, columnspan = 3, pady = 4)
# Create a variable of the selected radio button
button_choice = IntVar()
def selection():
''' This function gets the activated radio button and calls its corresponding function.'''
# Get the value of the activated radio button, and call its corresponding function
news_choice = button_choice.get()
# If the user's choice is industry news, ask them which feed they would like (E.g. Stock market),
if news_choice == 0:
# grab the corresponding url segment to the user's feed choice from the dictionary,
news_choice_url = news_areas[news_feed]
# set the url variable using by inserting this segment into the API url,
rss_url = feedparser.parse('https://au.finance.yahoo.com/news/' + news_choice_url + '/?format=rss')
# and call the feed parsing function.
parse_feed()
# If the user's choice is the second button, call the company news function
elif news_choice == 1:
company_news()
def read_news_file(news_feed_message):
'''This function opens the companyNews text file and reads its contents, line by line'''
with open('C:\\Users\\nicks_000\\PycharmProjects\\untitled\\SAT\\GUI\\Text Files\\companyNews.txt', mode='r') as inFile:
news_data_read = inFile.read()
print('\n')
news_feed_message.configure(text = news_data_read)
def parse_feed(news_feed_message, rss_url):
''' This function parses the Yahoo! RSS API for data of the latest five articles, and writes it to the company news text file'''
# Define the RSS feed to parse from, as the url passed in of the company the user chose
feed = feedparser.parse(rss_url)
try:
# Define the file to write the news data to the company news text file
with open('C:\\Users\\nicks_000\\PycharmProjects\\untitled\\SAT\\GUI\\Text Files\\companyNews.txt', mode='w') as outFile:
# Create a list to store the news data parsed from the Yahoo! RSS
news_data_write = []
# Initialise a count
count = 0
# For the number of articles to append to the file, append the article's title, link, and published date to the news_elements list
for count in range(10):
news_data_write.append(feed['entries'][count].title)
news_data_write.append(feed['entries'][count].published)
article_link = (feed['entries'][count].link)
article_link = article_link.split('*')[1]
news_data_write.append(article_link)
# Add one to the count, so that the next article is parsed
count+=1
# For each item in the news_elements list, convert it to a string and write it to the company news text file
for item in news_data_write:
item = str(item)
outFile.write(item+'\n')
# For each article, write a new line to the company news text file, so that each article's data is on its own line
outFile.write('\n')
# Clear the news_elements list so that data is not written to the file more than once
del(news_data_write[:])
finally:
outFile.close()
read_news_file(news_feed_message)
def industry_news():
''' This function creates a new window within the main window, and displays industry news'''
industry_window = Toplevel(root)
Label(industry_window, text = 'Industry news').grid()
def company_news():
''' This function creates a new window within the main window, and displays company news'''
company_window = Toplevel(root)
company_label = Label(company_window, text = 'Company news')
company_label.grid(row = 0, column = 0, columnspan = 6)
def company_news_handling(company_ticker):
''' This function gets the input from the entry widget (stock ticker) to be graphed.'''
# set the url variable by inserting the stock ticker into the API url,
rss_url = ('http://finance.yahoo.com/rss/headline?s={0}'.format(company_ticker))
# and call the feed parsing function.
parse_feed(news_feed_message, rss_url)
# Create the entry widget where the user enters a stock ticker, and define its location within the grid
company_ticker_entry = Entry(company_window)
company_ticker_entry.grid(row = 1, column = 0, columnspan = 6, padx = 10)
def entry_handling():
'''This function validates the input of the entry box, and if there is nothing entered, an error is outputted until a value is'''
# Create a variable that equals the input from the entry widget
company_ticker = company_ticker_entry.get()
# Convert the input into a string
company_ticker = str(company_ticker)
if company_ticker == '':
news_feed_message.configure(text = 'Please input a stock ticker in the entry box.')
else:
company_news_handling(company_ticker)
# Create the button that the user presses when they wish to graph the data of the stock ticker they inputted in the entry widget
graph_button = Button(company_window, text = 'SHOW', command = entry_handling, width = 10).grid(row = 2, column = 0, columnspan = 6)
news_feed_message = Message(company_window, text='', width=500, borderwidth=5, justify=LEFT, relief=RAISED)
news_feed_message.grid(row=3, column=0, columnspan=6)
</code></pre>
| 0 | 2016-07-25T09:21:29Z | 38,564,117 | <p>Most uses of hyperlinks in a tkinter application i have seen involved using the webbrowser and attaching events to your tkinter object to trigger callbacks, but there may be simpler ways, but heres what i mean :</p>
<pre><code>from tkinter import *
import webbrowser
def callback(event):
webbrowser.open_new(r"http://www.google.com")
root = Tk()
link = Label(root, text="Google Hyperlink", fg="blue", cursor="hand2")
link.pack()
link.bind("<Button-1>", callback)
root.mainloop()
</code></pre>
<p>From this <a href="http://stackoverflow.com/questions/23482748/how-to-create-a-hyperlink-with-a-label-in-tkinter">source</a></p>
<p>You could do as you said and read from a text file, and if the line contains "http" create a new label, and event, attaching the hyper link from the file to the event.</p>
<pre><code>import re
with open(fname) as f:
content = f.readlines()
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', content)
</code></pre>
<p>Access the url's after this and generate your label's or whatever widget you attach the url's too and you can then have all of them open the web page when clicked.</p>
<p>Hope this helps in some way, let me know if you need more help :)</p>
| 1 | 2016-07-25T09:28:31Z | [
"python",
"hyperlink",
"tkinter",
"rss",
"feedparser"
] |
Is it possible to display hyperlinks in a Tkinter message widget? | 38,563,981 | <p>I am creating a news feed program that uses the Feedparser module to read the Yahoo! RSS API, write key data to a text file, and then display the data organised in a Tkinter GUI.</p>
<p>I was enquiring if it is possible to have clickable hyperlinks in a text file/Tkinter message widget.</p>
<p>My current thinking is that you could write code that runs in the following fashion:</p>
<ul>
<li>If item in the text file includes 'http', make it a hyperlink.</li>
</ul>
<p>If anyone knows of a Pythonic way to achieve this, or knows if it is not in fact possible, please contribute.</p>
<p>Thank you for your time, here is my code:</p>
<pre><code>def news_feed(event):
''' This function creates a new window within the main window, passes an event(left mouse click), and creates a text heading'''
root = Toplevel(window)
# Create a text heading and define its placement within the grid
menu_heading = Label(root, text = 'News feed', font = 'bold')
menu_heading.grid(row = 0, column = 0, columnspan = 3, pady = 4)
# Create a variable of the selected radio button
button_choice = IntVar()
def selection():
''' This function gets the activated radio button and calls its corresponding function.'''
# Get the value of the activated radio button, and call its corresponding function
news_choice = button_choice.get()
# If the user's choice is industry news, ask them which feed they would like (E.g. Stock market),
if news_choice == 0:
# grab the corresponding url segment to the user's feed choice from the dictionary,
news_choice_url = news_areas[news_feed]
# set the url variable using by inserting this segment into the API url,
rss_url = feedparser.parse('https://au.finance.yahoo.com/news/' + news_choice_url + '/?format=rss')
# and call the feed parsing function.
parse_feed()
# If the user's choice is the second button, call the company news function
elif news_choice == 1:
company_news()
def read_news_file(news_feed_message):
'''This function opens the companyNews text file and reads its contents, line by line'''
with open('C:\\Users\\nicks_000\\PycharmProjects\\untitled\\SAT\\GUI\\Text Files\\companyNews.txt', mode='r') as inFile:
news_data_read = inFile.read()
print('\n')
news_feed_message.configure(text = news_data_read)
def parse_feed(news_feed_message, rss_url):
''' This function parses the Yahoo! RSS API for data of the latest five articles, and writes it to the company news text file'''
# Define the RSS feed to parse from, as the url passed in of the company the user chose
feed = feedparser.parse(rss_url)
try:
# Define the file to write the news data to the company news text file
with open('C:\\Users\\nicks_000\\PycharmProjects\\untitled\\SAT\\GUI\\Text Files\\companyNews.txt', mode='w') as outFile:
# Create a list to store the news data parsed from the Yahoo! RSS
news_data_write = []
# Initialise a count
count = 0
# For the number of articles to append to the file, append the article's title, link, and published date to the news_elements list
for count in range(10):
news_data_write.append(feed['entries'][count].title)
news_data_write.append(feed['entries'][count].published)
article_link = (feed['entries'][count].link)
article_link = article_link.split('*')[1]
news_data_write.append(article_link)
# Add one to the count, so that the next article is parsed
count+=1
# For each item in the news_elements list, convert it to a string and write it to the company news text file
for item in news_data_write:
item = str(item)
outFile.write(item+'\n')
# For each article, write a new line to the company news text file, so that each article's data is on its own line
outFile.write('\n')
# Clear the news_elements list so that data is not written to the file more than once
del(news_data_write[:])
finally:
outFile.close()
read_news_file(news_feed_message)
def industry_news():
''' This function creates a new window within the main window, and displays industry news'''
industry_window = Toplevel(root)
Label(industry_window, text = 'Industry news').grid()
def company_news():
''' This function creates a new window within the main window, and displays company news'''
company_window = Toplevel(root)
company_label = Label(company_window, text = 'Company news')
company_label.grid(row = 0, column = 0, columnspan = 6)
def company_news_handling(company_ticker):
''' This function gets the input from the entry widget (stock ticker) to be graphed.'''
# set the url variable by inserting the stock ticker into the API url,
rss_url = ('http://finance.yahoo.com/rss/headline?s={0}'.format(company_ticker))
# and call the feed parsing function.
parse_feed(news_feed_message, rss_url)
# Create the entry widget where the user enters a stock ticker, and define its location within the grid
company_ticker_entry = Entry(company_window)
company_ticker_entry.grid(row = 1, column = 0, columnspan = 6, padx = 10)
def entry_handling():
'''This function validates the input of the entry box, and if there is nothing entered, an error is outputted until a value is'''
# Create a variable that equals the input from the entry widget
company_ticker = company_ticker_entry.get()
# Convert the input into a string
company_ticker = str(company_ticker)
if company_ticker == '':
news_feed_message.configure(text = 'Please input a stock ticker in the entry box.')
else:
company_news_handling(company_ticker)
# Create the button that the user presses when they wish to graph the data of the stock ticker they inputted in the entry widget
graph_button = Button(company_window, text = 'SHOW', command = entry_handling, width = 10).grid(row = 2, column = 0, columnspan = 6)
news_feed_message = Message(company_window, text='', width=500, borderwidth=5, justify=LEFT, relief=RAISED)
news_feed_message.grid(row=3, column=0, columnspan=6)
</code></pre>
| 0 | 2016-07-25T09:21:29Z | 38,564,229 | <p><a href="http://i.stack.imgur.com/gbF8d.png" rel="nofollow"><img src="http://i.stack.imgur.com/gbF8d.png" alt="The output"></a></p>
<p>I think it is easy to create hyperlink in tkinter using following link and its easy for modifying as per your requirement </p>
<p><a href="http://effbot.org/zone/tkinter-text-hyperlink.htm" rel="nofollow">Updated Hyperlink in tkinter</a></p>
<p>hope this works for you.</p>
<p>regards Midhun</p>
| 0 | 2016-07-25T09:34:18Z | [
"python",
"hyperlink",
"tkinter",
"rss",
"feedparser"
] |
Using Pandas to Manipulate Multiple Columns | 38,563,999 | <p>I have a 30+ million row data set that I need to apply a whole host of data transformation rules to. For this task, I am trying to explore Pandas as a possible solution because my current solution isn't very fast.</p>
<p>Currently, I am performing a row by row manipulation of the data set, and then exporting it to a new table (CSV file) on disk.</p>
<p>There are 5 functions users can perform on the data within a given column:</p>
<ol>
<li>remove white space</li>
<li>Capitalize all text</li>
<li>format date</li>
<li>replace letter/number</li>
<li>replace word</li>
</ol>
<p>My first thought was to use the dataframe's apply or applmap, but this can only be used on a single column. </p>
<p>Is there a way to use apply or applymap to many columns instead of just one?
Is there a better workflow I should consider since I could be doing manipulations to 1:n columns in my dataset, where the maximum number of columns is currently around 30. </p>
<p>Thank you</p>
| 1 | 2016-07-25T09:22:21Z | 38,564,067 | <p>You can use list comprehension with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> if need apply some function working only with <code>Series</code>:</p>
<pre><code>import pandas as pd
data = pd.DataFrame({'A':[' ff ','2','3'],
'B':[' 77','s gg','d'],
'C':['s',' 44','f']})
print (data)
A B C
0 ff 77 s
1 2 s gg 44
2 3 d f
print (pd.concat([data[col].str.strip().str.capitalize() for col in data], axis=1))
A B C
0 Ff 77 S
1 2 S gg 44
2 3 D F
</code></pre>
| 2 | 2016-07-25T09:25:52Z | [
"python",
"pandas"
] |
python VTK context menu not at mouse position | 38,564,063 | <p>I am having problems with the context menu position in VTK with PyQt. The main GUI window has set the VTK widget as central widget:</p>
<pre><code>from vtk_widget.vtk_widget import VTKWidget
class DySMainWindow(QtGui.QMainWindow):
def __init__(self):
self.vtk_widget = VTKWidget(self)
self.setCentralWidget(self.vtk_widget)
</code></pre>
<p>and the <code>VTK widget</code> is:</p>
<pre><code>import vtk
from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
from PyQt4 import QtGui, QtCore, Qt
class VTKWidget(QVTKRenderWindowInteractor):
def __init__(self, MBD_system=None, parent=None):
super(VTKWidget, self).__init__(parent)
# this should show context menu
self.AddObserver("RightButtonPressEvent", self.contextMenu)
self.renderer = vtk.vtkRenderer()
self.GetRenderWindow().AddRenderer(self.renderer)
self.interactor = self.GetRenderWindow().GetInteractor()
self.interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
# camera object
self.camera = self.renderer.GetActiveCamera()
if self.projection == 'perspective':
self.camera.ParallelProjectionOff()
else:
self.camera.ParallelProjectionOn()
self.renderer.SetActiveCamera(self.camera)
self.renderer.ResetCamera()
self.renderer.SetBackground(0, 0, 0)
self.interactor.Initialize()
def contextMenu(self, caller, event):
pos = self.interactor.GetEventPosition()
menu = QtGui.QMenu(parent=self)
menu.addAction(self.tr("Edit object"))
menu.exec_(self.mapToGlobal(QtCore.QPoint(pos[0], pos[1])))
</code></pre>
<p>Any help solving this would be appreciated.</p>
| 0 | 2016-07-25T09:25:48Z | 38,586,895 | <p>The contextmeny event method takes a point as an input. If we assume that your menu is called qMenuVTK and you have a parent window, the following should work:</p>
<p>In your rightbuttonpressevent add the following:</p>
<pre class="lang-py prettyprint-override"><code>self.parent.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.parent.customContextMenuRequested.connect(self.onContextMenu)
</code></pre>
<p>And the method event will look like:</p>
<pre class="lang-py prettyprint-override"><code>def onContextMenu(self, point):
self.qMenuVTK.exec_(self.parent.mapToGlobal(point))
</code></pre>
| 1 | 2016-07-26T10:06:26Z | [
"python",
"pyqt",
"vtk",
"qvtkwidget"
] |
how to calculate short path geodesic distance of adjacency matrix csv [python]? | 38,564,308 | <p>i have an adjacency matrix of graph </p>
<p><a href="http://i.stack.imgur.com/IBom1.png" rel="nofollow">graph</a></p>
<blockquote>
<p>n 1 2 3 4 5 6 7 8 9</p>
<p>1 0 1 1 1 0 0 0 0 0</p>
<p>2 1 0 1 0 0 0 0 0 0</p>
<p>3 1 1 0 1 0 0 0 0 0</p>
<p>4 1 0 1 0 1 1 0 0 0</p>
<p>5 0 0 0 1 0 1 1 1 0</p>
<p>6 0 0 0 1 1 0 1 1 0</p>
<p>7 0 0 0 0 1 1 0 1 1</p>
<p>8 0 0 0 0 1 1 1 0 0</p>
<p>9 0 0 0 0 0 0 1 0 0</p>
</blockquote>
<p>how to convert it to geodesic discance matrix using python?</p>
<p>my goal is to make it like this :</p>
<blockquote>
<p>n 1 2 3 4 5 6 7 8 9</p>
<p>1 0 1 1 1 2 2 3 3 4</p>
<p>2 1 0 1 2 3 3 4 4 5</p>
<p>3 1 1 0 1 2 2 3 3 4</p>
<p>4 1 2 1 0 1 1 2 2 3</p>
<p>5 2 3 2 1 0 1 1 1 2</p>
<p>6 2 3 2 1 1 0 1 1 2</p>
<p>7 3 4 3 2 1 1 0 1 1</p>
<p>8 3 4 3 2 1 1 1 0 2</p>
<p>9 4 5 4 3 2 2 1 2 0</p>
</blockquote>
<p>i've tried some code in networkx but it only can calculate at one source and one destination of (n) not the whole matrix. I really need your help.
Thank you</p>
| 0 | 2016-07-25T09:38:33Z | 38,823,024 | <p><code>networkx</code> can calculate the whole matrix. One just need not to give source or destination to the <code>nx.shortest_path</code> function (see <a href="https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html" rel="nofollow">https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html</a> - last example). Here's my solution:</p>
<pre><code>import pprint
import networkx as nx
import pandas as pd
import numpy as np
mat = pd.read_csv('adjacency.csv', index_col=0, delim_whitespace=True).values
G = nx.from_numpy_matrix(mat)
p = nx.shortest_path(G)
shortest_path_mat = np.zeros(mat.shape)
for i in range(mat.shape[0]):
shortest_path_mat[i, :] = np.array([len(x) for x in p[i].values()])
pprint.pprint(shortest_path_mat-1)
</code></pre>
<p>adjacency.csv</p>
<pre><code>n 1 2 3 4 5 6 7 8 9
1 0 1 1 1 0 0 0 0 0
2 1 0 1 0 0 0 0 0 0
3 1 1 0 1 0 0 0 0 0
4 1 0 1 0 1 1 0 0 0
5 0 0 0 1 0 1 1 1 0
6 0 0 0 1 1 0 1 1 0
7 0 0 0 0 1 1 0 1 1
8 0 0 0 0 1 1 1 0 0
9 0 0 0 0 0 0 1 0 0
</code></pre>
| 0 | 2016-08-08T07:01:54Z | [
"python",
"csv",
"matrix",
"shortest-path",
"adjacency-matrix"
] |
How to replace invalid unicode characters in a string in Python? | 38,564,456 | <p>As far as I know it is the concept of python to have only valid characters in a string, but in my case the OS will deliver strings with invalid encodings in path names I have to deal with. So I end up with strings that contain characters that are non-unicode.</p>
<p>In order to correct these problems I need to display these strings somehow. Unfortunately I can not print them because they contain non-unicode characters. Is there an elegant way to replace these characters somehow to at least get some idea of the content of the string?</p>
<p>My idea would be to process these strings character by character and check if the character stored is actually valid unicode. In case of an invalid character I would like to use a certain unicode symbol. But how can I do this? Using <code>codecs</code> seems not to be suitable for that purpose: I already have a string, returned by the operating system, and not a byte array. Converting a string to byte array seems to involve decoding which will fail in my case of course. So it seems that I'm stuck.</p>
<p>Do you have an tips for me how to be able to create such a replacement string?</p>
| 0 | 2016-07-25T09:45:42Z | 38,564,967 | <p>Thanks to you for your comments. This way I was able to implement a better solution:</p>
<pre><code> try:
s2 = codecs.encode(s, "utf-8")
return (True, s, None)
except Exception as e:
ret = codecs.decode(codecs.encode(s, "utf-8", "replace"), "utf-8")
return (False, ret, e)
</code></pre>
<p>Please share any improvements on that solution. Thank you!</p>
| 0 | 2016-07-25T10:11:22Z | [
"python",
"string",
"unicode",
"character-encoding"
] |
How to replace invalid unicode characters in a string in Python? | 38,564,456 | <p>As far as I know it is the concept of python to have only valid characters in a string, but in my case the OS will deliver strings with invalid encodings in path names I have to deal with. So I end up with strings that contain characters that are non-unicode.</p>
<p>In order to correct these problems I need to display these strings somehow. Unfortunately I can not print them because they contain non-unicode characters. Is there an elegant way to replace these characters somehow to at least get some idea of the content of the string?</p>
<p>My idea would be to process these strings character by character and check if the character stored is actually valid unicode. In case of an invalid character I would like to use a certain unicode symbol. But how can I do this? Using <code>codecs</code> seems not to be suitable for that purpose: I already have a string, returned by the operating system, and not a byte array. Converting a string to byte array seems to involve decoding which will fail in my case of course. So it seems that I'm stuck.</p>
<p>Do you have an tips for me how to be able to create such a replacement string?</p>
| 0 | 2016-07-25T09:45:42Z | 38,564,992 | <p>You have not given any example. Therefore I have considered one example to answer your question.</p>
<p>x='This is a cat which looks good ðŸËÅ '
print x
x.replace('ðŸËÅ ','')</p>
<p>output is:
This is a cat which looks good ðŸËÅ
'This is a cat which looks good '</p>
| 0 | 2016-07-25T10:12:04Z | [
"python",
"string",
"unicode",
"character-encoding"
] |
How to replace invalid unicode characters in a string in Python? | 38,564,456 | <p>As far as I know it is the concept of python to have only valid characters in a string, but in my case the OS will deliver strings with invalid encodings in path names I have to deal with. So I end up with strings that contain characters that are non-unicode.</p>
<p>In order to correct these problems I need to display these strings somehow. Unfortunately I can not print them because they contain non-unicode characters. Is there an elegant way to replace these characters somehow to at least get some idea of the content of the string?</p>
<p>My idea would be to process these strings character by character and check if the character stored is actually valid unicode. In case of an invalid character I would like to use a certain unicode symbol. But how can I do this? Using <code>codecs</code> seems not to be suitable for that purpose: I already have a string, returned by the operating system, and not a byte array. Converting a string to byte array seems to involve decoding which will fail in my case of course. So it seems that I'm stuck.</p>
<p>Do you have an tips for me how to be able to create such a replacement string?</p>
| 0 | 2016-07-25T09:45:42Z | 38,565,489 | <p>If you have a <em>bytestring</em> (undecoded data), use the <code>'replace'</code> error handler. For example, if your data is (mostly) UTF-8 encoded, then you could use:</p>
<pre><code>decoded_unicode = bytestring.decode('utf-8', 'replace')
</code></pre>
<p>and <a href="https://codepoints.net/U+FFFD" rel="nofollow">U+FFFD � REPLACEMENT CHARACTER</a> characters will be inserted for any bytes that can't be decoded.</p>
<p>If you wanted to use a different replacement character, it is easy enough to replace these afterwards:</p>
<pre><code>decoded_unicode = decoded_unicode.replace(u'\ufffd', '#')
</code></pre>
<p>Demo:</p>
<pre><code>>>> bytestring = 'F\xc3\xb8\xc3\xb6\xbbB\xc3\xa5r'
>>> bytestring.decode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mjpieters/Development/venvs/stackoverflow-2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xbb in position 5: invalid start byte
>>> bytestring.decode('utf8', 'replace')
u'F\xf8\xf6\ufffdB\xe5r'
>>> print bytestring.decode('utf8', 'replace')
Føö�Bår
</code></pre>
| 0 | 2016-07-25T10:36:12Z | [
"python",
"string",
"unicode",
"character-encoding"
] |
Strange error in a PyCOMPSs application: Script without last "y" not found | 38,564,536 | <p>I am trying to run one of the example pyCOMPSs application with version 1.4 and I am getting the following error, which says that the python script without the final "y" can not be found. Do you have any idea what could be the error?</p>
<pre><code>xxx:~/xxx_xx/python/increment> runcompss --lang=python increment.py 3 1 2 3
Using default location for project file:
/opt/COMPSs/Runtime/scripts/user/../../configuration/xml/projects/project.xml
Using default location for resources file: /opt/COMPSs/Runtime/scripts/user/../../configuration/xml/resources/resources.xml
----------------- Executing increment.py --------------------------
WARNING: IT Properties file is null. Setting default values
[(0) API] - Deploying COMPSs Runtime v1.4 (build 20160725-0937.r2315)
[(2) API] - Starting COMPSs Runtime v1.4 (build 20160725-0937.r2315)
Traceback (most recent call last):
File "/opt/COMPSs/Runtime/scripts/user/../../../Bindings/python/pycompss/runtime/launch.py", line 85, in <module>
execfile(app_path) # MAIN EXECUTION
File "increment.py", line 92, in <module>
@task(filePath = FILE_INOUT)
File "/opt/COMPSs/Bindings/python/pycompss/api/task.py", line 117, in __call__
if "__init__.py" in os.listdir(path):
OSError: [Errno 2] No such file or directory: 'increment.p'
Error running application
</code></pre>
| 4 | 2016-07-25T09:49:41Z | 38,564,625 | <p>You have miss the ./ or the absolute pathe before the python script</p>
<pre><code>runcompss --lang=python ./increment.py 3 1 2 3
</code></pre>
<p>or </p>
<pre><code>runcompss --lang=python /path/to/script/increment.py 3 1 2 3
</code></pre>
| 4 | 2016-07-25T09:54:09Z | [
"python",
"distributed-computing",
"hpc",
"compss",
"pycompss"
] |
Run c++ class from python | 38,564,620 | <p>Is there a way to <strong>run a c++ class from python without using any external libraries</strong> like Boost.Python, SWING ect? I don't want to pass any arguments to this class or call a specific method and in my c++ class I have only a void main method, I just want to run the main and that is all.</p>
<p>Or if this is not possible a saw this tutorial <a href="http://intermediate-and-advanced-software-carpentry.readthedocs.io/en/latest/c++-wrapping.html#manual-wrapping" rel="nofollow">http://intermediate-and-advanced-software-carpentry.readthedocs.io/en/latest/c++-wrapping.html#manual-wrapping</a>. But I didn't understand if I should put the hello_wrapper function in the same c++ class where I have the original hello function. And also how can I create a modulo in Python(second part in the tutorial) and where should I put this code</p>
<pre><code>DL_EXPORT(void) inithello(void)
{
Py_InitModule("hello", HelloMethods);
}
</code></pre>
<p>Thanks</p>
| -4 | 2016-07-25T09:53:54Z | 38,564,697 | <blockquote>
<p>is there a way to run a c++ class</p>
</blockquote>
<p>you don't run C++ classes. They are data types!</p>
<blockquote>
<p>Boost.Python, SWING</p>
</blockquote>
<p>It's called SWIG, not SWING :)</p>
<p>You can add your own C wrapper code that initializes a PyObject. I'd recommend reading the CPython docs and the examples in the tutorial on extending python. Since you didn't specify a version, I can't give you a discrete link.</p>
<p>Note that python is C, and C++ isn't; which means that you'll have to export several things with a C ABI, i.e. by using <code>external "C"</code> in your code. That might not be something for the uninitiated, and you should certainly evaluate whether not using external wrapper generators is really worth the trouble â especially since using e.g. SWIG properly (which is really a pain) you can get Python objects that <em>really</em> behave like python objects, e.g. you can extend them with python etc.</p>
| 1 | 2016-07-25T09:57:31Z | [
"python",
"c++"
] |
Python Argparse usage instructions | 38,564,644 | <p>I'am trying to write a function which can parse 1 or 2 ip addresses & a searchterm.</p>
<pre><code>For example: ./system.py 172.16.19.152,172.16.19.153 model\ name
Output:
Search term: model name
Server: 172.16.19.152
Results:
Processor 0:
model name : Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
Server: 172.16.19.153
Results:
Processor 0:
model name : Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
</code></pre>
<p>How can i get this usage instructions with argparse:</p>
<pre><code> usage:./system.py {IP}[,{IP}] {SEARCH\ TERM}
</code></pre>
| 1 | 2016-07-25T09:55:03Z | 38,565,171 | <p>To resume, you can use argparse as below.</p>
<pre><code>parser = argparse.ArgumentParser()
parser.add_argument('--IP', nargs=2)
parser.add_argument('--TERM', nargs=1)
</code></pre>
| 0 | 2016-07-25T10:20:38Z | [
"python",
"argparse"
] |
Python Argparse usage instructions | 38,564,644 | <p>I'am trying to write a function which can parse 1 or 2 ip addresses & a searchterm.</p>
<pre><code>For example: ./system.py 172.16.19.152,172.16.19.153 model\ name
Output:
Search term: model name
Server: 172.16.19.152
Results:
Processor 0:
model name : Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
Server: 172.16.19.153
Results:
Processor 0:
model name : Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
</code></pre>
<p>How can i get this usage instructions with argparse:</p>
<pre><code> usage:./system.py {IP}[,{IP}] {SEARCH\ TERM}
</code></pre>
| 1 | 2016-07-25T09:55:03Z | 38,565,185 | <pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('ips',metavar='IP',nargs='+')
parser.add_argument('search_term',metavar='SEARCH\\ TERM',nargs=1)
</code></pre>
<p>The <code>metavar</code> keyword will be used in the usage text for your program. The double backslash is used for escaping the single backslash character for your <code>SEARCH\ TERM</code> argument. By calling <code>parser.parse_args()</code> the returning dictionary will contain your arguments parsed which can be reached like this:</p>
<pre><code>args = parser.parse_args()
args.ips
args.search_term
</code></pre>
<p>The <code>nargs</code> keyword will tell the number of this kind of argument to be passed to your program. </p>
<p><code>+</code> means at least one, <code>1</code> means exactly one argument to be passed.</p>
| 2 | 2016-07-25T10:21:20Z | [
"python",
"argparse"
] |
wxPython layout using boxsizers | 38,564,654 | <p>I've recently started using wxPython to build a GUI and I'm trying to create the following layout:</p>
<pre><code>Button1 Button2 Button3
----------------------------------------
listbox | textctrl
</code></pre>
<p>The buttons should have a flexible width, expanding to fill the full width of the frame with a border between them (each buttons has a width (incl. border) of 1/3 frame). Their height should be set to a height in pixels.</p>
<p>The listbox should fill the frame vertically and have a set width of x pixels</p>
<p>The textctrol should be a textbox which expands to fill the width of the frame vertically as well as horizontally.</p>
<p>This is the code I have:</p>
<pre><code>mainPanel = wx.Panel(self, -1)
parentBox = wx.BoxSizer(wx.VERTICAL)
menubar = wx.MenuBar()
filem = wx.Menu()
menubar.Append(filem, '&File')
self.SetMenuBar(menubar)
navPanel = wx.Panel(mainPanel, -1, size=(1000, 80))
navBox = wx.BoxSizer(wx.HORIZONTAL)
newSection = wx.Button(navPanel, self.ID_NEW, 'New')
renSection = wx.Button(navPanel, self.ID_RENAME, 'Rename')
dltSection = wx.Button(navPanel, self.ID_DELETE, 'Delete')
navBox.Add(newSection, 1, wx.EXPAND | wx.ALL, 5)
navBox.Add(renSection, 1, wx.EXPAND | wx.ALL, 5)
navBox.Add(dltSection, 1, wx.EXPAND | wx.ALL, 5)
navPanel.SetSizer(navBox)
contentPanel = wx.Panel(mainPanel, -1, size=(1000, 600))
contentBox = wx.BoxSizer(wx.HORIZONTAL)
self.listbox = wx.ListBox(contentPanel, -1, size=(300, 700))
self.settings = wx.TextCtrl(contentPanel, -1)
contentBox.Add(self.listbox, 0)
contentBox.Add(self.settings, 1, wx.EXPAND | wx.ALL, 5)
contentPanel.SetSizer(contentBox)
parentBox.Add(navPanel, 0, wx.EXPAND | wx.ALL, 5)
parentBox.Add(contentPanel, 1, wx.EXPAND | wx.ALL, 5)
mainPanel.SetSizer(parentBox)
</code></pre>
<p>Something is going wrong since what I see is not what I expect to see, anybody who can help me out?</p>
| 0 | 2016-07-25T09:55:27Z | 38,585,615 | <p>It is working for me, I'm on win64, python 32bit 2.7.3.3, wx '2.8.12.1 (msw-unicode)'. The full working test example is:</p>
<pre><code>import wx
class testframe(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'some title')
mainPanel = wx.Panel(self, -1)
parentBox = wx.BoxSizer(wx.VERTICAL)
menubar = wx.MenuBar()
filem = wx.Menu()
menubar.Append(filem, '&File')
self.SetMenuBar(menubar)
navPanel = wx.Panel(mainPanel, -1, size=(1000, 80))
navBox = wx.BoxSizer(wx.HORIZONTAL)
newSection = wx.Button(navPanel, -1, 'New')
renSection = wx.Button(navPanel, -1, 'Rename')
dltSection = wx.Button(navPanel, -1, 'Delete')
navBox.Add(newSection, 1, wx.EXPAND | wx.ALL, 5)
navBox.Add(renSection, 1, wx.EXPAND | wx.ALL, 5)
navBox.Add(dltSection, 1, wx.EXPAND | wx.ALL, 5)
navPanel.SetSizer(navBox)
contentPanel = wx.Panel(mainPanel, -1, size=(1000, 600))
contentBox = wx.BoxSizer(wx.HORIZONTAL)
self.listbox = wx.ListBox(contentPanel, -1, size=(300, 700))
self.settings = wx.TextCtrl(contentPanel, -1)
contentBox.Add(self.listbox, 0, wx.ALL, 5)
contentBox.Add(self.settings, 1, wx.EXPAND | wx.ALL, 5)
contentPanel.SetSizer(contentBox)
parentBox.Add(navPanel, 0, wx.EXPAND | wx.ALL, 5)
parentBox.Add(contentPanel, 1, wx.EXPAND | wx.ALL, 5)
mainPanel.SetSizer(parentBox)
parentBox.Fit(self)
app = wx.PySimpleApp()
app.frame = testframe()
app.frame.Show()
app.MainLoop()
</code></pre>
<p>Notice the addition of <code>Fit()</code> of the main sizer, and also 5px border added to the listbox.</p>
| 0 | 2016-07-26T09:08:49Z | [
"python",
"python-2.7",
"wxpython"
] |
Selenium clicking on link before it's visible | 38,564,702 | <p>I'm running into a problem where Selenium is clicking on a link before it's being displayed on the screen.</p>
<p>I've tried using both:</p>
<pre><code>WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID,('menu-link-dashboard'))))
</code></pre>
<p>and</p>
<pre><code>WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID,(self.ws.cell(row=i, column=j).value))))
</code></pre>
<p>The issue I'm running into is that with both of the above, Selenium is finding the link before it's actually displayed on the screen. It then manages to click on the link, but because it hasn't been properly loaded yet, it gives an incorrect behaviour (it expands its sub menu and then collapses it).</p>
<p>Can anyone offer a solution?</p>
| 0 | 2016-07-25T09:57:52Z | 38,565,182 | <p>I managed to solve it.
The problem was caused because I was waiting for the link to be visible. I actually needed to wait for the home page to be visible (which only happened 2 seconds after the menu links were visible).</p>
<p>I changed the Webdriverwait to be performed on an object on the home page instead.</p>
| 0 | 2016-07-25T10:21:14Z | [
"python",
"selenium"
] |
Selenium with Python - Switching to main content after popup overlay | 38,564,738 | <p>After handling a pop up overlay the rest of the code no longer works.</p>
<pre><code>from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://www.vapordna.com/login.asp')
#handling popup
browser.find_element_by_css_selector("div.age-verify-button.age-modal__btn.btn.btn-primary").click()
browser.find_element_by_link_text("Yes").click()
</code></pre>
<p>If I don't close the pop up the rest of the code works, if I close the popup none of the code after that point works. </p>
<pre><code>emailElem = browser.find_element_by_name("email")
emailElem.send_keys("****@****.com")
passwordElem = browser.find_element_by_name("password")
passwordElem.send_keys("******")
passwordElem.submit()
</code></pre>
<p>I have tried adding this line but it doesn't help,</p>
<pre><code>browser.switchTo().defaultContent();
</code></pre>
<p>To my understanding the popup isn't in a new iframe or window so I'm not sure why there would be any problem with continuing to interact with the page. </p>
<p>I also tried clicking on the body before continuing</p>
<pre><code>browser.find_element_by_tag_name("body").click()
</code></pre>
| 0 | 2016-07-25T09:59:49Z | 38,564,923 | <p>After seeing your website I observe this is neither an frame nor a window, I just a form so there is <strong>no need</strong> to use here <code>browser.switchTo().defaultContent();</code> which actually using for switching from any frame to default, Actually when you are going to find this button on the opened popup which overlay all the page, It would not be full loaded on the page, so you should try using <code>WebDriverWait</code> to wait until this button visible on the page.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Firefox()
browser.get('https://www.vapordna.com/login.asp')
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.age-verify-button.age-modal__btn.btn.btn-primary"))).click()
</code></pre>
<p>Now after clicking on this agreement button you can proceed further steps for login. </p>
| 0 | 2016-07-25T10:09:15Z | [
"python",
"selenium",
"selenium-webdriver"
] |
Python 3.5 | Scraping data from website | 38,564,754 | <p>I want to scrape a specific part of the website <a href="https://www.kickstarter.com/discover/categories/technology?ref=discover_index" rel="nofollow">Kickstarter.com</a></p>
<p>I need the strings of the Project-title. The website is structured and every project has this line.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Project-title"></code></pre>
</div>
</div>
</p>
<p>My code looks like: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>#Loading Libraries
import urllib
import urllib.request
from bs4 import BeautifulSoup
#define URL for scraping
theurl = "https://www.kickstarter.com/discover/advanced?category_id=16&woe_id=23424829&sort=popularity&seed=2448324&page=1"
thepage = urllib.request.urlopen(theurl)
#Cooking the Soup
soup = BeautifulSoup(thepage,"html.parser")
#Scraping "Project Title" (project-title)
project_title = soup.find('h6', {'class': 'project-title'}).findChildren('a')
title = project_title[0].text
print (title)</code></pre>
</div>
</div>
</p>
<p>If I use the soup.find_all or set another value at the line Project_title[0] instead of zero, Python shows an error.</p>
<p>I need a list with all the project titles of this Website. Eg.: </p>
<ul>
<li>The Superbook: Turn your smartphone into a laptop for $99</li>
<li>Weights: Weigh Smarter</li>
<li>Mine Kafon Drone World's First And Only Complete</li>
<li>Weather Camera System Omega2: $5 IoT Computer with Wi-Fi, Powered by
Linux</li>
</ul>
| 4 | 2016-07-25T10:00:40Z | 38,565,858 | <p><code>find()</code>only returns one element. To get all, you must use <code>findAll</code></p>
<p>Here's the code you need</p>
<pre><code>project_elements = soup.findAll('h6', {'class': 'project-title'})
project_titles = [project.findChildren('a')[0].text for project in project_elements]
print(project_titles)
</code></pre>
<p>We look at all the elements of tag <code>h6</code> and class <code>project-title</code>. We then take the title from each of these elements, and create a list with it.</p>
<p>Hope it helped, and don't hesitate to ask if you have any question.</p>
<p>edit : the problem of the above code is that it will fail if we do not get at least a child of tag <code>a</code> for each element in the list returned by <code>findAll</code> </p>
<p>How to prevent this :</p>
<pre><code>project_titles = [project.findChildren('a')[0].text for project in project_elements if project.findChildren('a')]
</code></pre>
<p>this will create the list only if the <code>project.findChildren('a')</code> as at least one element. (<code>if []</code> returns False)</p>
<p>edit : to get the description of the elements (class <code>project-blurb</code>), let's look a bit at the HTML code.</p>
<pre><code><p class="project-blurb">
Bagel is a digital tape measure that helps you measure, organize, and analyze any size measurements in a smart way.
</p>
</code></pre>
<p>This is only a paragraph of class <code>project-blurb</code>. To get them, we could use the same as we did to get the project_elements, or more condensed : </p>
<pre><code>project_desc = [description.text for description in soup.findAll('p', {'class': 'project-blurb'})]
</code></pre>
| 2 | 2016-07-25T10:54:28Z | [
"python",
"python-3.x",
"beautifulsoup",
"python-3.5"
] |
Python 3.5 | Scraping data from website | 38,564,754 | <p>I want to scrape a specific part of the website <a href="https://www.kickstarter.com/discover/categories/technology?ref=discover_index" rel="nofollow">Kickstarter.com</a></p>
<p>I need the strings of the Project-title. The website is structured and every project has this line.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Project-title"></code></pre>
</div>
</div>
</p>
<p>My code looks like: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>#Loading Libraries
import urllib
import urllib.request
from bs4 import BeautifulSoup
#define URL for scraping
theurl = "https://www.kickstarter.com/discover/advanced?category_id=16&woe_id=23424829&sort=popularity&seed=2448324&page=1"
thepage = urllib.request.urlopen(theurl)
#Cooking the Soup
soup = BeautifulSoup(thepage,"html.parser")
#Scraping "Project Title" (project-title)
project_title = soup.find('h6', {'class': 'project-title'}).findChildren('a')
title = project_title[0].text
print (title)</code></pre>
</div>
</div>
</p>
<p>If I use the soup.find_all or set another value at the line Project_title[0] instead of zero, Python shows an error.</p>
<p>I need a list with all the project titles of this Website. Eg.: </p>
<ul>
<li>The Superbook: Turn your smartphone into a laptop for $99</li>
<li>Weights: Weigh Smarter</li>
<li>Mine Kafon Drone World's First And Only Complete</li>
<li>Weather Camera System Omega2: $5 IoT Computer with Wi-Fi, Powered by
Linux</li>
</ul>
| 4 | 2016-07-25T10:00:40Z | 38,565,982 | <p>All the data you want is in the section with the css class <em>staff-picks</em>, just find the <em>h6's</em> with the <em>project-title</em> class and extract the text from the anchor tag inside:</p>
<pre><code>soup = BeautifulSoup(thepage,"html.parser")
print [a.text for a in soup.select("section.staff-picks h6.project-title a")]
</code></pre>
<p>Output:</p>
<pre><code>[u'The Superbook: Turn your smartphone into a laptop for $99', u'Weighitz: Weigh Smarter', u'Omega2: $5 IoT Computer with Wi-Fi, Powered by Linux', u"Bagel: The World's Smartest Tape Measure", u'FireFlies - Truly Wire-Free Earbuds - Music Without Limits!', u'ISOLATE\xae - Switch off your ears!']
</code></pre>
<p>Or using <em>find</em> with <em>find_all</em>:</p>
<pre><code>project_titles = soup.find("section",class_="staff-picks").find_all("h6", "project-title")
print([proj.a.text for proj in project_titles])
</code></pre>
<p>There is also only one anchor tag inside each h6 tag so you cannot end up with more than one whatever approach you take.</p>
| 0 | 2016-07-25T11:00:31Z | [
"python",
"python-3.x",
"beautifulsoup",
"python-3.5"
] |
Python 3.5 | Scraping data from website | 38,564,754 | <p>I want to scrape a specific part of the website <a href="https://www.kickstarter.com/discover/categories/technology?ref=discover_index" rel="nofollow">Kickstarter.com</a></p>
<p>I need the strings of the Project-title. The website is structured and every project has this line.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Project-title"></code></pre>
</div>
</div>
</p>
<p>My code looks like: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>#Loading Libraries
import urllib
import urllib.request
from bs4 import BeautifulSoup
#define URL for scraping
theurl = "https://www.kickstarter.com/discover/advanced?category_id=16&woe_id=23424829&sort=popularity&seed=2448324&page=1"
thepage = urllib.request.urlopen(theurl)
#Cooking the Soup
soup = BeautifulSoup(thepage,"html.parser")
#Scraping "Project Title" (project-title)
project_title = soup.find('h6', {'class': 'project-title'}).findChildren('a')
title = project_title[0].text
print (title)</code></pre>
</div>
</div>
</p>
<p>If I use the soup.find_all or set another value at the line Project_title[0] instead of zero, Python shows an error.</p>
<p>I need a list with all the project titles of this Website. Eg.: </p>
<ul>
<li>The Superbook: Turn your smartphone into a laptop for $99</li>
<li>Weights: Weigh Smarter</li>
<li>Mine Kafon Drone World's First And Only Complete</li>
<li>Weather Camera System Omega2: $5 IoT Computer with Wi-Fi, Powered by
Linux</li>
</ul>
| 4 | 2016-07-25T10:00:40Z | 38,584,902 | <p>With respect to the title of this post i would recommend you two different tutorial based on scraping particular data from a website . They do have a detailed explanation regarding how the task is achieved.</p>
<p>Firstly i would recommend to checkout pyimagesearch
<a href="http://www.pyimagesearch.com/2015/10/12/scraping-images-with-python-and-scrapy/" rel="nofollow">Scraping images using scrapy.</a></p>
<p>then you should try if you are more specific <a href="https://realpython.com/blog/python/web-scraping-with-scrapy-and-mongodb/" rel="nofollow">web scraping will help you.</a></p>
| 1 | 2016-07-26T08:37:19Z | [
"python",
"python-3.x",
"beautifulsoup",
"python-3.5"
] |
Pandas: replace values in column | 38,564,756 | <p>I have df and I want to replace values there</p>
<pre><code>df = pd.read_csv('visits_april.csv')
df1 = pd.read_csv('participants.csv')`
url, date
aliexpress.com/payment/payment-result.htm... 2016-04-30 22:57:41
shoppingcart.aliexpress.com/order/confirm_orde... 2016-04-30 23:05:21
shoppingcart.aliexpress.com/order/confirm_orde... 2016-04-30 23:05:33
shoppingcart.aliexpress.com/order/confirm_orde... 2016-04-30 23:11:37
aliexpress.com/payment/payment-result.htm... 2016-04-30 23:12:07
shoppingcart.aliexpress.com/order/confirm_orde... 2016-04-30 23:15:31
shoppingcart.aliexpress.com/order/confirm_orde... 2016-04-30 23:15:37
aliexpress.com/payment/payment-result.htm... 2016-04-30 23:16:13
kupivip.ru/shop/checkout/confirmation 2016-04-30 23:18:15
</code></pre>
<p>if string from <code>df</code> contain string from <code>df2</code> I want to replace it to string from <code>df2</code></p>
<pre><code>visits
aliexpress.com
ozon.ru
wildberries.ru
lamoda.ru
mvideo.ru
eldorado.ru
ulmart.ru
ebay.com
kupivip.ru
</code></pre>
<p>Desire output</p>
<pre><code>url
aliexpress.com
aliexpress.com
aliexpress.com
aliexpress.com
aliexpress.com
aliexpress.com
aliexpress.com
aliexpress.com
kupivip.ru
</code></pre>
<p>I try <code>df[df['url'].isin(df2['visits'])]</code> but it return <code>Empty DataFrame</code>.</p>
| 1 | 2016-07-25T10:00:53Z | 38,565,006 | <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow"><code>extract</code></a> joined list with <code>|</code> (regex <code>or</code>) from column <code>visits</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.tolist.html" rel="nofollow"><code>tolist</code></a>:</p>
<pre><code>L = df2.visits.tolist()
print (L)
['aliexpress.com', 'ozon.ru', 'wildberries.ru', 'lamoda.ru',
'mvideo.ru', 'eldorado.ru', 'ulmart.ru', 'ebay.com', 'kupivip.ru']
print (df.url.str.extract('(' + '|'.join(L) + ')', expand=False))
0 aliexpress.com
1 aliexpress.com
2 aliexpress.com
3 aliexpress.com
4 aliexpress.com
5 aliexpress.com
6 aliexpress.com
7 aliexpress.com
8 kupivip.ru
Name: url, dtype: object
</code></pre>
| 2 | 2016-07-25T10:12:58Z | [
"python",
"pandas",
"replace",
"dataframe"
] |
django foreign key of foreign key but can't show in admin page | 38,564,758 | <p>I get a problem with the models.py and views.py.
When user add a reply to comment, the "Dish_comment_reply_post" always show nothing, I need select by myself in admin page.
Please give me a hand...</p>
<p>models.py:</p>
<pre><code>class Dish_comment(models.Model):
Dish_comment_post=models.ForeignKey('dish.Dish_post', related_name='comments')
Your_name=models.CharField(max_length=200)
Content=models.TextField()
Dish_comment_created_date=models.DateField(default=timezone.now)
Dish_comment_approved=models.BooleanField(default=False)
def approve(self):
self.Dish_comment_approved=True
self.save()
def __str__(self):
return self.Content
def Dish_approved_comments(self):
return self.Dish_comment.filter(Dish_comment_approved=True)
class Dish_comment_reply(models.Model):
Dish_comment_reply_post=models.ForeignKey('dish.Dish_comment', related_name='replies', null=True)
Your_name=models.CharField(max_length=200, default='abcd12345')
Content=models.TextField()
Dish_comment_reply_created_date=models.DateField(default=timezone.now)
def __str__(self):
return self.Content
</code></pre>
<p>views.py:</p>
<pre><code>def dish_add_comment_to_post(request,pk):
dish_post_from_db=get_object_or_404(Dish_post, pk=pk)
if request.method=="POST":
dish_comment_form=DishCommentForm(request.POST)
if dish_comment_form.is_valid():
dish_comment_from_admin=dish_comment_form.save(commit=False)
dish_comment_from_admin.Dish_comment_post=dish_post_from_db
dish_comment_from_admin.save()
return redirect('dish.views.dish_detail', pk=dish_post_from_db.pk)
else:
dish_comment_form=DishCommentForm()
return render(request, 'dish/dish_add_comment_to_post.html', {'dish_comment_form': dish_comment_form})
@login_required
def dish_comment_approve(request, pk):
dish_comment_from_db = get_object_or_404(Dish_comment, pk=pk)
dish_comment_from_db.approve()
return redirect('dish.views.dish_detail', pk=dish_comment_from_db.Dish_comment_post.pk)
@login_required
def dish_comment_remove(request, pk):
dish_comment_from_db = get_object_or_404(Dish_comment, pk=pk)
dish_post_pk = dish_comment_from_db.Dish_comment_post.pk
dish_comment_from_db.delete()
return redirect('dish.views.dish_detail', pk=dish_post_pk)
def dish_add_reply_to_comment(request, pk1, pk2):
dish_post_from_db=get_object_or_404(Dish_post, pk=pk1)
dish_comment_from_db=get_object_or_404(Dish_comment, pk=pk2)
if request.method=="POST":
dish_reply_form=DishCommentReplyForm(request.POST)
if dish_reply_form.is_valid():
dish_reply_from_admin=dish_reply_form.save(commit=False)
dish_reply_from_admin.Dish_comment_reply_post=dish_comment_from_db
dish_reply_from_admin.save()
return redirect('dish.views.dish_detail', pk=dish_post_from_db.pk)
else:
dish_reply_form=DishCommentReplyForm()
return render(request, 'dish/dish_add_reply_to_comment.html', {'dish_reply_form': dish_reply_form})
</code></pre>
| 0 | 2016-07-25T10:00:59Z | 38,565,665 | <p>change
<code>Dish_comment_post=models.ForeignKey('dish.Dish_post', related_name='comments')</code> to
<code>Dish_comment_post=models.ForeignKey('Dish_post', related_name='comments')</code> and
<code>Dish_comment_reply_post=models.ForeignKey('dish.Dish_comment', related_name='replies', null=True)</code> to <code>Dish_comment_reply_post=models.ForeignKey('Dish_comment', related_name='replies', null=True)</code></p>
| 0 | 2016-07-25T10:44:52Z | [
"python",
"django"
] |
Synchronizing Django social auth with User registration | 38,564,782 | <p>I created a django project which has separate User registration form and uses <strong>python-social-auth</strong> for direct login. Whenever I try to login with social_auth which uses the email id which I already used for creating a account through registration form, a separate row has been inserted instead of using existing one.</p>
<p>If I try to login through social_auth after changing the email Id as unique in model, I am getting an error "email id already exists". If I remove unique from email, then separate entry coming in User table and It is considered as a different account.</p>
<p>Now the problem is, I don't need <strong>separate accounts for same email Id</strong>(created using registration form, Facebook, Google). And I need to <strong>synchronize the accounts created using registration form and social auth</strong>.</p>
<p>Settings.py</p>
<pre><code>import os
import datetime
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.dirname(BASE_DIR))
SECRET_KEY = '**********'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'app.accounts',
'social.apps.django_app.default',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social.apps.django_app.middleware.SocialAuthExceptionMiddleware',
)
AUTHENTICATION_BACKENDS = (
'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth2',
'app.accounts.backends.AuthBackend',
'django.contrib.auth.backends.ModelBackend',
)
REST_FRAMEWORK = {
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.AllowAny',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
)
}
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)
}
JWT_ALLOW_REFRESH = True
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.core.context_processors.request',
'django.core.context_processors.csrf',
'django.contrib.messages.context_processors.messages',
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
)
AUTH_USER_MODEL = 'accounts.Account'
ROOT_URLCONF = 'main.urls'
WSGI_APPLICATION = 'main.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates'),
)
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
SOCIAL_AUTH_LOGIN_URL = 'accounts/home/'
SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'accounts/home/'
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.auth_allowed',
'social.pipeline.social_auth.social_user',
'social.pipeline.user.get_username',
'social.pipeline.mail.mail_validation',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.load_extra_data',
)
SOCIAL_AUTH_USER_MODEL='accounts.Account'
</code></pre>
<p>Traceback</p>
<pre><code>Traceback (most recent call last):
File "/home/mugesh/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/apps/django_app/utils.py", line 51, in wrapper
return func(request, backend, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/apps/django_app/views.py", line 28, in complete
redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/actions.py", line 43, in do_complete
user = backend.complete(user=user, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/base.py", line 41, in complete
return self.auth_complete(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/utils.py", line 229, in wrapper
return func(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/oauth.py", line 387, in auth_complete
*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/utils.py", line 229, in wrapper
return func(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/oauth.py", line 396, in do_auth
return self.strategy.authenticate(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/strategies/django_strategy.py", line 96, in authenticate
return authenticate(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 74, in authenticate
user = backend.authenticate(**credentials)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/base.py", line 82, in authenticate
return self.pipeline(pipeline, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/base.py", line 85, in pipeline
out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/base.py", line 112, in run_pipeline
result = func(*args, **out) or {}
File "/home/mugesh/.local/lib/python2.7/site-packages/social/pipeline/user.py", line 70, in create_user
'user': strategy.create_user(**fields)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/strategies/base.py", line 53, in create_user
return self.storage.user.create_user(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/storage/django_orm.py", line 60, in create_user
return cls.user_model().objects.create_user(*args, **kwargs)
File "/media/mugesh/Extra/STUDIES/Internship/Projects/wedifly/app/accounts/models.py", line 43, in create_user
return self._create_user(email, first_name, last_name, password, False, False, **extra_fields)
File "/media/mugesh/Extra/STUDIES/Internship/Projects/wedifly/app/accounts/models.py", line 26, in _create_user
user.save(using=self._db)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 74, in save
super(AbstractBaseUser, self).save(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/base.py", line 700, in save
force_update=force_update, update_fields=update_fields)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/base.py", line 728, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/base.py", line 812, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/base.py", line 851, in _do_insert
using=using, raw=raw)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql
cursor.execute(sql, params)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: UNIQUE constraint failed: accounts.email
</code></pre>
<p>Any Suggestions or solutions are welcome.
Thank you,</p>
| 1 | 2016-07-25T10:01:58Z | 38,565,269 | <p>I think adding <code>associate_user</code> to <code>SOCIAL_AUTH_PIPELINE</code> was designed to fix this:</p>
<pre><code>SOCIAL_AUTH_PIPELINE = (
...
'social.pipeline.social_auth.associate_by_email',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.associate_user', # <------
'social.pipeline.social_auth.load_extra_data',
...
)
</code></pre>
<p>It should associate a <code>social_user</code> with an already existing user created via your form registration as opposed to creating an entirely new user.</p>
| 0 | 2016-07-25T10:25:51Z | [
"python",
"django",
"user-accounts",
"python-social-auth"
] |
Synchronizing Django social auth with User registration | 38,564,782 | <p>I created a django project which has separate User registration form and uses <strong>python-social-auth</strong> for direct login. Whenever I try to login with social_auth which uses the email id which I already used for creating a account through registration form, a separate row has been inserted instead of using existing one.</p>
<p>If I try to login through social_auth after changing the email Id as unique in model, I am getting an error "email id already exists". If I remove unique from email, then separate entry coming in User table and It is considered as a different account.</p>
<p>Now the problem is, I don't need <strong>separate accounts for same email Id</strong>(created using registration form, Facebook, Google). And I need to <strong>synchronize the accounts created using registration form and social auth</strong>.</p>
<p>Settings.py</p>
<pre><code>import os
import datetime
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.dirname(BASE_DIR))
SECRET_KEY = '**********'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'app.accounts',
'social.apps.django_app.default',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social.apps.django_app.middleware.SocialAuthExceptionMiddleware',
)
AUTHENTICATION_BACKENDS = (
'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth2',
'app.accounts.backends.AuthBackend',
'django.contrib.auth.backends.ModelBackend',
)
REST_FRAMEWORK = {
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.AllowAny',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
)
}
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)
}
JWT_ALLOW_REFRESH = True
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.core.context_processors.request',
'django.core.context_processors.csrf',
'django.contrib.messages.context_processors.messages',
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
)
AUTH_USER_MODEL = 'accounts.Account'
ROOT_URLCONF = 'main.urls'
WSGI_APPLICATION = 'main.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates'),
)
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
SOCIAL_AUTH_LOGIN_URL = 'accounts/home/'
SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'accounts/home/'
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.auth_allowed',
'social.pipeline.social_auth.social_user',
'social.pipeline.user.get_username',
'social.pipeline.mail.mail_validation',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.load_extra_data',
)
SOCIAL_AUTH_USER_MODEL='accounts.Account'
</code></pre>
<p>Traceback</p>
<pre><code>Traceback (most recent call last):
File "/home/mugesh/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/apps/django_app/utils.py", line 51, in wrapper
return func(request, backend, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/apps/django_app/views.py", line 28, in complete
redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/actions.py", line 43, in do_complete
user = backend.complete(user=user, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/base.py", line 41, in complete
return self.auth_complete(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/utils.py", line 229, in wrapper
return func(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/oauth.py", line 387, in auth_complete
*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/utils.py", line 229, in wrapper
return func(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/oauth.py", line 396, in do_auth
return self.strategy.authenticate(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/strategies/django_strategy.py", line 96, in authenticate
return authenticate(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 74, in authenticate
user = backend.authenticate(**credentials)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/base.py", line 82, in authenticate
return self.pipeline(pipeline, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/base.py", line 85, in pipeline
out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/backends/base.py", line 112, in run_pipeline
result = func(*args, **out) or {}
File "/home/mugesh/.local/lib/python2.7/site-packages/social/pipeline/user.py", line 70, in create_user
'user': strategy.create_user(**fields)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/strategies/base.py", line 53, in create_user
return self.storage.user.create_user(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/social/storage/django_orm.py", line 60, in create_user
return cls.user_model().objects.create_user(*args, **kwargs)
File "/media/mugesh/Extra/STUDIES/Internship/Projects/wedifly/app/accounts/models.py", line 43, in create_user
return self._create_user(email, first_name, last_name, password, False, False, **extra_fields)
File "/media/mugesh/Extra/STUDIES/Internship/Projects/wedifly/app/accounts/models.py", line 26, in _create_user
user.save(using=self._db)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 74, in save
super(AbstractBaseUser, self).save(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/base.py", line 700, in save
force_update=force_update, update_fields=update_fields)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/base.py", line 728, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/base.py", line 812, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/base.py", line 851, in _do_insert
using=using, raw=raw)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql
cursor.execute(sql, params)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/mugesh/.local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: UNIQUE constraint failed: accounts.email
</code></pre>
<p>Any Suggestions or solutions are welcome.
Thank you,</p>
| 1 | 2016-07-25T10:01:58Z | 38,566,634 | <p>When you are using social auth it has separate table 'social_auth_usersocialauth' it gets filled when you call the login for the first time, social auth work in such a way that if it doesn't have an entry in 'social_auth_usersocialauth' it creates a new entry in it and it assumes that you are login it for the first time and creates a new user, that's why user is getting created again.</p>
<p>Use social auth first and try to identify whether you are registering for the first time if so take him to the registration page else it will work as anormal login.</p>
| 0 | 2016-07-25T11:32:38Z | [
"python",
"django",
"user-accounts",
"python-social-auth"
] |
django.db.utils.OperationalError no matter what I try | 38,564,851 | <p>OK, I'm stumped. I think I've tried everything. </p>
<p>I created a model in an app's <code>models.py</code> and also added some more fields to an existing model (all with default values). Then I ran <code>makemigrations</code>. The result:</p>
<pre><code>$ python3 manage.py makemigrations
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such column: myapp_MyExistingModel.first_new_field
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 398, in execute
self.check()
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.5/dist-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.5/dist-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/path/to/myproject/myproject/urls.py", line 49, in <module>
url(r'^someurl/', include('myapp.urls')),
File "/usr/local/lib/python3.5/dist-packages/django/conf/urls/__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/path/to/myproject/myapp/urls.py", line 2, in <module>
from . import views
File "/path/to/myproject/myapp/views.py", line 8, in <module>
existing_model = MyExistingModel.objects.all()[0]
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 297, in __getitem__
return list(qs)[0]
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 258, in __iter__
self._fetch_all()
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 52, in __iter__
results = compiler.execute_sql()
File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 848, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such column: myapp_MyExistingModel.first_new_field
</code></pre>
<p>If it matters, I'm using Mezzanine CMS and MyExistingModel is an extension of its <code>Page</code> class. It only has one instance. </p>
<p>So here's what I tried next:</p>
<ol>
<li><code>manage.py migrate --fake</code></li>
<li><code>manage.py flush</code></li>
<li>Renaming my database so a new one would be created</li>
</ol>
<p>All of these threw the same traceback. I went into the last migration for the app. It contained an <code>AddModel</code> for my new model and a <code>RemoveField</code> for a field in the old model I renamed, but no <code>AddField</code> for the new fields I created. So I added them to the migrations file manually and retried <code>manage.py migrate --fake</code>. Same traceback. I tried all the other commands too. Same traceback. </p>
<p>Finally, I deleted all the app's migrations, leaving just <code>__init__.py</code>. I also renamed the database so it would be recreated. I retried <code>flush</code>, <code>makemigrations</code>, and <code>migrate</code> (with and without <code>--fake</code>). All of these resulted in this traceback: </p>
<pre><code>Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: myapp_MyExistingModel
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 398, in execute
self.check()
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.5/dist-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.5/dist-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/path/to/myproject/myproject/urls.py", line 49, in <module>
url(r'^someurl/', include('myapp.urls')),
File "/usr/local/lib/python3.5/dist-packages/django/conf/urls/__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/path/to/myproject/myapp/urls.py", line 2, in <module>
from . import views
File "/path/to/myproject/myapp/views.py", line 8, in <module>
existing_model = MyExistingModel.objects.all()[0]
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 297, in __getitem__
return list(qs)[0]
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 258, in __iter__
self._fetch_all()
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 52, in __iter__
results = compiler.execute_sql()
File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 848, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: myapp_MyExistingModel
</code></pre>
<p>At this point, I have no idea what to even try next, except <a href="http://stackoverflow.com/questions/29963186/django-1-7-migrations-django-db-utils-operationalerror-no-such-table-db-trans#comment48048112_29963186">start over</a>. Any suggestions are appreciated. </p>
| 0 | 2016-07-25T10:05:29Z | 38,604,017 | <p>I figured it out! Lesson learned: read the whole stacktrace, not just the last line. In this case, the offensive line was in my <code>views.py</code>: </p>
<pre><code>File "/path/to/myproject/myapp/views.py", line 8, in <module>
existing_model = MyExistingModel.objects.all()[0]
</code></pre>
<p>Like I said, <code>MyExistingModel</code> has only one instance, and this line set that instance to the local variable <code>existing_model</code> for use in the <code>views.py</code> code. </p>
<p>I still don't understand why <code>makemigrations</code> would need to run <code>views.py</code>. But it does, apparently! In doing so, <code>MyExistingModel</code> was imported from <code>models.py</code>, <strong>including</strong> the new fields. But those fields hadn't yet been migrated. Thus, OperationalError. </p>
| 0 | 2016-07-27T04:55:24Z | [
"python",
"django",
"python-3.x",
"django-models",
"mezzanine"
] |
Python BeautifulSoup only select top tag | 38,565,096 | <p>I encounter a problem, it might be very easy, but I didn't saw it on document.</p>
<p>Here is the target html structure, very simple.</p>
<pre><code><h3>Top
<em>Mid</em>
<span>Down</span>
</h3>
</code></pre>
<p>I want to get the "Top" text which was inside the <code>h3</code> tag, and I wrote this</p>
<pre><code>from bs4 import BeautifulSoup
html ="<h3>Top <em>Mid </em><span>Down</span></h3>"
soup = BeautifulSoup(html)
print soup.select("h3")[0].text
</code></pre>
<p>But it will return <code>Top Mid Down</code>, how do I modify it? </p>
| 1 | 2016-07-25T10:17:22Z | 38,565,191 | <p>Try something like this:</p>
<pre><code>from bs4 import BeautifulSoup
html ="<h3>Top <em>Mid </em><span>Down</span></h3>"
soup = BeautifulSoup(html)
print soup.select("h3").findChildren()[0]
</code></pre>
<p>Though I am not entirely sure. Check this as well - <a href="http://stackoverflow.com/questions/6287529/how-to-find-children-of-nodes-using-beautiful-soup">How to find children of nodes using Beautiful Soup</a></p>
<p>Basically you need to hunt the first <a href="http://www.w3schools.com/jsref/prop_node_childnodes.asp" rel="nofollow">childNode</a>.</p>
| 0 | 2016-07-25T10:21:46Z | [
"python",
"html",
"beautifulsoup"
] |
Python BeautifulSoup only select top tag | 38,565,096 | <p>I encounter a problem, it might be very easy, but I didn't saw it on document.</p>
<p>Here is the target html structure, very simple.</p>
<pre><code><h3>Top
<em>Mid</em>
<span>Down</span>
</h3>
</code></pre>
<p>I want to get the "Top" text which was inside the <code>h3</code> tag, and I wrote this</p>
<pre><code>from bs4 import BeautifulSoup
html ="<h3>Top <em>Mid </em><span>Down</span></h3>"
soup = BeautifulSoup(html)
print soup.select("h3")[0].text
</code></pre>
<p>But it will return <code>Top Mid Down</code>, how do I modify it? </p>
| 1 | 2016-07-25T10:17:22Z | 38,565,440 | <p>its easy for you to search using a regex
something like this </p>
<pre><code> pageid=re.search('<h3>(.*?)</h3>', curPage, re.DOTALL)
</code></pre>
<p>and get the each of the data inside the tag using <code>pageid.group(value)</code> method</p>
| -1 | 2016-07-25T10:34:22Z | [
"python",
"html",
"beautifulsoup"
] |
Python BeautifulSoup only select top tag | 38,565,096 | <p>I encounter a problem, it might be very easy, but I didn't saw it on document.</p>
<p>Here is the target html structure, very simple.</p>
<pre><code><h3>Top
<em>Mid</em>
<span>Down</span>
</h3>
</code></pre>
<p>I want to get the "Top" text which was inside the <code>h3</code> tag, and I wrote this</p>
<pre><code>from bs4 import BeautifulSoup
html ="<h3>Top <em>Mid </em><span>Down</span></h3>"
soup = BeautifulSoup(html)
print soup.select("h3")[0].text
</code></pre>
<p>But it will return <code>Top Mid Down</code>, how do I modify it? </p>
| 1 | 2016-07-25T10:17:22Z | 38,565,739 | <p>You can use <em>find</em> setting <em>text=True</em> and <em>recursive=False</em>:</p>
<pre><code>In [2]: from bs4 import BeautifulSoup
...: html ="<h3>Top <em>Mid </em><span>Down</span></h3>"
...: soup = BeautifulSoup(html,"html.parser")
...: print(soup.find("h3").find(text=True,recursive=False))
...:
Top
</code></pre>
<p>Depending on the format, there are lots of different ways:</p>
<pre><code>print(soup.find("h3").contents[0])
print(next(soup.find("h3").children))
print(soup.find("h3").next)
</code></pre>
| 1 | 2016-07-25T10:48:45Z | [
"python",
"html",
"beautifulsoup"
] |
How to name list of lists in Python? | 38,565,104 | <p>I have the following list of lists: </p>
<pre><code>sims1 = [[(2, 0.90452874), (1, 0.83522302), (4, 0.77591574), (0, 0.72705799), (3, 0.52282226)],
[(3, 0.79298556), (1, 0.78112978), (2, 0.76006395), (0, 0.58570701), (4, 0.40093967)],
[(2, 0.9549554), (1, 0.71705657), (0, 0.58731651), (3, 0.43987277), (4, 0.38266104)],
[(2, 0.96805269), (4, 0.68034023), (1, 0.66391909), (0, 0.64251828), (3, 0.50730866)],
[(2, 0.84748113), (4, 0.8338449), (1, 0.61795002), (0, 0.60271078), (3, 0.20899911)]]
</code></pre>
<p>I would like to name each list in the list according to these strings: <code>url = ['a', 'b', 'c', 'd']</code>. So for example, </p>
<pre><code>>>> a
[(2, 0.90452874), (1, 0.83522302), (4, 0.77591574), (0, 0.72705799), (3, 0.52282226)]
>>> b
[(3, 0.79298556), (1, 0.78112978), (2, 0.76006395), (0, 0.58570701), (4, 0.40093967)]
</code></pre>
<p>etc. So how do I accomplish this in Python?</p>
| 0 | 2016-07-25T10:17:43Z | 38,565,168 | <p>Use <code>zip()</code> and <code>dict()</code>:</p>
<pre><code>result = dict(zip(url, sims1))
</code></pre>
<p>Make sure that the elements in <code>url</code> are strings like <code>'a'</code> rather than a variable name like <code>a</code>, or the definition of <code>url</code> will fail with a <code>NameError</code>.</p>
| 1 | 2016-07-25T10:20:27Z | [
"python",
"arrays",
"list"
] |
How to name list of lists in Python? | 38,565,104 | <p>I have the following list of lists: </p>
<pre><code>sims1 = [[(2, 0.90452874), (1, 0.83522302), (4, 0.77591574), (0, 0.72705799), (3, 0.52282226)],
[(3, 0.79298556), (1, 0.78112978), (2, 0.76006395), (0, 0.58570701), (4, 0.40093967)],
[(2, 0.9549554), (1, 0.71705657), (0, 0.58731651), (3, 0.43987277), (4, 0.38266104)],
[(2, 0.96805269), (4, 0.68034023), (1, 0.66391909), (0, 0.64251828), (3, 0.50730866)],
[(2, 0.84748113), (4, 0.8338449), (1, 0.61795002), (0, 0.60271078), (3, 0.20899911)]]
</code></pre>
<p>I would like to name each list in the list according to these strings: <code>url = ['a', 'b', 'c', 'd']</code>. So for example, </p>
<pre><code>>>> a
[(2, 0.90452874), (1, 0.83522302), (4, 0.77591574), (0, 0.72705799), (3, 0.52282226)]
>>> b
[(3, 0.79298556), (1, 0.78112978), (2, 0.76006395), (0, 0.58570701), (4, 0.40093967)]
</code></pre>
<p>etc. So how do I accomplish this in Python?</p>
| 0 | 2016-07-25T10:17:43Z | 38,565,188 | <p>You can use dictionary:</p>
<pre><code>names = ['a', 'b', 'c', 'd', 'e']
named_sims1 = dict(zip(names, sims1))
print(named_sims1['a'])
</code></pre>
<p>If you want to access the variables as <code>a</code> instead of <code>x.a</code> or x['a'], you can use this:</p>
<pre><code>exec(",".join(names) + ' = ' + str(sims1)) # ensure same length
</code></pre>
<p>But I am not sure, if this is recommended.</p>
| 3 | 2016-07-25T10:21:27Z | [
"python",
"arrays",
"list"
] |
Regex replacement for strip() | 38,565,110 | <p>Long time/first time.</p>
<p>I am a pharmacist by trade by am going through the motions of teaching myself how to code in a variety of languages that are useful to me for things like task automation at work, but mainly Python 3.x. I am working through the automatetheboringstuff eBook and finding it great. </p>
<p>I am trying to complete one of the practice questions from Chapter 7:
<em>"Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string."</em></p>
<p>I am stuck for the situation when the characters I want to strip appear in the string I want to strip them from e.g. 'ssstestsss'.strip(s)</p>
<pre class="lang-python prettyprint-override"><code>#!python3
import re
respecchar = ['?', '*', '+', '{', '}', '.', '\\', '^', '$', '[', ']']
def regexstrip(string, _strip):
if _strip == '' or _strip == ' ':
_strip = r'\s'
elif _strip in respecchar:
_strip = r'\'+_strip'
print(_strip) #just for troubleshooting
re_strip = re.compile('^'+_strip+'*(.+)'+_strip+'*$')
print(re_strip) #just for troubleshooting
mstring = re_strip.search(string)
print(mstring) #just for troubleshooting
stripped = mstring.group(1)
print(stripped)
</code></pre>
<p>As it is shown, running it on ('ssstestsss', 's') will yield 'testsss' as the .+ gets all of it and the * lets it ignore the final 'sss'. If I change the final * to a + it only improves a bit to yield 'testss'. If I make the capture group non-greedy (i.e. (.+)? ) I still get 'testsss' and if exclude the character to be stripped from the character class for the capture group and remove the end string anchor (i.e. <code>re.compile('^'+_strip+'*([^'+_strip+'.]+)'+_strip+'*')</code> I get 'te' and if I don't remove the end string anchor then it obviously errors. </p>
<p>Apologies for the verbose and ramble-y question. </p>
<p>I deliberately included all the code (work in progress) as I am only learning so I realise that my code is probably rather inefficient, so if you can see any other areas where I can improve my code, please let me know. I know that there is no practical application for this code, but I'm going through this as a learning exercise. </p>
<p>I hope I have asked this question appropriately and haven't missed anything in my searches. </p>
<p>Regards</p>
<p>Lobsta</p>
| 1 | 2016-07-25T10:17:53Z | 38,565,208 | <p>You <code>(.+)</code> is greedy, (by default). Just change it to non greedy, by using <code>(.+?)</code><br>
You can test python regex at <a href="https://regex101.com/#python" rel="nofollow">this site</a></p>
<p>edit : As someone commented, <code>(.+?)</code> and <code>(.+)?</code> do not do the same thing : <code>(.+?)</code> is the non greedy version of <code>(.+)</code> while <code>(.+)?</code> matches or not the greedy <code>(.+)</code></p>
| 3 | 2016-07-25T10:22:35Z | [
"python",
"regex",
"python-3.x"
] |
Regex replacement for strip() | 38,565,110 | <p>Long time/first time.</p>
<p>I am a pharmacist by trade by am going through the motions of teaching myself how to code in a variety of languages that are useful to me for things like task automation at work, but mainly Python 3.x. I am working through the automatetheboringstuff eBook and finding it great. </p>
<p>I am trying to complete one of the practice questions from Chapter 7:
<em>"Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string."</em></p>
<p>I am stuck for the situation when the characters I want to strip appear in the string I want to strip them from e.g. 'ssstestsss'.strip(s)</p>
<pre class="lang-python prettyprint-override"><code>#!python3
import re
respecchar = ['?', '*', '+', '{', '}', '.', '\\', '^', '$', '[', ']']
def regexstrip(string, _strip):
if _strip == '' or _strip == ' ':
_strip = r'\s'
elif _strip in respecchar:
_strip = r'\'+_strip'
print(_strip) #just for troubleshooting
re_strip = re.compile('^'+_strip+'*(.+)'+_strip+'*$')
print(re_strip) #just for troubleshooting
mstring = re_strip.search(string)
print(mstring) #just for troubleshooting
stripped = mstring.group(1)
print(stripped)
</code></pre>
<p>As it is shown, running it on ('ssstestsss', 's') will yield 'testsss' as the .+ gets all of it and the * lets it ignore the final 'sss'. If I change the final * to a + it only improves a bit to yield 'testss'. If I make the capture group non-greedy (i.e. (.+)? ) I still get 'testsss' and if exclude the character to be stripped from the character class for the capture group and remove the end string anchor (i.e. <code>re.compile('^'+_strip+'*([^'+_strip+'.]+)'+_strip+'*')</code> I get 'te' and if I don't remove the end string anchor then it obviously errors. </p>
<p>Apologies for the verbose and ramble-y question. </p>
<p>I deliberately included all the code (work in progress) as I am only learning so I realise that my code is probably rather inefficient, so if you can see any other areas where I can improve my code, please let me know. I know that there is no practical application for this code, but I'm going through this as a learning exercise. </p>
<p>I hope I have asked this question appropriately and haven't missed anything in my searches. </p>
<p>Regards</p>
<p>Lobsta</p>
| 1 | 2016-07-25T10:17:53Z | 38,565,745 | <p>As I mentioned in my comment, you did not include special chars into the character class.</p>
<p>Also, the <code>.*</code> without a <code>re.S</code> / <code>re.DOTALL</code> modifier does not match newlines. You may avoid using it with <code>^PATTERN|PATTERN$</code> or <code>\APATTERN|PATTERN\Z</code> (note that <code>\A</code> matches the start of a string, and <code>\Z</code> matches the very end of the string, <code>$</code> can match before the final newline symbol in a string, and thus, you cannot use <code>$</code>).</p>
<p>I'd suggest shrinking your code to</p>
<pre><code>import re
def regexstrip(string, _strip=None):
_strip = r"\A[\s{0}]+|[\s{0}]+\Z".format(re.escape(_strip)) if _strip else r"\A\s+|\s+\Z"
print(_strip) #just for troubleshooting
return re.sub(_strip, '', string)
print(regexstrip(" ([no more stripping'] ) ", " ()[]'"))
# \A[\s\ \(\)\[\]\']+|[\s\ \(\)\[\]\']+\Z
# no more stripping
print(regexstrip(" ([no more stripping'] ) "))
# \A\s+|\s+\Z
# ([no more stripping'] )
</code></pre>
<p>See the <a href="https://ideone.com/EcEhrK" rel="nofollow">Python demo</a></p>
<p>Note that: </p>
<ul>
<li>The <code>_strip</code> argument is optional with a <code>=None</code></li>
<li>The <code>_strip = r"\A[\s{0}]+|[\s{0}]+\Z".format(re.escape(_strip)) if _strip else r"\A\s+|\s+\Z"</code> inits the regex pattern: if <code>_strip</code> is passed, the symbols are put inside a <code>[...]</code> character class and escaped (since we cannot control the symbol positions much, it is the quickest easiest way to make them all treated as literal symbols).</li>
<li>With <code>re.sub</code>, we remove the matched substrings.</li>
</ul>
| 1 | 2016-07-25T10:49:00Z | [
"python",
"regex",
"python-3.x"
] |
Zoom action in android using appium-python-client | 38,565,116 | <p>Does anybody know how to zoom an element in android via appium python client?</p>
<p>I am currently using</p>
<p><code>self.driver.zoom(self.element, percent)</code> but this gives an error</p>
<pre><code>self.driver.zoom(self.element, percent)
File "/usr/local/lib/python2.7/site-packages/appium/webdriver/webdriver.py", line 308, in zoom
self.execute_script('mobile: pinchOpen', opts)
File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 461, in execute_script
{'script': script, 'args':converted_args})['value']
File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 233, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/site-packages/appium/webdriver/errorhandler.py", line 29, in check_response
raise wde
WebDriverException: Message: Method has not yet been implemented
</code></pre>
<p>I also tried through <code>MultiAction</code>.</p>
<pre><code>loc = self.element.location
print loc
xx, yy = loc["x"], loc["y"]
xx=700
action1 = TouchAction(self.driver)
action1.long_press(x=xx, y=yy).move_to(x=0, y=1000).release()
action2 = TouchAction(self.driver)
action2.long_press(x=xx, y=yy).move_to(x=0, y=-1000).release()
m_action = MultiAction(self.driver)
m_action.add(action1, action2)
m_action.perform()
</code></pre>
<p>But again this does not perform any zoom.Instead it scrolls down the list.Does anybody have any idea about what's wrong here.</p>
<p><code>Appium Logs</code></p>
<pre><code>[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"action","action":"element:getLocation","params":{"elementId":"83"}}
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type ACTION
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command action: getLocation
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Returning result: {"status":0,"value":{"x":0,"y":1225}}
[debug] [AndroidBootstrap] Received command result from bootstrap
[MJSONWP] Responding to client with driver.getLocation() result: {"x":0,"y":1225}
[HTTP] <-- GET /wd/hub/session/c1a4d17f-0dc6-4445-bfad-776ec65bddb5/element/83/location 200 26 ms - 88
[HTTP] --> POST /wd/hub/session/c1a4d17f-0dc6-4445-bfad-776ec65bddb5/touch/multi/perform {"sessionId":"c1a4d17f-0dc6-4445-bfad-776ec65bddb5","actions":[[{"action":"longPress","options":{"y":1225,"x":700,"duration":1000}},{"action":"moveTo","options":{"y":1000,"x":0}},{"action":"release","options":{}}],[{"action":"longPress","options":{"y":1225,"x":700,"duration":1000}},{"action":"moveTo","options":{"y":-1000,"x":0}},{"action":"release","options":{}}]]}
[MJSONWP] Calling AppiumDriver.performMultiAction() with args: [[[{"action":"longPress","o...
[debug] [AndroidBootstrap] Sending command to android: {"cmd":"action","action":"performMultiPointerGesture","params":{"actions":[[{"action":"longPress","time":0.005,"touch":{"y":1225,"x":700,"duration":1000}},{"action":"moveTo","time":0.01,"touch":{"y":2225,"x":700}}],[{"action":"longPress","time":0.005,"touch":{"y":1225,"x":700,"duration":1000}},{"action":"moveTo","time":0.01,"touch":{"y":225,"x":700}}]]}}
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"action","action":"performMultiPointerGesture","params":{"actions":[[{"action":"longPress","time":0.005,"touch":{"y":1225,"x":700,"duration":1000}},{"action":"moveTo","time":0.01,"touch":{"y":2225,"x":700}}],[{"action":"longPress","time":0.005,"touch":{"y":1225,"x":700,"duration":1000}},{"action":"moveTo","time":0.01,"touch":{"y":225,"x":700}}]]}}
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type ACTION
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command action: performMultiPointerGesture
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Returning result: {"status":0,"value":"OK"}
[debug] [AndroidBootstrap] Received command result from bootstrap
[MJSONWP] Responding to client with driver.performMultiAction() result: "OK"
[HTTP] <-- POST /wd/hub/session/c1a4d17f-0dc6-4445-bfad-776ec65bddb5/touch/multi/perform 200 133 ms - 76
[HTTP] --> DELETE /wd/hub/session/c1a4d17f-0dc6-4445-bfad-776ec65bddb5 {}
</code></pre>
| 7 | 2016-07-25T10:18:20Z | 38,614,216 | <p>The MultiAction attempt looks good, but after testing a bit on my phone's native camera app, I was able to get a nice zoom gesture by adding 500ms wait() after the moveTo():</p>
<pre><code># Zoom
action1.long_press(x=xx, y=yy).move_to(x=0, y=50).wait(500).release()
action2.long_press(x=xx, y=yy).move_to(x=0, y=-50).wait(500).release()
m_action.add(action1, action2)
# Pinch
action3.long_press(x=xx, y=yy-50).move_to(x=0, y=50).wait(500).release()
action4.long_press(x=xx, y=yy+50).move_to(x=0, y=-50).wait(500).release()
m_action2.add(action3, action4)
m_action.perform()
m_action2.perform()
</code></pre>
<p>This resulted in a nice and slow zoom to the camera app. Without the wait() the gestures were too quick and didn't really do much. It is mentioned at Appium's documentation at Github, that wait() can be used to control the timing of a gesture: <a href="https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/touch-actions.md" rel="nofollow">https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/touch-actions.md</a></p>
<p>I set the <code>xx</code> and <code>yy</code> to the middle of the screen in my camera app with:</p>
<pre><code>xx = self.driver.get_window_size()['width']/2
yy = self.driver.get_window_size()['height']/2
</code></pre>
<p>Please remember that coordinates should never go out of device screen bounds, so checks for screen borders may be useful, if you want to make this into a re-usable function.</p>
<p>I also couldn't use the MultiAction gestures when automating Chrome (not even when changing to NATIVE_APP context. The gestures had no effect.) so it's possible that using MultiActions on WebView scenarios isn't supported.</p>
| 4 | 2016-07-27T13:21:37Z | [
"android",
"python",
"zoom",
"appium",
"python-appium"
] |
Kivy Launcher orientation | 38,565,231 | <p>Just a quick question:
Is it possible to enable both portrait and landscape mode in androind.txt for app run via Kivy Launcher?</p>
<p>I've seen that for buldozer there are "portrait/landscape/all" parameters available but it doesn't seem to work for Kivy Launcher</p>
| 0 | 2016-07-25T10:24:04Z | 38,669,257 | <p>Afaik, <code>orientation=all</code> or similar thing in <code>android.txt</code> does for launcher nothing, because it maybe needs some initial orientation(?) in the beginning and rotating isn't implemented maybe?. I'd go for not implemented, because the launcher itself can rotate in all types of orientation.</p>
<p>However, you may try <a href="https://github.com/kivy/plyer/" rel="nofollow">plyer</a> or <a href="https://github.com/kivy/pyjnius/" rel="nofollow">pyjnius</a> to change/fix orientation in runtime.</p>
| 0 | 2016-07-30T00:35:15Z | [
"python",
"kivy"
] |
Python Read ethernet frames using socket on Windows? | 38,565,335 | <p>I'm trying to read Ethernet (IEEE 802.2 / 3) frames using primarily <code>socket</code>.
The application shuld just sniff ethernet frames and depending on the content, act on it. However, there are almost no information on how to do this on Windows, the default (unix way) being <code>socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))</code>. This is nonexistent in winsock apparently. So how do I sniff eth frames? </p>
<p>I suspect I need to bind to a MAC using <code>socket.bind()</code> instead of IP.</p>
<p>My current piece of code:</p>
<pre><code>def _receive(interface): #Receive Eth packets.
#Interface = '192.168.0.10'
sock2 = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
sock2.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1))
sock2.bind((interface, 0))
while True:
data, sender = sock2.recvfrom(1500)
handle_data(sender, data)
</code></pre>
<p>Gets me nowhere. I see packets on Local connection in Wireshark, but it's not picked up in python.. </p>
<p>On linux, I can do <code>sock_raw = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_802_2))</code> , then bind and <code>setsockopt(sock_raw, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq))</code></p>
<p>I would like to not have to depend on too many external libraries becuase this is supposed to be distributed and thus pretty lightweight. <code>pip install</code>-able packages are OK though, they can be bundled with the installer..</p>
| 0 | 2016-07-25T10:28:41Z | 38,565,421 | <p>Python's socket doesn't come with sniffing capabilites. Simple as that.</p>
<p>The idea of having a network stack in your operating system is that programs "register" for specific types of packets to be delivered to them â typically, this is something like listening on a IP port, ie. one to two levels above raw ethernet packets.</p>
<p>To get all raw ethernet packets, your operating system's network stack needs some kind of driver/interface to support you with that. That's why wireshark needs WinPcap. </p>
<p>My guess is you're going to be pretty happy with <a href="https://github.com/pynetwork/pypcap" rel="nofollow">pypcap</a>, which probably is PyPi/pip installable.</p>
| 0 | 2016-07-25T10:33:34Z | [
"python",
"windows",
"sockets",
"ethernet"
] |
Can't install PyAL in Pycharm | 38,565,378 | <p>I wanted to use OpenAL in Python, therefore I tried to install <strong>PyAL</strong> through the Pycharm project settings. </p>
<p>I got the error message: </p>
<pre><code>No matching distribution found for PyAL
s the requirement PyAL (from version: )
</code></pre>
<p>Is this a known issue or am I doing something wrong? </p>
<p><strong>Reference:</strong></p>
<ul>
<li>Pycharm Community Edition 2016.1.4 </li>
<li>pip version 8.1.2</li>
<li>Python 3.5</li>
</ul>
| 1 | 2016-07-25T10:31:13Z | 38,565,404 | <p>There is no source or binary distribution for <a href="https://pypi.python.org/pypi/PyAL" rel="nofollow">PyAL</a></p>
<p>Maybe you should download it from <a href="https://bitbucket.org/marcusva/py-al/downloads" rel="nofollow">bitbucket</a></p>
<p>The homepage sais:</p>
<blockquote>
<p>PyAL is easy to install and integrate within your own projects. Just follow Python's standard procedure of installing packages or look for a prebuilt package for your operating system or distribution.</p>
</blockquote>
<p>Unfortunately this is not true. The only way to install PyAL is to download the <a href="https://bitbucket.org/marcusva/py-al/downloads" rel="nofollow">source</a> and run the setup.py</p>
<pre><code>python setup.py install
</code></pre>
| 0 | 2016-07-25T10:32:38Z | [
"python",
"pycharm",
"python-3.5",
"openal"
] |
Tensorflow - transfer learning implementation (semantic segmentation) | 38,565,497 | <p>I'm working on implementing a CNN architecture (FCN-8s model, with pretrained VGG16 model) for semantic segmentation on my own data (2 classes, therefore, a binary per-pixel classification)</p>
<p>How I intend to go about this is:</p>
<ol>
<li>Load the pre-trained model with weights</li>
<li>Add/remove additional higher layers to convert to FCN</li>
<li>Freeze lower layers of the pre-trained model (to not update during the training phase)</li>
<li>Train the network on specific dataset</li>
</ol>
<p>Assuming this is correct, how do I go about freezing the lower layers on my tensorflow model? (I'm looking for specific implementation details) I had a look at the Inception retraining on TensorFlow tutorial, but I'm not quite sure yet. </p>
<p>This is the workflow I have in mind:</p>
<ol>
<li><p>Run my data through the existing pretrained model, and extract the feature outputs, <em>without</em> training it. (how?) </p></li>
<li><p>Feed these feature outputs into another network containing the higher layers - and go about training it. </p></li>
</ol>
<p>Any suggestions would be helpful!</p>
<p>Else, if I'm wrong, how should I be thinking of this?</p>
<p>UPDATE:</p>
<p>I took up <a href="http://stackoverflow.com/users/2876799/chasep255">chasep255</a>'s suggestion below, and tried to use <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/train.html#stop_gradient" rel="nofollow">tf.stop_gradient</a> so as to "freeze" the lower layers in my model. Clearly, there is something wrong with my implementation. Possible alternatives/suggestions?</p>
<p>The model is built based on the FCN (for semantic segmentation) paper. I extract <code>logits</code> from the model architecture, i.e., my features, that I initially feed directly into a <code>loss</code> function to minimize it with a softmax classifier. (per-pixel classification) <code>deconv_1</code> is my logits tensor, of shape <code>[batch, h, w, num_classes] = [1, 750, 750, 2]</code> Implementation:</p>
<pre><code>logits = vgg_fcn.deconv_1
stopper = tf.stop_gradient(logits, 'stop_gradients')
loss = train_func.loss(stopper, labels_placeholder, 2)
with tf.name_scope('Optimizer'):
train_op = train_func.training(loss, FLAGS.learning_rate)
with tf.name_scope('Accuracy'):
eval_correct = train_func.accuracy_eval(logits, labels_placeholder)
accuracy_summary = tf.scalar_summary('Accuracy', eval_correct)
</code></pre>
<p>I then run these Graph operations as below:</p>
<pre><code>_, acc, loss_value = sess.run([train_op,eval_correct, loss], feed_dict=feed_dict)
</code></pre>
<p>When I run the training cycle thus, there is no optimization of the loss value, most definitely because of how I've introduced the <code>tf.stop_gradient</code> Op. </p>
<p>For more details, my loss function below:</p>
<pre><code>def loss(logits, labels, num_classes):
logits = tf.reshape(logits, [-1, num_classes])
#epsilon = tf.constant(value=1e-4)
#logits = logits + epsilon
labels = tf.to_int64(tf.reshape(labels, [-1]))
print ('shape of logits: %s' % str(logits.get_shape()))
print ('shape of labels: %s' % str(labels.get_shape()))
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, labels, name='Cross_Entropy')
cross_entropy_mean = tf.reduce_mean(cross_entropy, name='xentropy_mean')
tf.add_to_collection('losses', cross_entropy_mean)
loss = tf.add_n(tf.get_collection('losses'), name='total_loss')
return loss
</code></pre>
| 0 | 2016-07-25T10:36:55Z | 38,568,258 | <p>You could just pass the output of the pretrained model into sess.run(pretrained_output, ...) and capture the output of the pretrained model. After you save the output you could then feed it into your model. In this case the optimizer would not be able to propagate the gradients to the pretrained model. </p>
<p>You could also attach the pre trained model to you model normally and then pass the pretrained output through tf.stop_graidents() which would prevent the optimizer from propagating the gradients back into the pretrained model.</p>
<p>Finally, you could just go through all the variables in the pretrained model and remove them from the list of trainable variables.</p>
| 1 | 2016-07-25T12:49:43Z | [
"python",
"tensorflow",
"image-segmentation",
"pre-trained-model"
] |
Pandas: European style date_range | 38,565,592 | <p>I am trying to generate <code>date_range</code> in European style <code>dd/mm/yyyy</code></p>
<pre><code>import pandas as pd
rng = pd.date_range(start = '1/09/2016', periods = 10, dayfirst = True)
</code></pre>
<p>The output is as follows:</p>
<pre><code>DatetimeIndex(['2016-01-09', '2016-01-10', '2016-01-11', '2016-01-12',
'2016-01-13', '2016-01-14', '2016-01-15', '2016-01-16',
'2016-01-17', '2016-01-18'],
dtype='datetime64[ns]', freq='D')
</code></pre>
<p>And I get the same output without <code>dayfirst</code> argument.</p>
<p>What am I doing wrong?</p>
| 1 | 2016-07-25T10:40:56Z | 38,565,644 | <p>You can use only <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.strftime.html" rel="nofollow"><code>DatetimeIndex.strftime</code></a>, but lost <code>DatetimeIndex</code> and get <code>list</code> of <code>strings</code>:</p>
<pre><code>print (rng.strftime('%d/%m/%Y'))
['09/01/2016' '10/01/2016' '11/01/2016' '12/01/2016' '13/01/2016'
'14/01/2016' '15/01/2016' '16/01/2016' '17/01/2016' '18/01/2016']
</code></pre>
<p>EDIT by comment:</p>
<p>If need daily frequency, add parameter <code>freq</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html" rel="nofollow"><code>date_range</code></a> and convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> <code>date</code>:</p>
<pre><code>import pandas as pd
rng = pd.date_range(start = pd.to_datetime('1/09/2016', dayfirst = True),
periods = 10, freq = 'D')
print (rng)
DatetimeIndex(['2016-09-01', '2016-09-02', '2016-09-03', '2016-09-04',
'2016-09-05', '2016-09-06', '2016-09-07', '2016-09-08',
'2016-09-09', '2016-09-10'],
dtype='datetime64[ns]', freq='D')
</code></pre>
| 0 | 2016-07-25T10:43:42Z | [
"python",
"python-2.7",
"pandas",
"date-range"
] |
Boolean expression is producing a "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" | 38,565,606 | <p>When running the following code, I get the Error message
"ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" </p>
<pre><code>import random
import numpy as np
nx, ny = (32, 32)
xaxis = np.linspace(-310, 310, nx)
yaxis = np.linspace(-310, 310, ny)
xys = np.dstack(np.meshgrid(xaxis, yaxis)).reshape(-1, 2)
oris = random.randint (0, 180)
random_ori=oris
absX = abs(xys[:,0])
absY = abs(xys[:,1])
x_rand=(random.randint (0, 220))
y_rand=(random.randint (0, 220))
width=40
height=80
patch = (x_rand <= absX < x_rand + width) * (y_rand <= absY < y_rand + height)
oris[patch] = random_ori + 30
</code></pre>
<p>The problem seems to be due to the boolean expression: </p>
<pre><code>patch = (x_rand <= absX < x_rand + width) * (y_rand <= absY < y_rand + height)
</code></pre>
<p>As the error message suggests, I have tried using <code>.any()</code> and <code>.all()</code>, but the same error message appears. </p>
<p>I can't use <code>np.logical_and</code> or <code>np.logical_or</code> either as I am not working with a numpy array. </p>
<p>Would anyone know why <code>.any()</code> and <code>.all()</code> does not fix the problem, and what I can do to fix it? </p>
<p>Thanks.</p>
| 0 | 2016-07-25T10:41:44Z | 38,568,944 | <p>I think your problem is that absX has a bunch of numbers and x_rand+width only is one. Your x_rand <= absX returns an array. Apply np.all (or any) to that, and then the test against x_rand + width, e.g. <code>np.all(x_rand <= absX) < x_rand+width</code>.</p>
| 1 | 2016-07-25T13:22:07Z | [
"python",
"numpy",
"boolean-expression"
] |
Python: pause function but not whole program | 38,565,613 | <p>I have two function, which generate random integer, and sleep for the given interval. However, I would like to sleep those two functions independently, while <code>time.sleep()</code> pauses the whole Python program. </p>
<pre><code>def fun1():
interval1 = random.randint(2,800)
time.sleep(interval1)
# do other things
def fun2():
interval2 = random.randint(1, 999)
time.sleep(interval2)
# do other things, different than in fun2
</code></pre>
<p>How I can sleep a given function, such that when <code>fun1</code> is paused, <code>fun2</code> still is doing their thing as long as the <code>time.sleep(interval2)</code> is not called?</p>
| 1 | 2016-07-25T10:42:04Z | 38,565,796 | <p>Simply do like this:</p>
<pre><code>from threading import Thread
thread1 = Thread(target=fun1)
thread2 = Thread(target=fun2)
thread1.start()
thread2.start()
</code></pre>
<p>This will start two threads which are independent of the main thread, calling <code>fun1</code> and <code>fun2</code> respectively.</p>
<p>Example:</p>
<pre><code>from threading import Thread
import random
import time
starttime = time.time()
def fun1():
interval1 = random.randint(1,5)
time.sleep(interval1)
print "%d sec: Fun1" % (time.time() - starttime)
def fun2():
interval2 = random.randint(1,5)
time.sleep(interval2)
print "%d sec: Fun2" % (time.time() - starttime)
thread1 = Thread(target=fun1)
thread2 = Thread(target=fun2)
thread1.start()
thread2.start()
print "Still doing things!"
</code></pre>
<p>Output:</p>
<pre><code>Still doing things!
2 sec: Fun2
4 sec: Fun1
</code></pre>
<p>As you can see, the functions are ran but the code still continues executing the print statement after the threads.</p>
| 1 | 2016-07-25T10:50:54Z | [
"python",
"multithreading",
"python-2.7",
"sleep"
] |
Python: pause function but not whole program | 38,565,613 | <p>I have two function, which generate random integer, and sleep for the given interval. However, I would like to sleep those two functions independently, while <code>time.sleep()</code> pauses the whole Python program. </p>
<pre><code>def fun1():
interval1 = random.randint(2,800)
time.sleep(interval1)
# do other things
def fun2():
interval2 = random.randint(1, 999)
time.sleep(interval2)
# do other things, different than in fun2
</code></pre>
<p>How I can sleep a given function, such that when <code>fun1</code> is paused, <code>fun2</code> still is doing their thing as long as the <code>time.sleep(interval2)</code> is not called?</p>
| 1 | 2016-07-25T10:42:04Z | 38,565,999 | <p>Try this:</p>
<pre><code>from multiprocessing import Process
def fun1():
interval1 = random.randint(2,800)
time.sleep(interval1)
# do other things
def fun2():
interval2 = random.randint(1, 999)
time.sleep(interval2)
# do other things
proc1 = Process(target=fun1)
proc2 = Process(target=fun2)
proc1.start()
proc2.start()
proc1.join()
proc2.join()
</code></pre>
<p>This will start new Python processes using <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow"><code>multiprocessing</code></a> to run <code>fun1()</code> and <code>fun2()</code> in parallel. The <code>join()</code> calls will block in the main (parent) process until <code>proc1</code> and <code>proc2</code> are complete.</p>
<p>Unfortunately, due to the <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">Global Interpreter Lock</a>, the <a href="https://docs.python.org/2/library/threading.html" rel="nofollow"><code>threading</code></a> module doesn't help performance much. But if your functions are mostly just waiting, <code>Thread</code>s can be appropriate.</p>
| 1 | 2016-07-25T11:01:19Z | [
"python",
"multithreading",
"python-2.7",
"sleep"
] |
How to place ListBox object at text cursor position | 38,565,617 | <p>I have a code editor, that can autocomplete and give hints of code like the picture below</p>
<p><a href="http://i.stack.imgur.com/2O9bI.png" rel="nofollow"><img src="http://i.stack.imgur.com/2O9bI.png" alt="Example picture"></a></p>
<p>I was able to create a list of Autocompletion words and was able to filter down accordingly to what the user types in. I decided to put it in a ListBox widget, with a scroll bar. But how can I position it like the photo below</p>
<p>Here's my code:</p>
<pre><code>from tkinter import *
root=Tk()
text=Text(root)
text.pack()
...#Filtering part
l= Listbox(root,listvariable=finalList )#The list after being filtered
...#How to position it like the picture
root.mainloop()
</code></pre>
| 0 | 2016-07-25T10:42:09Z | 38,579,296 | <p>The winconfig_event function in IDLE's AutoCompleteWindow / autocomplete_w (pre3.6 / current 3.6) module has this code.</p>
<pre><code> text = self.widget
text.see(self.startindex)
x, y, cx, cy = text.bbox(self.startindex)
acw = self.autocompletewindow
acw_width, acw_height = acw.winfo_width(), acw.winfo_height()
text_width, text_height = text.winfo_width(), text.winfo_height()
new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width))
new_y = text.winfo_rooty() + y
if (text_height - (y + cy) >= acw_height # enough height below
or y < acw_height): # not enough height above
# place acw below current line
new_y += cy
else:
# place acw above current line
new_y -= acw_height
acw.wm_geometry("+%d+%d" % (new_x, new_y))
</code></pre>
<p>I have not really read it, because it does what it is supposed to do. It puts the top line of the popup on the line below the cursor line or the bottom line on the line above. It appears from your image that you might want to adjust the x position.</p>
| 0 | 2016-07-26T00:21:33Z | [
"python",
"text",
"tkinter",
"autocomplete",
"listbox"
] |
django api for create data in db | 38,565,706 | <p>every one, I am trying to wrote an django api to create data in db ,here is my </p>
<h3>models.py</h3>
<pre><code>class ProductsTbl(models.Model):
model_number = models.CharField(
max_length=255,
blank=True,
unique=True,
error_messages={
'unique': "é model number å·²ç¶è¢«è¨»åäº ."
}
)
name = models.CharField(max_length=255, blank=True, null=True)
material = models.CharField(max_length=255, blank=True, null=True)
color = models.CharField(max_length=255, blank=True, null=True)
feature = models.TextField(blank=True, null=True)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField(auto_now=True)
release = models.DateTimeField(blank=True, null=True)
twtime = models.DateTimeField(blank=True, null=True)
hktime = models.DateTimeField(blank=True, null=True)
shtime = models.DateTimeField(blank=True, null=True)
jptime = models.DateTimeField(blank=True, null=True)
suggest = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
cataloggroup = models.ManyToManyField(CatalogGroup)
place = models.ManyToManyField(Place)
scale = models.ManyToManyField(Scale)
slug = models.SlugField(unique=True)
user = models.ForeignKey(User, blank=True, null=True)
useredit = models.CharField(max_length=32, blank=True, null=True)
image = models.ImageField(upload_to=get_imagep_Product, blank=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
return super(ProductsTbl, self).save(*args, **kwargs)
</code></pre>
<p>the views.py I can create data from form ok </p>
<h3>views.py</h3>
<pre><code>def create_thing(request):
form_class = ProductsTblForm
# if we're coming from a submitted form, do this
if request.method == 'POST':
# grab the data from the submitted form and apply to # the form
form = form_class(request.POST, request.FILES)
if form.is_valid():
# create an instance but do not save yet
thing = form.save(commit=False)
# set the additional details
thing.user = request.user
thing.slug = slugify(thing.model_number)
# save the object
thing.save()
# redirect to our newly created thing
return redirect('thing_detail', slug=thing.slug)
# otherwise just create the form
else:
form = form_class()
return render(
request,
'things/create_thing.html',
{'form': form, 'login_user': request.user}
)
</code></pre>
<p>however, when comes to api,,,I jsut fail, here is my </p>
<h3>api/urls.py</h3>
<pre><code>from django.conf.urls import url, include
from . import views
urlpatterns = [
.....
url(r'^productsTbls/create_thing/$',views.api_create_thing,name='api_create_t'),
]
</code></pre>
<h2>api/views.py</h2>
<pre><code>......
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
........
@csrf_exempt
def api_create_thing( user_id ,model_number,name,release,feature, material,image,suggest,description,):
p1 = ProductsTbl(user_id = user_id ,model_number = model_number,slug = model_number ,name = name ,release = release ,feature = feature, material = material ,image=image,suggest = suggest,description = description )
p1.save()
return redirect('/api/productsTbls/')
</code></pre>
<p>here is my error message </p>
<p><a href="http://i.stack.imgur.com/8UASd.png" rel="nofollow"><img src="http://i.stack.imgur.com/8UASd.png" alt="enter image description here"></a></p>
<p>thanks for any one who reply to me</p>
| 1 | 2016-07-25T10:47:03Z | 38,602,209 | <p>the <code>api_create</code> method seems to be totally redundant and can be deleted safely. Your urls.py should instead point to the <code>create_thing</code> method in views.py</p>
<pre><code>urlpatterns = [
.....
url(r'^productsTbls/create_thing/$',views.create_thing,name='api_create_t'),
]
</code></pre>
<p>The reason that api_create_thing isnt' needed is because you already have the code to gather the data from the user with a form and save it to db. The second point is that it's not a good idea to use GET method to accept user input. You should always try to use POST (which create_thing) already does.</p>
| 1 | 2016-07-27T01:14:03Z | [
"python",
"django",
"api"
] |
Subset of dictionary keys | 38,565,727 | <p>I've got a python dictionary of the form <code>{'ip1:port1' : <value>, 'ip1:port2' : <value>, 'ip2:port1' : <value>, ...}</code>. Dictionary keys are strings, consisting of ip:port pairs. Values are not important for this task.</p>
<p>I need a list of <code>ip:port</code> combinations with unique IP addresses, ports can be any of those that appear among original keys. For example above, two variants are acceptable: <code>['ip1:port1', ip2:port1']</code> and <code>['ip1:port2', ip2:port1']</code>.</p>
<p>What is the most pythonic way for doing it?</p>
<p>Currently my solution is</p>
<pre><code>def get_uniq_worker_ips(workers):
wip = set(w.split(':')[0] for w in workers.iterkeys())
return [[worker for worker in workers.iterkeys() if worker.startswith(w)][0] for w in wip]
</code></pre>
<p>I don't like it, because it creates additional lists and then discards them.</p>
| 4 | 2016-07-25T10:48:00Z | 38,565,965 | <p>You can use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> to group by same IP addresses:</p>
<pre><code>data = {'ip1:port1' : "value1", 'ip1:port2' : "value2", 'ip2:port1' : "value3", 'ip2:port2': "value4"}
by_ip = {k: list(g) for k, g in itertools.groupby(sorted(data), key=lambda s: s.split(":")[0])}
by_ip
# {'ip1': ['ip1:port1', 'ip1:port2'], 'ip2': ['ip2:port1', 'ip2:port2']}
</code></pre>
<p>Then just pick any one from the different groups of IPs.</p>
<pre><code>{v[0]: data[v[0]] for v in by_ip.values()}
# {'ip1:port1': 'value1', 'ip2:port1': 'value3'}
</code></pre>
<p>Or shorter, making a generator expression for just the first key from the groups:</p>
<pre><code>one_by_ip = (next(g) for k, g in itertools.groupby(sorted(data), key=lambda s: s.split(":")[0]))
{key: data[key] for key in one_by_ip}
# {'ip1:port1': 'value1', 'ip2:port1': 'value3'}
</code></pre>
<p>However, note that <code>groupby</code> requires the input data to be sorted. So if you want to avoid sorting all the keys in the dict, you should instead just use a <code>set</code> of already seen keys. </p>
<pre><code>seen = set()
not_seen = lambda x: not(x in seen or seen.add(x))
{key: data[key] for key in data if not_seen(key.split(":")[0])}
# {'ip1:port1': 'value1', 'ip2:port1': 'value3'}
</code></pre>
<p>This is similar to your solution, but instead of looping the unique keys and finding a matching key in the dict for each, you loop the keys and check whether you've already seen the IP.</p>
| 7 | 2016-07-25T10:59:44Z | [
"python",
"dictionary"
] |
Subset of dictionary keys | 38,565,727 | <p>I've got a python dictionary of the form <code>{'ip1:port1' : <value>, 'ip1:port2' : <value>, 'ip2:port1' : <value>, ...}</code>. Dictionary keys are strings, consisting of ip:port pairs. Values are not important for this task.</p>
<p>I need a list of <code>ip:port</code> combinations with unique IP addresses, ports can be any of those that appear among original keys. For example above, two variants are acceptable: <code>['ip1:port1', ip2:port1']</code> and <code>['ip1:port2', ip2:port1']</code>.</p>
<p>What is the most pythonic way for doing it?</p>
<p>Currently my solution is</p>
<pre><code>def get_uniq_worker_ips(workers):
wip = set(w.split(':')[0] for w in workers.iterkeys())
return [[worker for worker in workers.iterkeys() if worker.startswith(w)][0] for w in wip]
</code></pre>
<p>I don't like it, because it creates additional lists and then discards them.</p>
| 4 | 2016-07-25T10:48:00Z | 38,566,384 | <p>I've changed few characters in my solution and now am satisfied with it.</p>
<pre><code>def get_uniq_worker_ips(workers):
wip = set(w.split(':')[0] for w in workers.iterkeys())
return [next(worker for worker in workers.iterkeys() if worker.startswith(w)) for w in wip]
</code></pre>
<p>Thanks to @Ignacio Vazquez-Abrams and @M.T. for explanations.</p>
| 0 | 2016-07-25T11:19:28Z | [
"python",
"dictionary"
] |
Subset of dictionary keys | 38,565,727 | <p>I've got a python dictionary of the form <code>{'ip1:port1' : <value>, 'ip1:port2' : <value>, 'ip2:port1' : <value>, ...}</code>. Dictionary keys are strings, consisting of ip:port pairs. Values are not important for this task.</p>
<p>I need a list of <code>ip:port</code> combinations with unique IP addresses, ports can be any of those that appear among original keys. For example above, two variants are acceptable: <code>['ip1:port1', ip2:port1']</code> and <code>['ip1:port2', ip2:port1']</code>.</p>
<p>What is the most pythonic way for doing it?</p>
<p>Currently my solution is</p>
<pre><code>def get_uniq_worker_ips(workers):
wip = set(w.split(':')[0] for w in workers.iterkeys())
return [[worker for worker in workers.iterkeys() if worker.startswith(w)][0] for w in wip]
</code></pre>
<p>I don't like it, because it creates additional lists and then discards them.</p>
| 4 | 2016-07-25T10:48:00Z | 38,566,415 | <p>One way to do this is to transform your keys into a custom class that only looks at the IP part of the string when doing an equality test. It also needs to supply an appropriate <code>__hash__</code> method.</p>
<p>The logic here is that the <code>set</code> constructor will "see" keys with the same IP as identical, ignoring the port part in the comparison, so it will avoid adding a key to the set if a key with that IP is already present in the set.</p>
<p>Here's some code that runs on Python 2 or Python 3.</p>
<pre><code>class IPKey(object):
def __init__(self, s):
self.key = s
self.ip, self.port = s.split(':', 1)
def __eq__(self, other):
return self.ip == other.ip
def __hash__(self):
return hash(self.ip)
def __repr__(self):
return 'IPKey({}:{})'.format(self.ip, self.port)
def get_uniq_worker_ips(workers):
return [k.key for k in set(IPKey(k) for k in workers)]
# Test
workers = {
'ip1:port1' : "val",
'ip1:port2' : "val",
'ip2:port1' : "val",
'ip2:port2' : "val",
}
print(get_uniq_worker_ips(workers))
</code></pre>
<p><strong>output</strong></p>
<pre><code>['ip2:port1', 'ip1:port1']
</code></pre>
<p>If you are running Python 2.7 or later, the function can use a set comprehension instead of that generator expression inside the <code>set()</code> constructor call.</p>
<pre><code>def get_uniq_worker_ips(workers):
return [k.key for k in {IPKey(k) for k in workers}]
</code></pre>
<p>The <code>IPKey.__repr__</code> method isn't strictly necessary, but I like to give all my classes a <code>__repr__</code> since it can be handy during development.</p>
<hr>
<p>Here's a much more succinct solution which is very efficient, courtesy of <a href="http://stackoverflow.com/users/1252759/jon-clements">Jon Clements</a>. It builds the desired list via a dictionary comprehension.</p>
<pre><code>def get_uniq_worker_ips(workers):
return list({k.partition(':')[0]:k for k in workers}.values())
</code></pre>
| 4 | 2016-07-25T11:21:03Z | [
"python",
"dictionary"
] |
Switch to vim like editor interactivelly to change a Python string | 38,565,797 | <p>I have the following source code:</p>
<pre><code>import sys, os
import curses
import textwrap
if __name__ == "__main__":
curses.setupterm()
sys.stdout.write(curses.tigetstr('civis'))
os.system("clear")
str = "abcdefghijklmnopqrstuvwxyz" * 10 # only example
for line in textwrap.wrap(str, 60):
os.system("clear")
print "\n" * 10
print line.center(150)
sys.stdin.read(1) # read one character or #TODO
#TODO
# x = getc() # getc() gets one character from keyboard (already done)
# if x == "e": # edit
# updatedString = runVim(line)
# str.replace(line, updatedString)
sys.stdout.write(curses.tigetstr('cnorm'))
</code></pre>
<p>The program moves through the string by 60 characters.
I would like to have editing possibility (in the #TODO place) in case
I want to change the string just displayed.</p>
<p>Is it possible to open a small <code>vim</code> buffer when I press a key? I would make an edit and when I press <code>:w</code> it would update the string. I would like the <code>vim</code> editor not to change the position of the string in the terminal (I'd like it centered).</p>
| 0 | 2016-07-25T10:50:56Z | 38,571,331 | <p><strong>Idea:</strong></p>
<p>Let us choose <code>\o</code> and <code>\w</code> for our purpose.
Keep the cursor on "TO DO" or any other word you like and press <code>\o</code>.
Then, it opens new tab. You can write anything in new buffer and then press <code>\w</code>. It will copy the whole thing and close the buffer and then pastes in the cursor position in current buffer.</p>
<p><strong>Mapping</strong></p>
<pre><code> :nmap \o cw<ESC>:tabnew<CR>
:nmap \w ggvG"wy:tabclose<CR>"wp
</code></pre>
| 0 | 2016-07-25T15:06:48Z | [
"python",
"vim",
"curses"
] |
Switch to vim like editor interactivelly to change a Python string | 38,565,797 | <p>I have the following source code:</p>
<pre><code>import sys, os
import curses
import textwrap
if __name__ == "__main__":
curses.setupterm()
sys.stdout.write(curses.tigetstr('civis'))
os.system("clear")
str = "abcdefghijklmnopqrstuvwxyz" * 10 # only example
for line in textwrap.wrap(str, 60):
os.system("clear")
print "\n" * 10
print line.center(150)
sys.stdin.read(1) # read one character or #TODO
#TODO
# x = getc() # getc() gets one character from keyboard (already done)
# if x == "e": # edit
# updatedString = runVim(line)
# str.replace(line, updatedString)
sys.stdout.write(curses.tigetstr('cnorm'))
</code></pre>
<p>The program moves through the string by 60 characters.
I would like to have editing possibility (in the #TODO place) in case
I want to change the string just displayed.</p>
<p>Is it possible to open a small <code>vim</code> buffer when I press a key? I would make an edit and when I press <code>:w</code> it would update the string. I would like the <code>vim</code> editor not to change the position of the string in the terminal (I'd like it centered).</p>
| 0 | 2016-07-25T10:50:56Z | 38,686,401 | <p>Not exactly: you can't do it that way. Programs generally cannot read what you printed to the screen.</p>
<p>You <em>could</em> make a program which displays text on the screen and (knowing what it wrote) pass that information to an editor. For instance, <code>lynx</code> (an application using curses) displays a formatted HTML page on the screen, and provides a feature which passes the content of a form text-field to an editor, reads the updated file from the editor and redisplays the information in the form.</p>
| 0 | 2016-07-31T17:02:15Z | [
"python",
"vim",
"curses"
] |
Switch to vim like editor interactivelly to change a Python string | 38,565,797 | <p>I have the following source code:</p>
<pre><code>import sys, os
import curses
import textwrap
if __name__ == "__main__":
curses.setupterm()
sys.stdout.write(curses.tigetstr('civis'))
os.system("clear")
str = "abcdefghijklmnopqrstuvwxyz" * 10 # only example
for line in textwrap.wrap(str, 60):
os.system("clear")
print "\n" * 10
print line.center(150)
sys.stdin.read(1) # read one character or #TODO
#TODO
# x = getc() # getc() gets one character from keyboard (already done)
# if x == "e": # edit
# updatedString = runVim(line)
# str.replace(line, updatedString)
sys.stdout.write(curses.tigetstr('cnorm'))
</code></pre>
<p>The program moves through the string by 60 characters.
I would like to have editing possibility (in the #TODO place) in case
I want to change the string just displayed.</p>
<p>Is it possible to open a small <code>vim</code> buffer when I press a key? I would make an edit and when I press <code>:w</code> it would update the string. I would like the <code>vim</code> editor not to change the position of the string in the terminal (I'd like it centered).</p>
| 0 | 2016-07-25T10:50:56Z | 38,761,065 | <pre><code>def runVim(ln):
with tempfile.NamedTemporaryFile(suffix=".txt") as tmp:
tmp.write(ln)
tmp.flush()
call(['vim', '+1', '-c set filetype=txt', tmp.name]) # for centering +1 can be changed
with open(tmp.name, 'r') as f:
lines = f.read()
return lines
...
x = getch()
if x == "e":
updatedString = runVim(line)
str = str.replace(line, updatedString)
print str
...
</code></pre>
| 1 | 2016-08-04T07:29:54Z | [
"python",
"vim",
"curses"
] |
Pandas: replace substring in string | 38,565,849 | <p>I want to replace substring <code>icashier.alipay.com</code> in column in <code>df</code></p>
<pre><code>url
icashier.alipay.com/catalog/2758186/detail.aspx
icashier.alipay.com/catalog/2758186/detail.aspx
icashier.alipay.com/catalog/2758186/detail.aspx
vk.com
</code></pre>
<p>to <code>aliexpress.com</code>.</p>
<p>Desire output</p>
<pre><code>aliexpress.com/catalog/2758186/detail.aspx
aliexpress.com/catalog/2758186/detail.aspx
aliexpress.com/catalog/2758186/detail.aspx
vk.com
</code></pre>
<p>I try <code>df['url'].replace('icashier.alipay.com', 'aliexpress.com', 'inplace=True')</code> but it return <code>empty dataframe</code>.</p>
| 1 | 2016-07-25T10:54:02Z | 38,565,881 | <p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>str.replace</code></a> to replace a substring, <code>replace</code> looks for exact matches unless you pass a regex pattern and param <code>regex=True</code>:</p>
<pre><code>In [25]:
df['url'] = df['url'].str.replace('icashier.alipay.com', 'aliexpress.com')
df['url']
Out[25]:
0 aliexpress.com/catalog/2758186/detail.aspx
1 aliexpress.com/catalog/2758186/detail.aspx
2 aliexpress.com/catalog/2758186/detail.aspx
3 vk.com
Name: url, dtype: object
</code></pre>
| 1 | 2016-07-25T10:55:15Z | [
"python",
"pandas",
"replace",
"dataframe",
"substring"
] |
Pandas: replace substring in string | 38,565,849 | <p>I want to replace substring <code>icashier.alipay.com</code> in column in <code>df</code></p>
<pre><code>url
icashier.alipay.com/catalog/2758186/detail.aspx
icashier.alipay.com/catalog/2758186/detail.aspx
icashier.alipay.com/catalog/2758186/detail.aspx
vk.com
</code></pre>
<p>to <code>aliexpress.com</code>.</p>
<p>Desire output</p>
<pre><code>aliexpress.com/catalog/2758186/detail.aspx
aliexpress.com/catalog/2758186/detail.aspx
aliexpress.com/catalog/2758186/detail.aspx
vk.com
</code></pre>
<p>I try <code>df['url'].replace('icashier.alipay.com', 'aliexpress.com', 'inplace=True')</code> but it return <code>empty dataframe</code>.</p>
| 1 | 2016-07-25T10:54:02Z | 38,565,899 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>replace</code></a> with <code>dict</code> for replacing and parameters <code>inplace=True</code> and <code>regex=True</code>:</p>
<pre><code>df['url'].replace({'icashier.alipay.com': 'aliexpress.com'}, inplace=True, regex=True)
print (df)
url
0 aliexpress.com/catalog/2758186/detail.aspx
1 aliexpress.com/catalog/2758186/detail.aspx
2 aliexpress.com/catalog/2758186/detail.aspx
3 vk.com
</code></pre>
| 3 | 2016-07-25T10:56:04Z | [
"python",
"pandas",
"replace",
"dataframe",
"substring"
] |
flask query print all record table | 38,565,927 | <p>When i use this script in flask i'll print on the screen one record stored on my database only for 3 data :</p>
<pre><code>app = Flask(__name__)
@app.route("/")
def index():
cur = mysql.connection.cursor()
cur.execute('SELECT temperatura,umidita, orario FROM soggiorno ORDER BY id DESC LIMIT 1;')
results = cur.fetchall()
for row in results:
temperatura = row[0]
umidita = row[1]
orario = row[2]
return render_template('index.php',temperatura=temperatura,umidita=umidita , orario=orario)
return render_template('index.html',templateData=rv)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
</code></pre>
<p>My question is: how can you do a print for all record, in flask, stored on the database? And what to write for the part in html?</p>
| 0 | 2016-07-25T10:57:54Z | 38,566,553 | <p>In your sql remove <code>LIMIT 1</code> like so:</p>
<p><code>
cur.execute('SELECT temperatura,umidita, orario FROM soggiorno ORDER BY id DESC;')
</code></p>
| 0 | 2016-07-25T11:28:16Z | [
"python",
"html",
"mysql",
"flask"
] |
.value_counts() giving truncated results | 38,565,985 | <p>I have an excel file with a single column of multiple words. I am trying to count the frequency of occurrence of each word.
So If I have a list</p>
<pre><code>Labels
a
a
b
b
c
c
c
</code></pre>
<p>The output should be </p>
<pre><code>c : 3
b : 2
a : 2
</code></pre>
<p>I am using the following the code snippet</p>
<pre><code>import pandas as pd
train = pd.read_csv("ani2.csv")
A = train['Labels'].value_counts()
f = open("ani3.csv",'a')
f.write(str(A))
f.close()
</code></pre>
<p>The dataset has about 53000 values and the output I obtained was truncated. The output I obtained was in this format.</p>
<pre><code>z : 1700
y : 1500
x : 1000
...
c : 3
b : 2
a : 2
</code></pre>
<p>The values in middle are missing for some reason and all I obtained was three dots.</p>
| 1 | 2016-07-25T11:00:37Z | 38,566,070 | <p>You're passing <code>str(A)</code></p>
<p>just call <code>to_csv</code> on <code>A</code>:</p>
<pre><code>A = train['Labels'].value_counts()
A.to_csv("ani3.csv",mode='a')
</code></pre>
<p>When you did <code>str(A)</code> you're converting the output, which will be affected by the pandas display options, to a string representation which is why you get <code>...</code>.</p>
<p>You can see the effect here:</p>
<pre><code>In [34]:
df = pd.DataFrame(np.random.randn(100,1), columns=['a'])
str(df['a'].value_counts())
Out[34]:
'-1.115774 1\n-0.196748 1\n-0.193616 1\n-0.197265 1\n 0.745611 1\n 0.766238 1\n-0.263205 1\n 0.542410 1\n-1.930702 1\n-0.913680 1\n 1.150879 1\n 0.213193 1\n-1.245947 1\n-2.610836 1\n 1.482863 1\n 0.430732 1\n-1.290851 1\n-0.962350 1\n-0.160461 1\n 1.895585 1\n 0.923683 1\n-1.206336 1\n 0.454317 1\n 0.293499 1\n-1.289761 1\n-0.191499 1\n 1.311149 1\n 0.380678 1\n 0.964312 1\n-0.703558 1\n ..\n-0.384447 1\n 0.172968 1\n-0.221997 1\n 0.133441 1\n-0.343758 1\n-0.897193 1\n-0.525859 1\n-0.226437 1\n-0.552760 1\n-1.991686 1\n 0.517877 1\n 0.659020 1\n 1.680185 1\n 0.155123 1\n-0.788438 1\n-1.364535 1\n 0.034736 1\n 0.494853 1\n 1.113248 1\n-1.449296 1\n 1.123138 1\n-0.747243 1\n-0.429054 1\n-0.567881 1\n-0.476616 1\n-2.630239 1\n 0.084506 1\n 1.250732 1\n 0.071242 1\n-0.432580 1\nName: a, dtype: int64'
</code></pre>
| 4 | 2016-07-25T11:04:36Z | [
"python",
"pandas"
] |
Pyramid get current user/user id without access to request | 38,566,092 | <p>Is there any way to access current user object or at least id without access to request? Let's say in model?</p>
<p>I use pyramid and SQLAlchemy.</p>
<p>First I thought about Singleton, but I think this may return wrong object when there is more users.</p>
<pre><code>class UserSingleton(object):
user = None
def __new__(cls, user=None):
UserSingleton.user = user
return UserSingleton.user
@classmethod
def get(cls):
return cls.user
</code></pre>
<p>I need this to use with my model, but I can't pass request in here, because this is called by orm event:</p>
<pre><code>@classmethod
def log(cls, description, log_type=None, name=None):
user = ??
audit_log = cls(
user_id=user.id if user else None,
description=description,
type=log_type,
name=name
)
DBSession.add(audit_log)
return audit_log
</code></pre>
| 3 | 2016-07-25T11:05:44Z | 38,569,125 | <p>Ok, found a solution by doing:</p>
<pre><code>from pyramid.threadlocal import get_current_request
request = get_current_request()
</code></pre>
| 3 | 2016-07-25T13:30:15Z | [
"python",
"sqlalchemy",
"pyramid"
] |
Timezone not working properly in Django | 38,566,228 | <p>I want to change timezone in Django, so I read documentation how to do it nad here's what I've got:</p>
<pre><code>#settings.py
TIME_ZONE = 'Europe/Ljubljana'
#models.py #date_time gets filled with "auto_now=True")
date_time = models.DateTimeField(auto_now=True)
</code></pre>
<p>UTC DST offset for given location (Europe/Ljubljana) is +2, while in my db I see timestamp of UTC. So what am I missing?</p>
<p>Or is this working as intended so it gets processed for each request separately (useful for people in different timezones)? But if this is the case, what's the use of setting <code>TIME_ZONE = 'Europe/Ljubljana'</code>?</p>
| 2 | 2016-07-25T11:12:21Z | 38,566,337 | <p>From the <a href="https://docs.djangoproject.com/en/1.9/topics/i18n/timezones/" rel="nofollow">documentation</a></p>
<blockquote>
<p>When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end userâs time zone in templates and forms.</p>
</blockquote>
<p>so the datetime in your DB will always be stored in UTC, but will be displayed using the correct TZ in templates and forms.</p>
<p>To get the date in correct TZ elsewhere, use <code>astimezone()</code>:</p>
<pre><code>>>> from myapp.models import Details
>>> import pytz
>>> d = Details.objects.get(pk=1)
>>> d.added
datetime.datetime(2016, 5, 28, 18, 59, 55, 841193, tzinfo=<UTC>)
>>> localdate = d.added.astimezone(pytz.timezone('Europe/Ljubljana'))
>>> localdate
datetime.datetime(2016, 5, 28, 20, 59, 55, 841193, tzinfo=<DstTzInfo 'Europe/Ljubljana' CEST+2:00:00 DST>)
</code></pre>
| 2 | 2016-07-25T11:17:10Z | [
"python",
"django",
"timezone"
] |
Python3 , OOP : Multiple classes inheritance into single class | 38,566,396 | <p>I am Inheriting from multiple parent classes into a single class. What I am trying to do is make a situation of object data conflict. </p>
<p>I mean if two classes hold a variable with same name and different data, which data will be loaded by Python if that variable comes to picture?</p>
<p>what I did </p>
<pre><code>>>> class pac:
... var=10
... var2=20
...
>>> class cac:
... var3=30
... var2=10
...
>>> pob=pac()
>>> cob=cac()
>>> pob.var
10
>>> pob.var2
20
>>> cob.var2
10
>>> cob.var3
30
>>> class newclass(pac,cac):
... def sum(self):
... sum=self.var+self.var2
... sum2=self.var2+self.var3
... print(sum)
... print(sum2)
...
30
50
>>> nob.var
10
>>> nob.var2
20
>>> nob.var3
30
>>>
</code></pre>
<p>It seems like <code>var2</code> data will consider from parent class : <code>pac</code> instead of <code>cac</code> class. </p>
<p>What needs to be done to make Python consider data from <code>cac</code> instead of <code>pac</code> if same variable name existed with different data? Please do not suggest me to change order of inheritance.</p>
<p>Thank you.</p>
| 0 | 2016-07-25T11:20:06Z | 38,566,686 | <p>Without changing the order of inheritance, your subclass will always get an attribute it can find in the first class, from the first class. If you want to find out what the corresponding value is in the second class, you're going to have to explicitly ask for the second class's value.</p>
<p>In your case, something like</p>
<pre><code>class newclass(pac,cac):
@property
def var2(self):
return cac.var2
</code></pre>
<p>Note that I'm explicitly asking for <code>cac</code>'s var2.</p>
| 1 | 2016-07-25T11:35:25Z | [
"python",
"oop"
] |
Python3 , OOP : Multiple classes inheritance into single class | 38,566,396 | <p>I am Inheriting from multiple parent classes into a single class. What I am trying to do is make a situation of object data conflict. </p>
<p>I mean if two classes hold a variable with same name and different data, which data will be loaded by Python if that variable comes to picture?</p>
<p>what I did </p>
<pre><code>>>> class pac:
... var=10
... var2=20
...
>>> class cac:
... var3=30
... var2=10
...
>>> pob=pac()
>>> cob=cac()
>>> pob.var
10
>>> pob.var2
20
>>> cob.var2
10
>>> cob.var3
30
>>> class newclass(pac,cac):
... def sum(self):
... sum=self.var+self.var2
... sum2=self.var2+self.var3
... print(sum)
... print(sum2)
...
30
50
>>> nob.var
10
>>> nob.var2
20
>>> nob.var3
30
>>>
</code></pre>
<p>It seems like <code>var2</code> data will consider from parent class : <code>pac</code> instead of <code>cac</code> class. </p>
<p>What needs to be done to make Python consider data from <code>cac</code> instead of <code>pac</code> if same variable name existed with different data? Please do not suggest me to change order of inheritance.</p>
<p>Thank you.</p>
| 0 | 2016-07-25T11:20:06Z | 38,566,943 | <p>You could also return a list/tuple of the possible values by using the following code:</p>
<pre><code>@property
def var2(self):
key='var2'
return [getattr(c,key) for c in self.__class__.mro()[1:-1] if hasattr(c,key)]
</code></pre>
<p>The <code>mro</code> method returns a list of classes, the first one will be the callers class followed by parents and lastly the <code>object</code> built-in class.
This code will return a list of values in the order of inheritance.</p>
| 0 | 2016-07-25T11:47:29Z | [
"python",
"oop"
] |
Python3 , OOP : Multiple classes inheritance into single class | 38,566,396 | <p>I am Inheriting from multiple parent classes into a single class. What I am trying to do is make a situation of object data conflict. </p>
<p>I mean if two classes hold a variable with same name and different data, which data will be loaded by Python if that variable comes to picture?</p>
<p>what I did </p>
<pre><code>>>> class pac:
... var=10
... var2=20
...
>>> class cac:
... var3=30
... var2=10
...
>>> pob=pac()
>>> cob=cac()
>>> pob.var
10
>>> pob.var2
20
>>> cob.var2
10
>>> cob.var3
30
>>> class newclass(pac,cac):
... def sum(self):
... sum=self.var+self.var2
... sum2=self.var2+self.var3
... print(sum)
... print(sum2)
...
30
50
>>> nob.var
10
>>> nob.var2
20
>>> nob.var3
30
>>>
</code></pre>
<p>It seems like <code>var2</code> data will consider from parent class : <code>pac</code> instead of <code>cac</code> class. </p>
<p>What needs to be done to make Python consider data from <code>cac</code> instead of <code>pac</code> if same variable name existed with different data? Please do not suggest me to change order of inheritance.</p>
<p>Thank you.</p>
| 0 | 2016-07-25T11:20:06Z | 38,567,236 | <p>You can set self.var2=cac.var2 in the newclass's <strong>init</strong> method:</p>
<pre><code>class newclass(pac, cac):
def __init__(self):
self.var2 = cac.var2
</code></pre>
| 1 | 2016-07-25T12:01:52Z | [
"python",
"oop"
] |
Python/Pandas if statement and index | 38,566,406 | <p>I'm sure there is a simple solution to this problem but I cannot seem to find it. </p>
<p>I am trying to check if an age from a list is in the age column of my dataframe. However, it is only comparing to the index and not the column. </p>
<p>Here is a simplified piece of code from my program:</p>
<pre><code>def findages(data,ages):
for age in ages:
if age in data['age']:
print('yes')
else:
print('no')
</code></pre>
<p>I have also tried this:</p>
<pre><code>def findages(data,ages):
for age in ages:
if age in data.loc[data['age']]:
print('yes')
else:
print('no')
</code></pre>
<p>the dataframe looks like this</p>
<pre><code> age x Lambda L
0 1.258930e+05 0.01 91.0 5.349000e+25
1 1.258930e+05 0.01 94.0 1.188800e+26
2 1.258930e+05 0.01 96.0 1.962700e+26
3 1.258930e+05 0.01 98.0 3.169400e+26
4 1.258930e+05 0.01 100.0 5.010800e+26
</code></pre>
<p>and the list like this:</p>
<pre><code>ages = ([125893.0, 4e7,5e9])
</code></pre>
<p>What am I doing wrong? </p>
| 1 | 2016-07-25T11:20:38Z | 38,566,437 | <p>Use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a>:</p>
<pre><code>np.where(data['age'].isin(ages),'yes','no')
</code></pre>
<p>Sample:</p>
<pre><code>import pandas as pd
import numpy as np
data = pd.DataFrame({'age':[10,20,30]})
ages = [10,30]
print (data)
age
0 10
1 20
2 30
data['new'] = np.where(data['age'].isin(ages),'yes','no')
print (data)
age new
0 10 yes
1 20 no
2 30 yes
</code></pre>
<p>EDIT by sample:</p>
<pre><code>print (data)
age x Lambda L
0 125893.0 0.01 91.0 5.349000e+25
1 125893.0 0.01 94.0 1.188800e+26
2 125893.0 0.01 96.0 1.962700e+26
3 125893.0 0.01 98.0 3.169400e+26
4 125893.0 0.01 100.0 5.010800e+26
ages = ([125893.0, 4e7,5e9])
print (np.where(data['age'].isin(ages),'yes','no'))
['yes' 'yes' 'yes' 'yes' 'yes']
</code></pre>
| 0 | 2016-07-25T11:22:39Z | [
"python",
"function",
"pandas",
"if-statement",
"dataframe"
] |
Python/Pandas if statement and index | 38,566,406 | <p>I'm sure there is a simple solution to this problem but I cannot seem to find it. </p>
<p>I am trying to check if an age from a list is in the age column of my dataframe. However, it is only comparing to the index and not the column. </p>
<p>Here is a simplified piece of code from my program:</p>
<pre><code>def findages(data,ages):
for age in ages:
if age in data['age']:
print('yes')
else:
print('no')
</code></pre>
<p>I have also tried this:</p>
<pre><code>def findages(data,ages):
for age in ages:
if age in data.loc[data['age']]:
print('yes')
else:
print('no')
</code></pre>
<p>the dataframe looks like this</p>
<pre><code> age x Lambda L
0 1.258930e+05 0.01 91.0 5.349000e+25
1 1.258930e+05 0.01 94.0 1.188800e+26
2 1.258930e+05 0.01 96.0 1.962700e+26
3 1.258930e+05 0.01 98.0 3.169400e+26
4 1.258930e+05 0.01 100.0 5.010800e+26
</code></pre>
<p>and the list like this:</p>
<pre><code>ages = ([125893.0, 4e7,5e9])
</code></pre>
<p>What am I doing wrong? </p>
| 1 | 2016-07-25T11:20:38Z | 38,566,551 | <h1>DataFrame column access return a Series</h1>
<p>In your code, <code>data['age']</code> is returning a series of columns <code>age</code>. In this case the <code>in</code> operator will compare against the index. To compare against the values in the series use the <code>.values</code> attribute to get an array of the series values.</p>
<h2>By example:</h2>
<pre><code>import pandas as pd
df = pd.DataFrame({'age':[33, 34], 'pet':['Dog', 'Cat']}, index=['Bob', 'Mary'])
ages = [5, 33, 67]
def findages(data, ages):
for age in ages:
if age in data['age'].values:
print('yes')
else:
print('no')
findages(df, ages)
</code></pre>
<hr>
<pre><code>no
yes
no
</code></pre>
| 1 | 2016-07-25T11:28:12Z | [
"python",
"function",
"pandas",
"if-statement",
"dataframe"
] |
AttributeError: module 'pandas' has no attribute 'to_csv' | 38,566,430 | <p>I took some rows from csv file like this </p>
<pre><code>pd.DataFrame(CV_data.take(5), columns=CV_data.columns)
</code></pre>
<p>and performed some functions on it. now i want to save it in csv again but it is giving error <code>module 'pandas' has no attribute 'to_csv'</code>
I am trying to save it like this </p>
<pre><code>pd.to_csv(CV_data, sep='\t', encoding='utf-8')
</code></pre>
<p>here is my full code. how can i save my resulting data in csv or excel?</p>
<pre><code> # Disable warnings, set Matplotlib inline plotting and load Pandas package
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
import pandas as pd
pd.options.display.mpl_style = 'default'
CV_data = sqlContext.read.load('Downloads/data/churn-bigml-80.csv',
format='com.databricks.spark.csv',
header='true',
inferSchema='true')
final_test_data = sqlContext.read.load('Downloads/data/churn-bigml-20.csv',
format='com.databricks.spark.csv',
header='true',
inferSchema='true')
CV_data.cache()
CV_data.printSchema()
pd.DataFrame(CV_data.take(5), columns=CV_data.columns)
from pyspark.sql.types import DoubleType
from pyspark.sql.functions import UserDefinedFunction
binary_map = {'Yes':1.0, 'No':0.0, True:1.0, False:0.0}
toNum = UserDefinedFunction(lambda k: binary_map[k], DoubleType())
CV_data = CV_data.drop('State').drop('Area code') \
.drop('Total day charge').drop('Total eve charge') \
.drop('Total night charge').drop('Total intl charge') \
.withColumn('Churn', toNum(CV_data['Churn'])) \
.withColumn('International plan', toNum(CV_data['International plan'])) \
.withColumn('Voice mail plan', toNum(CV_data['Voice mail plan'])).cache()
final_test_data = final_test_data.drop('State').drop('Area code') \
.drop('Total day charge').drop('Total eve charge') \
.drop('Total night charge').drop('Total intl charge') \
.withColumn('Churn', toNum(final_test_data['Churn'])) \
.withColumn('International plan', toNum(final_test_data['International plan'])) \
.withColumn('Voice mail plan', toNum(final_test_data['Voice mail plan'])).cache()
pd.DataFrame(CV_data.take(5), columns=CV_data.columns)
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.tree import DecisionTree
def labelData(data):
# label: row[end], features: row[0:end-1]
return data.map(lambda row: LabeledPoint(row[-1], row[:-1]))
training_data, testing_data = labelData(CV_data).randomSplit([0.8, 0.2])
model = DecisionTree.trainClassifier(training_data, numClasses=2, maxDepth=2,
categoricalFeaturesInfo={1:2, 2:2},
impurity='gini', maxBins=32)
print (model.toDebugString())
print ('Feature 12:', CV_data.columns[12])
print ('Feature 4: ', CV_data.columns[4] )
from pyspark.mllib.evaluation import MulticlassMetrics
def getPredictionsLabels(model, test_data):
predictions = model.predict(test_data.map(lambda r: r.features))
return predictions.zip(test_data.map(lambda r: r.label))
def printMetrics(predictions_and_labels):
metrics = MulticlassMetrics(predictions_and_labels)
print ('Precision of True ', metrics.precision(1))
print ('Precision of False', metrics.precision(0))
print ('Recall of True ', metrics.recall(1))
print ('Recall of False ', metrics.recall(0))
print ('F-1 Score ', metrics.fMeasure())
print ('Confusion Matrix\n', metrics.confusionMatrix().toArray())
predictions_and_labels = getPredictionsLabels(model, testing_data)
printMetrics(predictions_and_labels)
CV_data.groupby('Churn').count().toPandas()
stratified_CV_data = CV_data.sampleBy('Churn', fractions={0: 388./2278, 1: 1.0}).cache()
stratified_CV_data.groupby('Churn').count().toPandas()
pd.to_csv(CV_data, sep='\t', encoding='utf-8')
</code></pre>
| -2 | 2016-07-25T11:22:05Z | 38,566,460 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow"><code>to_csv</code></a> is a method of a <code>DataFrame</code> object, not of the <code>pandas</code> module. </p>
<pre><code>df = pd.DataFrame(CV_data.take(5), columns=CV_data.columns)
# whatever manipulations on df
df.to_csv(...)
</code></pre>
<p>You also have a line <code>pd.DataFrame(CV_data.take(5), columns=CV_data.columns)</code> in your code. </p>
<p>This line creates a dataframe and then discards it. Even if you were successfully calling <code>to_csv</code>, none of your changes to <code>CV_data</code> would have been reflected in that dataframe (and therefore in the outputed csv file).</p>
| 2 | 2016-07-25T11:23:43Z | [
"python",
"csv",
"pandas",
"export-to-csv",
"spark-dataframe"
] |
How to use Airbnb Caravel Time Filter | 38,566,435 | <p>Recently, I use Caravel to do Log Analytics Dashboard, and I think Caravel Time filter is not good to use, for example:</p>
<ul>
<li>I can't display all data without Time filter</li>
<li>Time filter is too rough, so I can't get data within two datetime</li>
</ul>
<p>Is any way can resolve these problem? Thank you very much!</p>
| 0 | 2016-07-25T11:22:29Z | 38,626,662 | <p>I found the answer: </p>
<p>In Time Filter, you can just type 1 day, 2 day or a date string in Since and Until field</p>
| 0 | 2016-07-28T03:35:37Z | [
"python",
"airbnb"
] |
NameError: name 'View' is not defined in views.py | 38,566,446 | <p>I am trying to define a class in views.py which is inheriting generic view. The code is as follows. On running server I get the error that
class UserFormView(View):
NameError: name 'View' is not defined </p>
<p>although I have imported generic. Please let me know the reason.</p>
<pre><code>from django.views import generic
from django.utils import timezone
from django.shortcuts import render, get_object_or_404,render_to_response,redirect
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth import authenticate,login
from django.core.context_processors import csrf
from .forms import UserForm
# Create your views here.
def home(request):
return render(request, 'fosssite/home.html')
def login(request):
c={}
c.update(csrf(request))
return render_to_response('fosssite/login.html',c)
class UserFormView(View):
form_class=UserForm
template_name='fosssite/signup.html'
def get(self,request):
form=self.form_class(None)
return render(request,self.template_name,{'form':form})
#validate by forms of django
def post(self,request):
form=self.form_class(request.POST)
if form.is_valid():
# not saving to database only creating object
user=form.save(commit=False)
#normalized data
username=form.cleaned_data['username']
password=form.cleaned_data['password']
#not as plain data
user.set_password(password)
user.save() #saved to database
def auth_view(request):
username=request.POST.get('username', '')
password=request.POST.get('password', '')
user=auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
return HttpResponseRedirect('/loggedin')#url in brackets
else:
return HttpResponseRedirect('/invalid')
def loggedin(request):
return render_to_response('fosssite/loggedin.html',{'fullname':request.user.username})
def logout(request):
auth.logout(request)
return render_to_response('fosssite/logout.html')
def invalid_login(request):
return render_to_response('fosssite/invalid_login.html')
`
</code></pre>
| 0 | 2016-07-25T11:23:09Z | 38,566,482 | <p>The <code>View</code> name needs to be <em>imported</em>. Add the following import statement:</p>
<pre><code>from django.views.generic import View
</code></pre>
<p>Or use the already imported <code>generic</code> module in </p>
<pre><code>class UserFormView(generic.View)
# ^
</code></pre>
| 2 | 2016-07-25T11:24:58Z | [
"python",
"django"
] |
NameError: name 'View' is not defined in views.py | 38,566,446 | <p>I am trying to define a class in views.py which is inheriting generic view. The code is as follows. On running server I get the error that
class UserFormView(View):
NameError: name 'View' is not defined </p>
<p>although I have imported generic. Please let me know the reason.</p>
<pre><code>from django.views import generic
from django.utils import timezone
from django.shortcuts import render, get_object_or_404,render_to_response,redirect
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth import authenticate,login
from django.core.context_processors import csrf
from .forms import UserForm
# Create your views here.
def home(request):
return render(request, 'fosssite/home.html')
def login(request):
c={}
c.update(csrf(request))
return render_to_response('fosssite/login.html',c)
class UserFormView(View):
form_class=UserForm
template_name='fosssite/signup.html'
def get(self,request):
form=self.form_class(None)
return render(request,self.template_name,{'form':form})
#validate by forms of django
def post(self,request):
form=self.form_class(request.POST)
if form.is_valid():
# not saving to database only creating object
user=form.save(commit=False)
#normalized data
username=form.cleaned_data['username']
password=form.cleaned_data['password']
#not as plain data
user.set_password(password)
user.save() #saved to database
def auth_view(request):
username=request.POST.get('username', '')
password=request.POST.get('password', '')
user=auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
return HttpResponseRedirect('/loggedin')#url in brackets
else:
return HttpResponseRedirect('/invalid')
def loggedin(request):
return render_to_response('fosssite/loggedin.html',{'fullname':request.user.username})
def logout(request):
auth.logout(request)
return render_to_response('fosssite/logout.html')
def invalid_login(request):
return render_to_response('fosssite/invalid_login.html')
`
</code></pre>
| 0 | 2016-07-25T11:23:09Z | 38,566,573 | <p>You need to either import <code>View</code> explicitly:</p>
<pre><code>from django.views.generic import View
</code></pre>
<p>or refer to it as <code>generic.View</code>:</p>
<pre><code>class UserFormView(generic.View):
# ...
</code></pre>
| 1 | 2016-07-25T11:29:29Z | [
"python",
"django"
] |
Flask Blueprint url_for BuildError when using add_url_rule | 38,566,481 | <p>I am stuck in blueprint when I am trying to use flask blueprint in the way of <code>add_url_rule</code></p>
<p>Here's my flask project structure:</p>
<pre><code>myapp
... __init__.py
... app.py
... model
... static
... views
...... main.py
... templates
...... base.html
...... results.html
</code></pre>
<p>In main.pyï¼Here is my code:</p>
<pre><code>from flask import Flask, url_for, Blueprint
main_bp = Blueprint('main', __name__)
def home():
return redirect(url_for('main.results'))
def results():
# some code
return render_template('result.html')
</code></pre>
<p>and In my app.py, Here's the code:</p>
<pre><code>from myapp.views.main import main_bp
app.register_blueprint(main_bp)
app.add_url_rule('/', view_func=main.home)
app.add_url_rule('/results', view_func=main.results, methods=['POST', 'GET'])
</code></pre>
<p>when I am visiting the index page, I always got the following error message:</p>
<pre><code>Traceback (most recent call last):
File "/Users/deamon/venv/src/staticngclient/staticng_client/middlewares/wsgi.py", line 25, in __call__
return app(environ, start_response)
File "/Users/deamon/venv/src/daeprofiling/dae_profiling/middleware.py", line 24, in __call__
return self.app(environ, start_response)
File "/Users/deamon/venv/src/doubancommonlib/douban/common/middleware/content_filter.py", line 18, in __call__
app_iter = self.application(environ, response.start_response)
File "/Users/deamon/dae/app/web.py", line 77, in __call__
return handler(environ, start_response)
File "/Users/deamon/Projects/dae/dae/handlers/__init__.py", line 65, in __call__
return self.app(environ, start_response)
File "/Users/deamon/Projects/dae/dae/handlers/web.py", line 46, in __call__
return self._app(*a, **kw)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/deamon/kiwi/views/main.py", line 19, in home
return redirect(url_for('main.results'))
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/helpers.py", line 312, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/app.py", line 1641, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/Users/deamon/venv/lib/python2.7/site-packages/flask/helpers.py", line 305, in url_for
force_external=external)
File "/Users/deamon/venv/lib/python2.7/site-packages/werkzeug/routing.py", line 1678, in build
raise BuildError(endpoint, values, method)
BuildError: ('main.results', {}, None)
</code></pre>
<p>also, in mye templates, such as base.html or results.html, when I am using </p>
<pre><code> <a class="navbar-brand" href="{{ url_for('main.home') }}">kiwi</a>
</code></pre>
<p>the same error occurs.</p>
<p>Can someone help?</p>
| 0 | 2016-07-25T11:24:51Z | 38,567,627 | <p>Ok, so the first problem I see that is even though you're trying to use blueprint you're not actually doing anything with it. </p>
<p>Yeah, in the line <code>main_bp = Blueprint('main', __name__)</code> you create it, but after that you don't actually register any url endpoints for it and instead try to do it via imports in the main app. </p>
<p>Because you don't actually register the endpoints <em>in the blueprint</em> but try to create redirect for it by calling <code>main.results</code> with prefix to the blueprint 'main' your url_for function fails. </p>
<p>This is how your code would look with proper use of blueprints</p>
<p>blueprint</p>
<pre><code>from flask import Flask, url_for, Blueprint
main_bp = Blueprint('main', __name__)
@main_bp.route('/')
def home():
return redirect(url_for('main.results'))
@main_bp.route('/results')
def results():
# some code
return render_template('result.html')
</code></pre>
<p>and app.py</p>
<pre><code>from myapp.views.main import main_bp
app.register_blueprint(main_bp)
</code></pre>
<p>Or if you want to use <code>add_url_rule</code> (which works <strong>exactly</strong> like the decorator) just use <code>main_bp.add_url_rule(...)</code> in the blueprint file.</p>
<p><strong>Working example with add_url_rule</strong></p>
<p>Blueprint file</p>
<pre><code>from flask import Flask, url_for, Blueprint, redirect, render_template
main_bp = Blueprint('main', __name__)
def home():
return redirect(url_for('main.results'))
def results():
# some code
return 'some results'
main_bp.add_url_rule('/', view_func=home)
main_bp.add_url_rule('/results', view_func=results)
</code></pre>
<p>app file</p>
<pre><code>from flask import Flask
import bp
app = Flask(__name__)
app.register_blueprint(bp.main_bp)
if __name__ == '__main__':
app.run()
</code></pre>
| 1 | 2016-07-25T12:20:56Z | [
"python",
"flask",
"blueprint",
"url-for"
] |
flask template setting id for divs in a for loop | 38,566,525 | <p>In the html file:</p>
<pre><code>{% for elems in result2 %}
<div style="border:1px solid green;">
{% for elem in elems %}
{{ elem }}
{%endfor%}
</div><br>
{%endfor%}
</code></pre>
<p>I want to give <code>id</code> to <code><div></code> and the id should be set to <code>{{ elem.1 }}</code></p>
<p>As you see here, each row will be printed in separate div, so here we would have 3 dives that the id of the first div would be 1 as the <code>{{ elem.1 }}</code> of the first row is 1, and ....</p>
<pre><code>(1, 1, 'text') (2, 1, 'text') (3, 1, 'text') (4, 1, 'text')
(5, 2, 'text') (6, 2, 'text')
(7, 3, 'text') (8, 3, 'text')
</code></pre>
<p>but the open div tag comes before printing <code>{{ elem }}</code> ro after <code>{%endfor%}</code>, so how can I do that?</p>
| -1 | 2016-07-25T11:26:54Z | 38,567,213 | <p>I think you could just use <code>id="{{ elems[0][1] }}"</code></p>
| 1 | 2016-07-25T12:00:59Z | [
"python",
"templates",
"for-loop",
"flask"
] |
flask template setting id for divs in a for loop | 38,566,525 | <p>In the html file:</p>
<pre><code>{% for elems in result2 %}
<div style="border:1px solid green;">
{% for elem in elems %}
{{ elem }}
{%endfor%}
</div><br>
{%endfor%}
</code></pre>
<p>I want to give <code>id</code> to <code><div></code> and the id should be set to <code>{{ elem.1 }}</code></p>
<p>As you see here, each row will be printed in separate div, so here we would have 3 dives that the id of the first div would be 1 as the <code>{{ elem.1 }}</code> of the first row is 1, and ....</p>
<pre><code>(1, 1, 'text') (2, 1, 'text') (3, 1, 'text') (4, 1, 'text')
(5, 2, 'text') (6, 2, 'text')
(7, 3, 'text') (8, 3, 'text')
</code></pre>
<p>but the open div tag comes before printing <code>{{ elem }}</code> ro after <code>{%endfor%}</code>, so how can I do that?</p>
| -1 | 2016-07-25T11:26:54Z | 38,567,227 | <p>The data structure being used for <code>result2</code> is unclear, but assuming that it is a list of lists of tuples you should be able to reach the second element of the first tuple of each list with <code>elems.0.1</code>. In the template:</p>
<pre><code>{% for elems in result2 %}
<div id="{{ elems.0.1 }}"" style="border:1px solid green;">
{% for elem in elems %}
{{ elem }}
{%endfor%}
</div><br>
{%endfor%}
</code></pre>
<p>Here I am assuming that <code>result2</code> is something like this:</p>
<pre><code>>>> result2 = [[(1, 1, 'text'), (2, 1, 'text'), (3, 1, 'text'), (4, 1, 'text')],
[(5, 2, 'text'), (6, 2, 'text')],
[(7, 3, 'text'), (8, 3, 'text')]]
>>> print(render_template_string(template, result2=result2))
<div id="1" style="border:1px solid green;">
(1, 1, 'text')
(2, 1, 'text')
(3, 1, 'text')
(4, 1, 'text')
</div><br>
<div id="2" style="border:1px solid green;">
(5, 2, 'text')
(6, 2, 'text')
</div><br>
<div id="3" style="border:1px solid green;">
(7, 3, 'text')
(8, 3, 'text')
</div><br>
</code></pre>
| 1 | 2016-07-25T12:01:37Z | [
"python",
"templates",
"for-loop",
"flask"
] |
Django testing: AssertionError: The form 'form' was not used to render the response | 38,566,704 | <p>So I'm writing a test to check for the occurrence of Validation Errors in my Form.</p>
<p>In doing so I'm getting the following error:</p>
<pre><code>======================================================================
FAIL: test_start_date_before_end_date_errors (reports.tests.ScheduleValidation)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/jwe/piesup2/reports/tests.py", line 61, in test_start_date_before_end_date_errors
self.assertFormError(response, 'form', None, 'End Date Must Be Greater Than Start Date')
File "/home/jwe/piesup2/venv/lib/python3.4/site-packages/django/test/testcases.py", line 467, in assertFormError
" response" % form)
AssertionError: The form 'form' was not used to render the response
----------------------------------------------------------------------
</code></pre>
<p>The validation error I'm specifically checking for is raised in models.py inside the <code>clean()</code> method</p>
<pre><code>class Schedule(models.Model)
...
...
def clean(self):
if self.start_date and self.end_date:
# Ensure that the end_date occurs after the start_date
if self.end_date <= self.start_date:
err = "End Date Must Be Greater Than Start Date"
raise ValidationError(err)
</code></pre>
<p>The Generic CreateView I am testing looks as follows:</p>
<pre><code>class ScheduleCreate(SuccessMessageMixin, FetchURLMixin, CreateView):
model = Schedule
form_class = ScheduleCreateForm
template_name_suffix = '_create_form'
</code></pre>
<p>I'm able to render the errors in the view's template as <code>non_field_errors</code> as so: </p>
<pre><code>{% for error in form.non_field_errors %}
<label>{{ error }}</label>
{% endfor %}
</code></pre>
<p>My test looks as follows:</p>
<pre><code>class ScheduleValidation(RequiresLogin, TestCase):
def setUp(self):
self._client = client_fixture.create()[0]
# Setup some example sample data for a Schedule
self.data = {
'client': self._client.id,
'schedule_date': today,
'billing_period': 'Q',
'schedule_type': 'SE',
}
def test_start_date_before_end_date_errors(self):
self.data['start_date'] = today
self.data['end_date'] = yesterday
response = self.client.post('reports:schedule-create', self.data, follow=True)
# Check if redirects back to the page
with self.assertTemplateUsed('schedule_create_form.html'):
self.assertFormError(response, 'form', None, 'End Date Must Be Greater Than Start Date')
</code></pre>
<p>I'm setting the field type of <code>None</code> in order to access <code>non_field_errors</code> as detailed by the documentation <a href="https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.SimpleTestCase.assertFormError" rel="nofollow">here</a></p>
<h2>What I've Tried Already</h2>
<p>Inside my template for the view, I'm able to reference the form using <code>{{ form }}</code>, including any <code>non_field_errors</code>. Which means it is being passed to the template properly.</p>
<p>I can check the context data inside the view itself. </p>
<pre><code>def get_context_data(self, **kwargs):
context = super(ScheduleCreate, self).get_context_data(**kwargs)
assert False
return context
</code></pre>
<p>From the breakpoint here I'm able to log the contents of the context variable with Werkzeug in the browser, which shows that 'form' is actually passed to the template</p>
<pre><code>[console ready]
>>> context
{'form': <ScheduleCreateForm bound=True, valid=False, fields=(client;schedule_date;start_date;end_date;billing_period;schedule_type)>, 'view': <reports.views.ScheduleCreate object at 0x7f256eb6c908>}
</code></pre>
<p>Which begs the question why am I getting this error, and how would I fix this?</p>
| 0 | 2016-07-25T11:36:07Z | 38,567,262 | <p>When you use <code>client.post()</code>, you should use the actual URL, not the name of the url.</p>
<p>You could either hardcode it, for example:</p>
<pre><code>response = self.client.post('/reports/schedules/create/, self.data, follow=True)
</code></pre>
<p>Or you could reverse the url:</p>
<pre><code>from django.core.urlresolvers import reverse
url = reverse('reports:schedule-create')
response = self.client.post(url, self.data, follow=True)
</code></pre>
| 1 | 2016-07-25T12:02:46Z | [
"python",
"django",
"forms",
"testing"
] |
Python - import error when trying to activate a virtual environment, or lauch Spyder | 38,566,705 | <p>I get an ImportError whenever I try to activate a virtual environment, or when I try to launch Spyder.</p>
<p>When trying to activate a virtual environment:</p>
<pre><code>Traceback (most recent call last):
File "/home/pauline/anaconda3/bin/conda", line 3, in <module>
from conda.cli import main
ImportError: No module named conda.cli
</code></pre>
<p>When trying to open spyder:</p>
<pre><code>Traceback (most recent call last):
File "/home/pauline/anaconda3/bin/spyder", line 2, in <module>
from spyderlib import start_app
ImportError: No module named spyderlib
</code></pre>
<p>I tried to find an answer for that but I could mainly find problems occurring after Anaconda was just installed (mine has been installed previously and was working fine up until yesterday).</p>
<p>I have also tried <a href="https://stackoverflow.com/questions/19825250/after-anaconda-installation-conda-command-fails-with-importerror-no-module-na">this answer</a> and <a href="https://stackoverflow.com/questions/34981284/pythonpath-error-when-trying-to-activate-a-virtual-environment">this answer</a> but they did not solve the problem.</p>
<p>The only think I can think of which may have provoked this error is that I changed the interpreter used by Spyder yesterday from the default Anaconda Python interpreter to an interpreter from a virtual environment created with virtualenv. Even then, I could close and restart Spyder with no problems, and the errors started after I rebooted my computer.</p>
<p>[edit] I should add that both Anaconda and my virtual environment use the same version of Python which is Python 3.5</p>
| 0 | 2016-07-25T11:36:08Z | 38,566,782 | <p>If you are using a different python version, whatever packages that you had with anaconda or that you may have installed with <code>conda install</code> will not be there on the new version. You need to install them with <code>pip</code> or <code>conda</code> again.</p>
| 1 | 2016-07-25T11:40:15Z | [
"python",
"virtualenv",
"anaconda",
"spyder",
"pythonpath"
] |
number of files; date creation and file size | 38,566,804 | <p>desperately need your help - i have a folder which consists of many files created different days and has different quantity and different size.
For a file size measure i use : </p>
<pre><code>find . -name "*20160725*" -print -exec du -ks {} \; | cut -f1 | awk '{total=total+$1}END{print total/1024}'
</code></pre>
<p>for file quantity </p>
<pre><code>ls -l | grep -c "Jul 25"
</code></pre>
<p>and my question how to SUM them to make some kinda script which will export file in a such view:</p>
<pre><code>DATE QUANTITY SIZE
05-jul 416 26,84
06-jul 1170 28,6
07-jul 490 27,53
08-jul 794 16,19
09-jul 112 13,47
10-jul 122 18,53
11-jul 698 34,04
12-jul 456 19,4
</code></pre>
<p>Thanks for your help </p>
| 0 | 2016-07-25T11:41:13Z | 38,569,822 | <p>Try this :</p>
<pre><code>find . -name '*' -printf '%Td-%Tb %s\n' | awk 'NR==1 {print "DATE\tQUANTITY\tSIZE"}{a[$1]+=$2;b[$1]+=1;}END{for(i in a)print i"\t"b[i]"\t"a[i]/1024}'
</code></pre>
<p>The <code>printf</code> option of the <code>find</code> command outputs date and size for each file. </p>
<p>The ouput is piped to <code>awk</code> that sum the sizes for each date and convert byte sizes to kilobytes as in your sample output.</p>
<p><strong>Update</strong></p>
<p>To sort by date using <code>mm/dd/yyyy</code> format:</p>
<pre><code>find . -maxdepth 1 -name '*' -printf '%TD %s\n' | awk 'NR==1 {print "DATE\tQUANTITY\tSIZE"}{a[$1]+=$2;b[$1]+=1;}END{for(i in a)print i"\t"b[i]"\t"a[i]/1024}' | sort -n -t"/" -k3 -k1 -k2
</code></pre>
| 0 | 2016-07-25T14:01:13Z | [
"python",
"bash",
"shell"
] |
Pandas: concatenate some df | 38,566,920 | <p>I have two df</p>
<pre><code>ID url visits
123 vk.com 14
789 twitter.com 7
</code></pre>
<p>And </p>
<pre><code>ID url buys
123 vk.com 3
456 facebook.com 1
</code></pre>
<p>Desire output</p>
<pre><code>ID url visits buys
123 vk.com 14 3
456 facebook.com NaN 1
789 twitter.com 7 NaN
</code></pre>
<p>I try </p>
<pre><code>result = pd.concat([short, short1], axis=1, ignore_index=False)
</code></pre>
<p>But it doesn't look like my desire output.</p>
| 1 | 2016-07-25T11:46:26Z | 38,566,959 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> on columns <code>ID</code> and <code>url</code> with outer join by parameter <code>how='outer'</code>:</p>
<pre><code>result = pd.merge(short, short1, on=['ID','url'], how='outer')
print (result)
ID url visits buys
0 123.0 vk.com 14.0 3.0
1 789.0 twitter.com 7.0 NaN
2 456.0 facebook.com NaN 1.0
</code></pre>
| 2 | 2016-07-25T11:48:49Z | [
"python",
"pandas"
] |
Populating python matrix | 38,566,995 | <p>I'm doing the splitting of the words from the text file in python. I've receive the number of row (c) and a dictionary (word_positions) with index. Then I create a zero matrix (c, index). Here is the code:</p>
<pre><code>from collections import defaultdict
import re
import numpy as np
c=0
f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r')
for line in f:
c = c + 1
word_positions = {}
with open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r') as f:
index = 0
for word in re.findall(r'[a-z]+', f.read().lower()):
if word not in word_positions:
word_positions[word] = index
index += 1
print(word_positions)
matrix=np.zeros(c,index)
</code></pre>
<p>My question: How can I populate the matrix to be able to get this: <code>matrix[c,index] = count</code>, where <code>c</code> - is the number of row, <code>index</code> -the indexed position and <code>count</code> -the number of counted words in a row</p>
| 1 | 2016-07-25T11:50:43Z | 38,568,742 | <p>It looks like you are trying to create something similar to an <a href="https://pythonprogramming.net/python-3-multi-dimensional-list/" rel="nofollow">n-dimensional list</a>. these are achieved by nesting lists inside themselves as such:</p>
<pre><code>two_d_list = [[0, 1], [1, 2], [example, blah, blah blah]]
words = two_d_list[2]
single_word = two_d_list[2][1] # Notice the second index operator
</code></pre>
<p>This concept is very flexible in Python and can also be done with a dictionary nested inside as you would like:</p>
<pre><code>two_d_list = [{"word":1}, {"example":1, "blah":3}]
words = two_d_list[1] # type(words) == dict
single_word = two_d_list[2]["example"] # Similar index operator, but for the dictionary
</code></pre>
<p>This achieves what you would like, functionally, but does not use the syntax <code>matrix[c,index]</code>, however this syntax does not really exist in python for indexing. Commas within square-brackets usually delineate the elements of list literals. Instead you can access the row's dictionary's element with <code>matrix[c][index] = count</code></p>
<hr>
<p>You may be able to overload the index operator to achieve the syntx you want. <a href="http://%60matrix[c][index]%20=%20count%60" rel="nofollow">Here</a> is a question about achieving the syntax you desire. In summary:</p>
<p>Overload the <code>__getitem__(self, inex)</code> function in a wrapper of the list class and set the function to accept a tuple. The tuple can be created without parenthesis, giving the syntax <code>matrix[c, index] = count</code></p>
| 0 | 2016-07-25T13:12:20Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
Populating python matrix | 38,566,995 | <p>I'm doing the splitting of the words from the text file in python. I've receive the number of row (c) and a dictionary (word_positions) with index. Then I create a zero matrix (c, index). Here is the code:</p>
<pre><code>from collections import defaultdict
import re
import numpy as np
c=0
f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r')
for line in f:
c = c + 1
word_positions = {}
with open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r') as f:
index = 0
for word in re.findall(r'[a-z]+', f.read().lower()):
if word not in word_positions:
word_positions[word] = index
index += 1
print(word_positions)
matrix=np.zeros(c,index)
</code></pre>
<p>My question: How can I populate the matrix to be able to get this: <code>matrix[c,index] = count</code>, where <code>c</code> - is the number of row, <code>index</code> -the indexed position and <code>count</code> -the number of counted words in a row</p>
| 1 | 2016-07-25T11:50:43Z | 38,573,259 | <p>Try next:</p>
<pre><code>import re
import numpy as np
from itertools import chain
text = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt')
text_list = text.readlines()
c=0
for i in range(len(text_list)):
c=c+1
text_niz = []
for i in range(len(text_list)):
text_niz.append(text_list[i].lower()) # пеÑевел к Ð½Ð¸Ð¶Ð½ÐµÐ¼Ñ ÑегиÑÑÑÑ
slovo = []
for j in range(len(text_niz)):
slovo.append(re.split('[^a-z]', text_niz[j])) # ÑокенизаÑиÑ
for e in range(len(slovo)):
while slovo[e].count('') != 0:
slovo[e].remove('') # Ñдалил пÑÑÑÑе Ñлова
slovo_list = list(chain(*slovo))
print (slovo_list) # ÑоÑÑавил ÑпиÑок Ñлов
slovo_list=list(set(slovo_list)) # Ñдалил повÑоÑÑÑÑиеÑÑ
x=len(slovo_list)
s = []
for i in range(len(slovo)):
for j in range(len(slovo_list)):
s.append(slovo[i].count(slovo_list[j])) # поÑÑиÑал колиÑеÑÑво Ñлов в каждом пÑедложении
matr = np.array(s) # маÑÑиÑа вÑ
ождений Ñлов в пÑедложениÑ
d = matr.reshape((c, x)) # пÑеобÑазовал в маÑÑиÑÑ 22*254
</code></pre>
| 1 | 2016-07-25T16:41:04Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
In sympy, how functional expression can be translated into operator overloaded expression? | 38,567,219 | <p>Recently I am working with boolean network and I am using sympy to manipulate boolean functions. I think this can be very basic question but I could not find any clue.</p>
<p>Following line works well. </p>
<pre><code>>>>from sympy import *
>>>x,y = symbols("x y")
>>>(x | y) & x
And(Or(x, y), x)
</code></pre>
<p>Here I have very simple question. How the expression 'And(Or(x, y), x)' can be expressed as '(x | y) & x'? </p>
<p>Thanks</p>
| 0 | 2016-07-25T12:01:12Z | 38,567,388 | <p>Sympy makes extensive use of Python operator overloading capabilities.
In Python each class can define as any mathematical operator will take effect, by defining methods with special names - these methods allways are prefixed and postfixed with <code>__</code>, and are described in the <a href="https://docs.python.org/3/reference/datamodel.html" rel="nofollow">Python Data Model</a>.</p>
<p>Sympy symbols and expressions are objects that redefine all of the operator-related methods to perform an operation that return a Sympy expression object instead of a numeric result.</p>
<p>Thus, the operators for bynary and <code>&</code> an dbinary or <code>|</code> are just one part of what Sympy does, and the long English versions <code>And</code> and <code>Or</code> function calls are provided as well for ease of typing and readability in certain contexts.</p>
| 0 | 2016-07-25T12:09:11Z | [
"python",
"expression",
"sympy",
"prefix",
"infix-notation"
] |
In sympy, how functional expression can be translated into operator overloaded expression? | 38,567,219 | <p>Recently I am working with boolean network and I am using sympy to manipulate boolean functions. I think this can be very basic question but I could not find any clue.</p>
<p>Following line works well. </p>
<pre><code>>>>from sympy import *
>>>x,y = symbols("x y")
>>>(x | y) & x
And(Or(x, y), x)
</code></pre>
<p>Here I have very simple question. How the expression 'And(Or(x, y), x)' can be expressed as '(x | y) & x'? </p>
<p>Thanks</p>
| 0 | 2016-07-25T12:01:12Z | 38,598,499 | <p>If you just want nicer printing, you can run </p>
<pre><code>init_printing()
</code></pre>
<p>and it will print it using Unicode characters, or even LaTeX if it's available (like in the Jupyter notebook)</p>
<pre><code>In [1]: (x | y) & x
Out[1]: x ⧠(x ⨠y)
</code></pre>
<p>You can also use the <code>pprint()</code> function to get this directly. </p>
<p>It looks like the default SymPy printers use <code>And</code> and <code>Or</code> instead of the <code>&</code> and <code>|</code> symbols to print logic expressions, so if you explicitly want those, you would need to subclass <code>sympy.printing.str.StrPrinter</code> and override <code>_print_And</code> and <code>_print_Or</code> (see the <a href="https://github.com/sympy/sympy/blob/17d046e8386fb4098d442b04f4b7bcf8a798f5b9/sympy/printing/str.py#L77" rel="nofollow">current implementation</a> to get an idea of how that would work). </p>
| 0 | 2016-07-26T19:36:52Z | [
"python",
"expression",
"sympy",
"prefix",
"infix-notation"
] |
Function not returning values after being called for a second time | 38,567,257 | <p>I'm trying to complete a python Hangman miniproject to help me learn to code.</p>
<p>I've created a function that will hopefully ask the player for a letter, check the letter is only 1 letter and make sure it is not a number. </p>
<p>Here is the code I have so far:</p>
<pre><code>def getLetter():
letter = raw_input('Please enter a letter...')
if letter.isdigit() == True:
print('That is a number!')
getLetter()
if len(str(letter)) >1:
print("Sorry, you have to enter exactly ONE letter")
getLetter()
else:
return letter
</code></pre>
<p>This works fine when the first input is correct, ie. one letter. However, when the input is incorrect, e.g 'ddddd', the program asks for another letter to be input but will either return the initial input ('ddddd') rather than the new input, or return nothing at all.</p>
<p>How can I make it return the new input? Do I need to clear the raw_input? If so, how?</p>
| 0 | 2016-07-25T12:02:42Z | 38,567,297 | <p>You are not returning the result of your recursive calls; everywhere you call <code>getLetter()</code> you <em>drop</em> the return value.</p>
<p>Add <code>return</code> before those calls to pass on the result up the call chain:</p>
<pre><code>return getLetter()
</code></pre>
<p>However, you should not be using recursion <em>at all</em>; use a loop instead:</p>
<pre><code>def getLetter():
while True:
letter = raw_input('Please enter a letter...')
if letter.isdigit() == True:
print('That is a number!')
continue
if len(str(letter)) >1:
print("Sorry, you have to enter exactly ONE letter")
continue
return letter
</code></pre>
<p>Every recursive call adds onto the call stack, which is not unlimited in size; eventually a user always entering numbers will break your program! See <a href="http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response">Asking the user for input until they give a valid response</a> for more information.</p>
| 4 | 2016-07-25T12:04:06Z | [
"python",
"function"
] |
Function not returning values after being called for a second time | 38,567,257 | <p>I'm trying to complete a python Hangman miniproject to help me learn to code.</p>
<p>I've created a function that will hopefully ask the player for a letter, check the letter is only 1 letter and make sure it is not a number. </p>
<p>Here is the code I have so far:</p>
<pre><code>def getLetter():
letter = raw_input('Please enter a letter...')
if letter.isdigit() == True:
print('That is a number!')
getLetter()
if len(str(letter)) >1:
print("Sorry, you have to enter exactly ONE letter")
getLetter()
else:
return letter
</code></pre>
<p>This works fine when the first input is correct, ie. one letter. However, when the input is incorrect, e.g 'ddddd', the program asks for another letter to be input but will either return the initial input ('ddddd') rather than the new input, or return nothing at all.</p>
<p>How can I make it return the new input? Do I need to clear the raw_input? If so, how?</p>
| 0 | 2016-07-25T12:02:42Z | 38,567,656 | <pre><code>def get_valid_letter():
while True:
letter = raw_input('Please enter a letter...')
if letter.isdigit() == True:
print('That is a number!')
elif len(str(letter)) >1:
print("Sorry, you have to enter exactly ONE letter")
else:
return letter
</code></pre>
| 0 | 2016-07-25T12:22:11Z | [
"python",
"function"
] |
Debugging a Python Prime Number Program | 38,567,337 | <p>I wrote the code for a Python prime number generator, to generate the first 100 primes. But, somehow, I get non-primes like 22, 25, etc. in my output. I've rechecked it over and over again for hours now and still can't figure out where I went wrong... Please help!</p>
<p>Here's my code:</p>
<pre><code>from math import sqrt
y=[2]
x=3
while len(y)!=100:
for i in range (2,int(round(sqrt(x)+1))):
if x%i==0:
x=x+1
else:
y.append(x)
x=x+1
break
print(y)
</code></pre>
| 2 | 2016-07-25T12:06:17Z | 38,567,464 | <p>the content of your else should be outside the for loop. Here you are appending x to your array as soon as it failed to be divided by "at least one of the i" instead of "failing to be divided by each of the i"</p>
<p>Also this algorithms is very inefficient. For a fast one try:
<a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes</a></p>
<pre><code>from math import sqrt
y=[2]
x=3
while len(y)!=100:
prime = True
for i in [ i for i in y if i < sqrt(x) + 1 ]:
if x%i==0:
prime = False
break
if prime:
y.append(x)
x=x+1
print(y)
</code></pre>
<p>Note that I already optimized your algorithm by dividing only by previously found primes. </p>
| 2 | 2016-07-25T12:13:07Z | [
"python",
"debugging"
] |
Debugging a Python Prime Number Program | 38,567,337 | <p>I wrote the code for a Python prime number generator, to generate the first 100 primes. But, somehow, I get non-primes like 22, 25, etc. in my output. I've rechecked it over and over again for hours now and still can't figure out where I went wrong... Please help!</p>
<p>Here's my code:</p>
<pre><code>from math import sqrt
y=[2]
x=3
while len(y)!=100:
for i in range (2,int(round(sqrt(x)+1))):
if x%i==0:
x=x+1
else:
y.append(x)
x=x+1
break
print(y)
</code></pre>
| 2 | 2016-07-25T12:06:17Z | 38,567,581 | <p>Your test for a number being prime is wrong. You check whether a number is divisible by <code>i</code> going from 2 to <code>sqrt(x)</code> which is correct, but as soon as you hit a number which isn't a factor you assume that the number is prime, which is not correct. You have to check all numbers and if none is factor, then you can conclude that your number is prime:</p>
<pre><code>from math import sqrt
y=[2]
x=3
while len(y)!=100:
isPrime=True
for i in range (2,int(round(sqrt(x)+1))):
if x%i==0:
x=x+1
isPrime=False
break # See Mr Nun's answer
if(isPrime):
y.append(x)
x=x+1
print(y)
</code></pre>
<p>As it was pointed out, this is not a very efficient solution. Check out the link in @user2346536's answer.</p>
| 0 | 2016-07-25T12:18:52Z | [
"python",
"debugging"
] |
Debugging a Python Prime Number Program | 38,567,337 | <p>I wrote the code for a Python prime number generator, to generate the first 100 primes. But, somehow, I get non-primes like 22, 25, etc. in my output. I've rechecked it over and over again for hours now and still can't figure out where I went wrong... Please help!</p>
<p>Here's my code:</p>
<pre><code>from math import sqrt
y=[2]
x=3
while len(y)!=100:
for i in range (2,int(round(sqrt(x)+1))):
if x%i==0:
x=x+1
else:
y.append(x)
x=x+1
break
print(y)
</code></pre>
| 2 | 2016-07-25T12:06:17Z | 38,567,648 | <p>As user2346536 said, your else should not be inside the loop. You will only ever look at the element for <code>i = 2</code></p>
<p>How to do it :</p>
<pre><code>from math import sqrt, ceil
prime_list = [2]
x = 2
while prime_list != 100:
x += 1
is_prime = True
for element in range(2,int(ceil(sqrt(x)))):
# if x is divided, then we go to next iteration
if x%element == 0:
is_prime = False
break
if is_prime:
y.append(x)
</code></pre>
| 0 | 2016-07-25T12:21:57Z | [
"python",
"debugging"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.