title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
infinite while loop in python when integer compared with range
39,315,460
<p>my while code:</p> <pre><code>i=0 a = range(100) while i &lt; range(100): print i i += 9 </code></pre> <p>this goes into an infinite loop...may i know why?</p> <p>is it because an integer is compared to the list? but what happens when i becomes greater than 99?</p> <p>shouldnt it come out of the while loop?</p> <p>below code works fine as expected:</p> <pre><code>i=0 a = range(100) a_len = len(a) while i &lt; a_len: print i i += 9 </code></pre>
0
2016-09-04T09:26:44Z
39,315,493
<p><code>range(100)</code> is a list of integers from 1 to 100 over which you are supposed to iterate. So, <code>len(range(100)</code> = 100. In python 2.x, a list is always greater than an integer. A very simple way to fix this problem is:</p> <pre><code>i=0 while i &lt; 100: # instead of range(100) print i i += 9 </code></pre>
0
2016-09-04T09:29:53Z
[ "python", "python-2.7", "while-loop" ]
Issue when trying to install ipython through terminal
39,315,558
<p>I want to install <code>ipython</code> through the macOS terminal (I have tried both <code>easy_install</code> and <code>pip</code>), but a specific problem always occurs, which is described in the last line:</p> <pre><code>Searching for ipython Reading https://pypi.python.org/simple/ipython/ Best match: ipython 5.1.0 Downloading https://pypi.python.org/packages/d4/0b/70c913ed4c99eb84c589e5e25b28985ba93ca2a57e08959bb14372f7f5f8/ipython-5.1.0.zip#md5=9d6a0bd4d4c18a4dc88d2f69dfefdea7 Processing ipython-5.1.0.zip Writing /tmp/easy_install-f_u6YT/ipython-5.1.0/setup.cfg Running ipython-5.1.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-f_u6YT/ipython-5.1.0/egg-dist-tmp-3mwkoQ checking package data check version number creating /Library/Python/2.7/site-packages/ipython-5.1.0-py2.7.egg Extracting ipython-5.1.0-py2.7.egg to /Library/Python/2.7/site-packages Adding ipython 5.1.0 to easy-install.pth file Installing ipython script to /usr/local/bin Installing iptest2 script to /usr/local/bin Installing iptest script to /usr/local/bin Installing ipython2 script to /usr/local/bin Installed /Library/Python/2.7/site-packages/ipython-5.1.0-py2.7.egg Processing dependencies for ipython error: six 1.4.1 is installed but six&gt;=1.9.0 is required by set(['prompt-toolkit']) </code></pre> <p>What can i do to resolve it?</p> <p><strong>EDIT:</strong> I tried <code>sudo pip install --upgrade six</code>, but a permission error occurred.</p> <pre><code>OSError: [Errno 1] Operation not permitted: '/tmp/pip-GgNJ79-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info' </code></pre>
1
2016-09-04T09:40:33Z
39,317,018
<p>Well, assuming that <code>sudo easy_install ipython</code> is used to install <code>ipython</code>, this is what worked for me, in order to get the latest version of <code>six</code>.</p> <p><code>sudo pip install --ignore-installed six</code>, which is described more analytically <a href="http://stackoverflow.com/questions/31900008/oserror-errno-1-operation-not-permitted-when-installing-scrapy-in-osx-10-11">here</a>.</p>
1
2016-09-04T12:40:59Z
[ "python", "osx", "terminal", "ipython" ]
Can't get lFilter to work (rpi2b)
39,315,576
<p>Some information: I am using a rpi2b with a cirrus logic audio card and have worked out the kernel changes to get the sound card going, I can output without problems, I can record from line in without problems (I am using pyAudio). </p> <p>Now I only want to filter the signal and have found a lot of functions in the scipy library...</p> <p>First thing to mention I can only use 2 channels (stereo) input the soundcard seems to doesnt allow 1 channel and I dont have a source to stream mono (iPhone, simple USB player everyone has only stereo)....</p> <p>The filter line (specifications) is just an example I think it will be an other filter if it works :D</p> <p>So before the code begins a little to explain. When using stereo input the samples appear to be interleaved so you get on the one channel a sample on the other... I thought this thread was helpful: <a href="http://stackoverflow.com/questions/22636499/convert-multi-channel-pyaudio-into-numpy-array/22644499#comment35021142_22644499">Convert multi-channel PyAudio into NumPy array</a></p> <p>Thats why I also tried to decode my stream into an array, filter and then code it again into a stream for output. If I neglect the interleaving fact I get weird noises thats why I think I should take care of it :)</p> <p><strong>Now comes the part where I fail:</strong> lFilter doesnt want to work! If I just use my unprocessed input_data it says the axis is out of range (I tried -1,0,1,2) dont know :/ and when using my reshaped etc. data I get:</p> <pre><code>return sigtools._linear_filter(b, a, x, axis, zi) ValueError: object of too small depth for desired array </code></pre> <p>Can someone please explain why this is happening? :D Never used signals thats why I am unexperienced but I cant understand why the unprocessed data has axis problems and even though it wouldnt bother because I need the reshaped data like in the linked thread... </p> <pre><code>WIDTH = 2 CHANNELS = 2 RATE = 44100 p = pyaudio.PyAudio() [b,a] = signal.iirfilter(2,[50,200],rs=60,btype='band',analog=True,ftype='cheby2') full_data = np.array([]) def callback(in_data, frame_count, time_info, status): global b,a,full_data full_data = decode (in_data, 2) audio_data = signal.lfilter(b,a, full_data) print (audio_data) stream_data = encode(audio_data) return (stream_data, pyaudio.paContinue) </code></pre> <p>I skipped the stream open part and the decode and encode since the last ones are right now exactly the same as in the thread and the first one works thats why I just posted these parts. If needed I can also provide the others.</p> <p>Any help is highly appreciated!</p> <ul> <li>Sanj3k</li> </ul> <hr> <p>This is an example of what the data looks like, at first its a 1d np array and after the reshape etc ist 2d because of the stereo....</p> <p>What does lFilter need? Since I have axis errors and with 2d its to small....</p> <p><a href="http://i.stack.imgur.com/xaZte.png" rel="nofollow">screenshot from the terminal</a></p> <p>Edit: Btw here is the documentation from scipy library for the lfilter function and it says:</p> <pre><code>x : array_like An N-dimensional input array. </code></pre> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.lfilter.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.lfilter.html</a></p>
1
2016-09-04T09:43:34Z
39,320,138
<p>For one thing, you need to keep the final conditions from one chunk and feed it as initial conditions to the next chunk. Otherwise the filter assumes rest at the start of each chunk, which will result in glitches at each chunk.</p> <pre><code>global zi audio_data, zi = signal.lfilter(b, a, full_data, zi=zi)` </code></pre> <p>So this call will update <code>zi</code> and then on the next cycle it will use it as the input to lfilter, which will update it, etc. As <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.lfilter.html" rel="nofollow">the docs</a> say:</p> <pre><code>zi : array_like, optional Initial conditions for the filter delays. It is a vector (or array of vectors for an N-dimensional input) of length ``max(len(a), len(b)) - 1``. If `zi` is None or is not given then initial rest is assumed. ... zf : array, optional If `zi` is None, this is not returned, otherwise, `zf` holds the final filter delay values. </code></pre> <p>To initialize <code>zi</code> in the first place, just create a zeros array of shape <code>(max(len(a), len(b)) - 1, number_of_channels)</code>.</p>
0
2016-09-04T18:23:11Z
[ "python", "numpy", "scipy", "raspberry-pi2" ]
Tkinter ListBox and dictionaries
39,315,584
<p>Displaying list items in a tkinter listbox looks like this:</p> <pre><code>from tkinter import * root = Tk() lst = ["one", "two", "three"] lstbox = Listbox(root) lstbox.pack() for item in lst: lstbox.insert(END, item) root.mainloop() </code></pre> <p>How can I display a dictionary with both its keys and values using a listbox? </p>
0
2016-09-04T09:44:28Z
39,315,685
<p>Iterate over the keys of the dictionary and insert a string comprising the key and its value. You can use <code>str.format()</code> to create the string. Here's an example:</p> <pre><code>d = {"one": 1, "two": 2, "three": 3} for key in d: lstbox.insert(END, '{}: {}'.format(key, d[key])) </code></pre> <hr> <p>Note that the items will not be in any particular order because dictionaries are unordered. You could sort the keys like this:</p> <pre><code>for key in sorted(d): lstbox.insert(END, '{}: {}'.format(key, d[key])) </code></pre>
1
2016-09-04T09:55:33Z
[ "python", "dictionary", "tkinter", "listbox" ]
Invalid literal for int() with base 10: ' ', reading off text file
39,315,773
<p>Im trying to make a text game/rpg in python. Im getting an</p> <blockquote> <p>line 89, in surv = int(statload.readline(3))</p> <p>ValueError: invalid literal for int() with base 10: ''</p> </blockquote> <p>error code, when trying to read off a file. the other ones around it read fine.</p> <p>Reading code-</p> <pre><code>statload = open("Statsheet.txt","r") luck = int(statload.readline(2)) surv = int(statload.readline(3)) statload.close </code></pre> <p>Code which Writes to file-</p> <pre><code>stats = open("Statsheet.txt","w") stats.write(repr(luck)+ "\n") stats.write(repr(surv)+ "\n") stats.close </code></pre> <p>Contents of Text File-</p> <pre><code>45 40 </code></pre> <p>I have to have the "luck" and "surv" stats in "int" format, as later on in the code they are used in mathematical functions. The modules i have imported are "sys", "time", "random", and "math", if that helps at all.</p> <p>Edit- will put variables into a JSON file instead, as one user suggested, and now know that the "readline" reads the bit value. thanks!</p>
-3
2016-09-04T10:05:54Z
39,315,840
<p>You are using raedline incorrectly. The argument in readline() should be number of bytes to read from the file, not the line number to read.</p> <p>What you want to be doing is something like this:</p> <pre><code>with open("Statsheet.txt", "r") as file: stats = file.readlines() luck = int(stats[0]) surv = int(stats[1]) </code></pre> <p>But there are better options for storing stats etc than text files with each line meaning something, like SQL, json etc.</p>
-1
2016-09-04T10:14:17Z
[ "python", "sys" ]
Invalid literal for int() with base 10: ' ', reading off text file
39,315,773
<p>Im trying to make a text game/rpg in python. Im getting an</p> <blockquote> <p>line 89, in surv = int(statload.readline(3))</p> <p>ValueError: invalid literal for int() with base 10: ''</p> </blockquote> <p>error code, when trying to read off a file. the other ones around it read fine.</p> <p>Reading code-</p> <pre><code>statload = open("Statsheet.txt","r") luck = int(statload.readline(2)) surv = int(statload.readline(3)) statload.close </code></pre> <p>Code which Writes to file-</p> <pre><code>stats = open("Statsheet.txt","w") stats.write(repr(luck)+ "\n") stats.write(repr(surv)+ "\n") stats.close </code></pre> <p>Contents of Text File-</p> <pre><code>45 40 </code></pre> <p>I have to have the "luck" and "surv" stats in "int" format, as later on in the code they are used in mathematical functions. The modules i have imported are "sys", "time", "random", and "math", if that helps at all.</p> <p>Edit- will put variables into a JSON file instead, as one user suggested, and now know that the "readline" reads the bit value. thanks!</p>
-3
2016-09-04T10:05:54Z
39,315,855
<p>The argument to <code>readline()</code> is unnecessary in your case. Just drop it and the code will work:</p> <pre><code>luck = int(statload.readline()) surv = int(statload.readline()) </code></pre> <p>If you're curious, <code>statload.readline(2)</code> reads the first two characters (<code>45</code>) and leaves the file pointer right before the newline that follows the <code>45</code>. That newline is all that the second call to <code>readline()</code> reads, giving you the empty string that results in the exception you're getting.</p> <p>When you omit the argument, <code>readline()</code> will simply read the entire line irrespective of how long it is.</p> <p>Also note that you're missing parentheses after the calls to <code>close()</code>:</p> <pre><code>statload.close() </code></pre>
1
2016-09-04T10:15:51Z
[ "python", "sys" ]
Invalid literal for int() with base 10: ' ', reading off text file
39,315,773
<p>Im trying to make a text game/rpg in python. Im getting an</p> <blockquote> <p>line 89, in surv = int(statload.readline(3))</p> <p>ValueError: invalid literal for int() with base 10: ''</p> </blockquote> <p>error code, when trying to read off a file. the other ones around it read fine.</p> <p>Reading code-</p> <pre><code>statload = open("Statsheet.txt","r") luck = int(statload.readline(2)) surv = int(statload.readline(3)) statload.close </code></pre> <p>Code which Writes to file-</p> <pre><code>stats = open("Statsheet.txt","w") stats.write(repr(luck)+ "\n") stats.write(repr(surv)+ "\n") stats.close </code></pre> <p>Contents of Text File-</p> <pre><code>45 40 </code></pre> <p>I have to have the "luck" and "surv" stats in "int" format, as later on in the code they are used in mathematical functions. The modules i have imported are "sys", "time", "random", and "math", if that helps at all.</p> <p>Edit- will put variables into a JSON file instead, as one user suggested, and now know that the "readline" reads the bit value. thanks!</p>
-3
2016-09-04T10:05:54Z
39,315,856
<p>It looks like once you execute luck = int(statload.readline(2)), the file pointer moves to the end of the file, and there's nothing more to read. Try this:</p> <pre><code>statload = open("Statsheet.txt","r").read().split('\n') luck = int(statload[0]) surv = int(statload[1]) </code></pre>
0
2016-09-04T10:16:06Z
[ "python", "sys" ]
Match number between '<<' (regex)
39,315,811
<p>I have the following string</p> <blockquote> <p>All files | 100 &lt;&lt;222>></p> </blockquote> <p>And would like to match the number between <code>&lt;&lt; &gt;&gt;</code></p> <p>How can I do that? </p> <p>So far I tried this expression <code>(?&lt;&lt;)(.*?)(?&gt;&gt;)</code></p>
0
2016-09-04T10:11:21Z
39,315,846
<p>The problem is, that <code>&lt;</code> is a special character, which needs to be escaped. Also, the <code>?</code> in the first and third group are invalid:</p> <pre><code>(\&lt;\&lt;)(?P&lt;number&gt;\d*?)(\&gt;\&gt;) </code></pre> <p>Additionally, I named the group with the number and used <code>\d</code> to match digits instead of <code>*</code>. I tested it <a href="https://regex101.com/r/tN0bG9/1" rel="nofollow">here</a>.</p>
2
2016-09-04T10:15:00Z
[ "python", "regex" ]
Match number between '<<' (regex)
39,315,811
<p>I have the following string</p> <blockquote> <p>All files | 100 &lt;&lt;222>></p> </blockquote> <p>And would like to match the number between <code>&lt;&lt; &gt;&gt;</code></p> <p>How can I do that? </p> <p>So far I tried this expression <code>(?&lt;&lt;)(.*?)(?&gt;&gt;)</code></p>
0
2016-09-04T10:11:21Z
39,315,864
<p>Try this,</p> <pre><code>In [1]: match = re.compile(r'&lt;&lt;(\d+)&gt;&gt;') In [2]: match.findall('100 &lt;&lt;222&gt;&gt;') Out[2]: ['222'] </code></pre> <p>Regex model</p> <pre><code>&lt;&lt;(\d+)&gt;&gt; </code></pre> <p><img src="https://www.debuggex.com/i/igWnc7UKlm_2GgcB.png" alt="Regular expression visualization"></p> <p><a href="https://www.debuggex.com/r/igWnc7UKlm_2GgcB" rel="nofollow">Demo</a></p>
1
2016-09-04T10:17:18Z
[ "python", "regex" ]
Use .ckpt and .meta -files to make predictions with Inception in TensorFlow
39,315,920
<p>I used the Inception-library <em>(Tensorflow/models/Inception-tutorial on github)</em>, feeding selfmade TFRecord-files to imagenet_train.py, and ended up with a 7Gb directory containing .ckpt and .meta files.</p> <p>How do i use them to make actual predictions?(also evaluating, testing, <strong>testing with actual .jpg files</strong>, continue the training)</p> <p>What would be the next steps?Are there dummy-friendly examples(tutorials)?</p> <p><em>[I know there´s a thread with a similar name, but it contains barely a question nor answers.]</em></p>
1
2016-09-04T10:24:28Z
39,333,832
<p><a href="https://www.tensorflow.org/versions/r0.10/how_tos/variables/index.html#restoring-variables" rel="nofollow">https://www.tensorflow.org/versions/r0.10/how_tos/variables/index.html#restoring-variables</a> provides pretty much everything you should need.</p> <p>The code there is:</p> <pre><code># Add ops to save and restore all the variables. saver = tf.train.Saver() # Later, launch the model, use the saver to restore variables from disk, and # do some work with the model. with tf.Session() as sess: # Restore variables from disk. saver.restore(sess, "/tmp/model.ckpt") print("Model restored.") # Do some work with the model ... </code></pre> <p>So at the <code>...</code> part, you could load your .jpegs and feed them into the network with placeholders and feeddicts. </p>
0
2016-09-05T15:34:54Z
[ "python", "machine-learning", "tensorflow" ]
Pandas merge 5 csv files with only 1 different column name
39,315,923
<p>I have 5 csv files which I'm trying to merge using Python Pandas, also I'm running 64-bit Python cause of Memory issue.</p> <p>All 5 csv files have identical column names: <code>['A', 'B', 'C', ... 'Start_time', 'end_time', 'Unique_column']</code></p> <p>Here <strong>Unique_column</strong> is the different column name per CSV file. So I need to merge all 5 files with each other, so in the end I will get DataFrame as </p> <p><code>['A', 'B', 'C', ... 'Start_time', 'end_time', 'Unique_column1', 'Unique_colum2', ... 'Unique_colum5']</code></p> <p>Is it <code>pandas.merge</code> or <code>pandas.concat</code> method?</p> <p><strong>UPDATE</strong>:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; import glob &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; dir_name = r'C:\Users\data' &gt;&gt;&gt; dfs = [] &gt;&gt;&gt; files = glob.glob(os.path.join(dir_name, '*.csv')) &gt;&gt;&gt; for f in files: ... df = pd.read_csv(f) ... dfs.append(df) ... &gt;&gt;&gt; common_cols = ['Target', 'POS', 'Start_Week', 'End_Week', 'Measure_Metric'] &gt;&gt;&gt; res = pd.concat([df.set_index(common_cols) for df in dfs], axis=1).reset_index() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "c:\Python27x64\lib\site-packages\pandas\tools\merge.py", line 846, in concat return op.get_result() File "c:\Python27x64\lib\site-packages\pandas\tools\merge.py", line 1031, in get_result indexers[ax] = obj_labels.reindex(new_labels)[1] File "c:\Python27x64\lib\site-packages\pandas\indexes\multi.py", line 1422, in reindex raise Exception("cannot handle a non-unique multi-index!") Exception: cannot handle a non-unique multi-index! &gt;&gt;&gt; </code></pre>
1
2016-09-04T10:24:33Z
39,316,011
<p>IIUC, use <code>pd.concat</code> after having set the index on each to be all common columns.</p> <p>Imagine you have all files imported into the list <code>dfs</code></p> <pre><code>dfs = [df1, df2, df3, df4, df5] </code></pre> <p>Then concat like</p> <pre><code>common_cols = ['A', 'B', 'C', 'Start_time', 'end_time'] pd.concat([df.set_index(common_cols) for df in dfs], axis=1).reset_index() </code></pre>
1
2016-09-04T10:35:20Z
[ "python", "csv", "pandas", "merge" ]
Pandas merge 5 csv files with only 1 different column name
39,315,923
<p>I have 5 csv files which I'm trying to merge using Python Pandas, also I'm running 64-bit Python cause of Memory issue.</p> <p>All 5 csv files have identical column names: <code>['A', 'B', 'C', ... 'Start_time', 'end_time', 'Unique_column']</code></p> <p>Here <strong>Unique_column</strong> is the different column name per CSV file. So I need to merge all 5 files with each other, so in the end I will get DataFrame as </p> <p><code>['A', 'B', 'C', ... 'Start_time', 'end_time', 'Unique_column1', 'Unique_colum2', ... 'Unique_colum5']</code></p> <p>Is it <code>pandas.merge</code> or <code>pandas.concat</code> method?</p> <p><strong>UPDATE</strong>:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; import glob &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; dir_name = r'C:\Users\data' &gt;&gt;&gt; dfs = [] &gt;&gt;&gt; files = glob.glob(os.path.join(dir_name, '*.csv')) &gt;&gt;&gt; for f in files: ... df = pd.read_csv(f) ... dfs.append(df) ... &gt;&gt;&gt; common_cols = ['Target', 'POS', 'Start_Week', 'End_Week', 'Measure_Metric'] &gt;&gt;&gt; res = pd.concat([df.set_index(common_cols) for df in dfs], axis=1).reset_index() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "c:\Python27x64\lib\site-packages\pandas\tools\merge.py", line 846, in concat return op.get_result() File "c:\Python27x64\lib\site-packages\pandas\tools\merge.py", line 1031, in get_result indexers[ax] = obj_labels.reindex(new_labels)[1] File "c:\Python27x64\lib\site-packages\pandas\indexes\multi.py", line 1422, in reindex raise Exception("cannot handle a non-unique multi-index!") Exception: cannot handle a non-unique multi-index! &gt;&gt;&gt; </code></pre>
1
2016-09-04T10:24:33Z
39,316,040
<p>you can do</p> <pre><code>df_master['unique1'] = df_reference1['unique1'] </code></pre> <p>this will create the new row 'unique1'. Watch your indexing!</p>
0
2016-09-04T10:38:48Z
[ "python", "csv", "pandas", "merge" ]
When I try to do errbot after errbot --init, I get the following error?
39,316,009
<p>I can get errbot terminal as >>>. I am using python 3.5 and virtual enviroment is activated. </p> <p>I am building a chatops bot for telegram. I was working on other device where errbot was fine but I can't even install it here. Can any one help me here ?</p> <pre><code>16:05:42 ERROR errbot.cli I cannot find the config file /home/roshan/Python/config.py (You can change this path with the -c parameter see --help) 16:05:42 INFO errbot.cli You can use the template /home/roshan/Python/environment/lib/python3.5/site-packages/errbot/cli.py/config-template.py as a base and copy it to /home/roshan/Python/config.py. You can then customize it. (environment) roshan@roshan-HP-630-Notebook-PC:~/Python$ cd errbot (environment) roshan@roshan-HP-630-Notebook-PC:~/Python/errbot$ errbot 16:05:56 INFO errbot.cli Config check passed... 16:05:56 INFO errbot.cli Selected backend 'Text'. 16:05:56 INFO errbot.cli Checking for '/home/roshan/Python/errbot/data'... 16:05:56 INFO errbot.specific_plugin_ma storage search paths {'/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/storage'} 16:05:56 INFO errbot.specific_plugin_ma Found those plugings available: 16:05:56 INFO errbot.specific_plugin_ma Shelf (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/storage/shelf.py) 16:05:56 INFO errbot.specific_plugin_ma Memory (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/storage/memory.py) 16:05:56 INFO errbot.bootstrap Found Storage plugin: 'Shelf' Description: This is the storage plugin for the traditional shelf store for errbot. 16:05:56 DEBUG errbot.specific_plugin_ma Refilter the plugins... 16:05:56 WARNING yapsy Plugin candidate '/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/storage/memory.plug' rejected by strategy 'SpecificBackendLocator' 16:05:56 DEBUG errbot.specific_plugin_ma Load the one remaining... 16:05:56 DEBUG errbot.specific_plugin_ma Class to load ShelfStoragePlugin 16:05:56 DEBUG errbot.storage Opening storage 'repomgr' 16:05:56 DEBUG errbot.storage.shelf Open shelf storage /home/roshan/Python/errbot/data/repomgr.db 16:05:56 DEBUG errbot.storage Opening storage 'core' 16:05:56 DEBUG errbot.storage.shelf Open shelf storage /home/roshan/Python/errbot/data/core.db 16:05:56 INFO errbot.specific_plugin_ma backends search paths {'/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends'} 16:05:56 INFO errbot.specific_plugin_ma Found those plugings available: 16:05:56 INFO errbot.specific_plugin_ma IRC (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/irc.py) 16:05:56 INFO errbot.specific_plugin_ma XMPP (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/xmpp.py) 16:05:56 INFO errbot.specific_plugin_ma Slack (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/slack.py) 16:05:56 INFO errbot.specific_plugin_ma Null (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/null.py) 16:05:56 INFO errbot.specific_plugin_ma Telegram (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/telegram_messenger.py) 16:05:56 INFO errbot.specific_plugin_ma Graphic (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/graphic.py) 16:05:56 INFO errbot.specific_plugin_ma Text (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/text.py) 16:05:56 INFO errbot.specific_plugin_ma Hipchat (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/hipchat.py) 16:05:56 INFO errbot.specific_plugin_ma Test (/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/test.py) 16:05:56 INFO errbot.bootstrap Found Backend plugin: 'Text' Description: This is the text backend for Err. 16:05:56 DEBUG errbot.specific_plugin_ma Refilter the plugins... 16:05:56 WARNING yapsy Plugin candidate '/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/irc.plug' rejected by strategy 'SpecificBackendLocator' 16:05:56 WARNING yapsy Plugin candidate '/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/xmpp.plug' rejected by strategy 'SpecificBackendLocator' 16:05:56 WARNING yapsy Plugin candidate '/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/slack.plug' rejected by strategy 'SpecificBackendLocator' 16:05:56 WARNING yapsy Plugin candidate '/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/null.plug' rejected by strategy 'SpecificBackendLocator' 16:05:56 WARNING yapsy Plugin candidate '/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/telegram_messenger.plug' rejected by strategy 'SpecificBackendLocator' 16:05:56 WARNING yapsy Plugin candidate '/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/graphic.plug' rejected by strategy 'SpecificBackendLocator' 16:05:56 WARNING yapsy Plugin candidate '/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/hipchat.plug' rejected by strategy 'SpecificBackendLocator' 16:05:56 WARNING yapsy Plugin candidate '/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/test.plug' rejected by strategy 'SpecificBackendLocator' 16:05:56 DEBUG errbot.specific_plugin_ma Load the one remaining... 16:05:56 ERROR yapsy Unable to import plugin: /home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/text Traceback (most recent call last): File "/home/roshan/Python/environment/lib/python3.5/site-packages/yapsy/PluginManager.py", line 488, in loadPlugins candidate_module = imp.load_module(plugin_module_name,plugin_file,candidate_filepath+".py",("py","r",imp.PY_SOURCE)) File "/usr/lib/python3.5/imp.py", line 234, in load_module return load_source(name, filename, file) File "/usr/lib/python3.5/imp.py", line 172, in load_source module = _load(spec) File "&lt;frozen importlib._bootstrap&gt;", line 693, in _load File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 665, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/text.py", line 16, in &lt;module&gt; from errbot.backends.test import TestPerson File "/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/test.py", line 10, in &lt;module&gt; import pytest ImportError: No module named 'pytest' 16:05:56 ERROR errbot.bootstrap Unable to load or configure the backend. Traceback (most recent call last): File "/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/bootstrap.py", line 125, in setup_bot bot = backendpm.get_plugin_by_name(backend_name) File "/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/specific_plugin_manager.py", line 86, in get_plugin_by_name raise Exception('Error loading plugin %s:\nError:\n%s\n' % (name, formatted_error)) Exception: Error loading plugin Text: Error: &lt;class 'ImportError'&gt;: File "/home/roshan/Python/environment/lib/python3.5/site-packages/yapsy/PluginManager.py", line 488, in loadPlugins candidate_module = imp.load_module(plugin_module_name,plugin_file,candidate_filepath+".py",("py","r",imp.PY_SOURCE)) File "/usr/lib/python3.5/imp.py", line 234, in load_module return load_source(name, filename, file) File "/usr/lib/python3.5/imp.py", line 172, in load_source module = _load(spec) File "&lt;frozen importlib._bootstrap&gt;", line 693, in _load File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 665, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/text.py", line 16, in &lt;module&gt; from errbot.backends.test import TestPerson File "/home/roshan/Python/environment/lib/python3.5/site-packages/errbot/backends/test.py", line 10, in &lt;module&gt; import pytest </code></pre>
0
2016-09-04T10:35:07Z
39,316,545
<p>This is caused by <a href="https://github.com/errbotio/errbot/issues/841" rel="nofollow">a bug in errbot</a> itself which affects the <code>Text</code> backend. What you can do to work around this until this is fixed upstream is to simply install <a href="https://pypi.python.org/pypi/pytest/" rel="nofollow">pytest</a> in your virtualenv (through <code>pip install pytest</code>) so that the import succeeds.</p>
0
2016-09-04T11:43:02Z
[ "python", "python-3.x", "errbot" ]
email with optional headers error
39,316,013
<p>I'm attempting to send a sample email, but get the following error:</p> <pre><code>&gt;&gt;&gt; import smtplib &gt;&gt;&gt; from email.mime.text import MIMEText &gt;&gt;&gt; def send_email(subj, msg, from_addr, *to, host="localhost", port=1025, **headers): ... email = MIMEText(msg) ... email['Subject'] = subj ... email['From'] = from_addr ... for h, v in headers.items(): ... print("Headers - {} Value {} ".format(h, v)) ... email[h] = v ... sender = smtplib.SMTP(host,port) ... for addr in to: ... del email['To'] ... email['To'] = addr ... sender.sendmail(from_addr, addr, email.as_string()) ... sender.quit() ... &gt;&gt;&gt; headers={'Reply-To': 'me2@example.com'} &gt;&gt;&gt; send_email("first email", "test", "first@example.com", ("p1@example.com", "p2@example.com"), headers=headers) Headers - headers Value {'Reply-To': 'me2@example.com'} Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 12, in send_email File "/usr/lib/python3.5/email/message.py", line 159, in as_string g.flatten(self, unixfrom=unixfrom) File "/usr/lib/python3.5/email/generator.py", line 115, in flatten self._write(msg) File "/usr/lib/python3.5/email/generator.py", line 195, in _write self._write_headers(msg) File "/usr/lib/python3.5/email/generator.py", line 222, in _write_headers self.write(self.policy.fold(h, v)) File "/usr/lib/python3.5/email/_policybase.py", line 322, in fold return self._fold(name, value, sanitize=True) File "/usr/lib/python3.5/email/_policybase.py", line 360, in _fold parts.append(h.encode(linesep=self.linesep, AttributeError: 'dict' object has no attribute 'encode' </code></pre> <p>When I omit the optional header dictionary, then the email is successfully sent. The **param requires a dictionary, is that correct? Can anybody suggest a remedy for the error?</p>
0
2016-09-04T10:35:34Z
39,316,056
<p>You are misunderstanding how <code>*args</code> and <code>**kwargs</code> work. They capture additional positional and keyword arguments, while you are passing in an extra tuple and an extra dictionary as <code>(...)</code> and <code>headers=headers</code>, respectively.</p> <p>That means that <code>to</code> is now set to <code>(("p1@example.com", "p2@example.com"),)</code> (a tuple containing a single tuple), and <code>headers</code> is set to <code>{'headers': {'Reply-To': 'me2@example.com'}}</code> (a dictionary containing another dictionary).</p> <p>You see the latter in your output:</p> <pre><code>Headers - headers Value {'Reply-To': 'me2@example.com'} </code></pre> <p>That's the <code>headers</code> key, referencing a dictionary.</p> <p>Pass in the <code>to</code> values <em>as separate arguments</em>, and use the <code>**kwargs</code> <em>call</em> syntax to pass in the headers:</p> <pre><code>headers={'Reply-To': 'me2@example.com'} send_email("first email", "test", "first@example.com", "p1@example.com", "p2@example.com", **headers) </code></pre> <p><code>**headers</code> applies each key-value pair in that dictionary as a separate keyword argument.</p>
1
2016-09-04T10:40:28Z
[ "python", "python-3.x", "smtplib" ]
Splitting arithmetric expressions in python with regexps
39,316,072
<p>i have a following snippet, generally i want to split arithmetic expression (with negative numbers) to tokens.</p> <pre><code>import re import collections NUM = r'(?P&lt;NUM&gt;-?\d+)' PLUS = r'(?P&lt;PLUS&gt;\+)' MINUS = r'(?P&lt;MINUS&gt;-)' TIMES = r'(?P&lt;TIMES&gt;\*)' DIVIDE = r'(?P&lt;DIVIDE&gt;/)' LPAREN = r'(?P&lt;LPAREN&gt;\()' RPAREN = r'(?P&lt;RPAREN&gt;\))' WS = r'(?P&lt;WS&gt;\s+)' Token = collections.namedtuple('Token', ['type', 'value']) def generate_tokens(text): pattern = re.compile('|'.join((NUM, PLUS, MINUS, TIMES, DIVIDE, LPAREN, RPAREN, WS))) scanner = pattern.scanner(text) for m in iter(scanner.match, None): token = Token(m.lastgroup, m.group()) if token.type != 'WS': yield token expr = "2-2" out = [token for token in generate_tokens(expr)] for token in out: print(token) </code></pre> <p>And there is problem with splitting negative numbers with this code, output is</p> <pre><code>Token(type='NUM', value='2') Token(type='NUM', value='-2') </code></pre> <p>But should be</p> <pre><code>Token(type='NUM', value='2') Token(type='MINUS', value='-') Token(type='NUM', value='2') </code></pre> <p>How to fix this?</p>
0
2016-09-04T10:43:04Z
39,316,811
<p>I think the easiest way is just to create expressions by seperating each part with space.</p> <p>ex.</p> <pre><code>expr= '2 - -2' Token(type='NUM', value='2') Token(type='MINUS', value='-') Token(type='NUM', value='-2') </code></pre> <p>The problem is that the computer dosen't know wheter you've forgot to add a minus sign in "2-2" expression or if you wanted to substract 2 - 2, which would be 0. I think it shouldn't be a problem to just specific the way how the input should be given.</p>
0
2016-09-04T12:14:58Z
[ "python", "regex", "parsing" ]
How to read a audio file in Python similar to Matlab audioread?
39,316,087
<p>I'm using <code>wavefile.read()</code> in Python to import a audio file to Python. What I want is read a audio file where every sample is in double and normalized to -1.0 to +1.0 similar to Matlab <code>audioread()</code> function. How can I do it ?</p>
1
2016-09-04T10:45:25Z
39,319,960
<p>Use <a href="http://pysoundfile.readthedocs.io/en/latest/#soundfile.read" rel="nofollow">read</a> function of the <a href="https://pypi.python.org/pypi/PySoundFile/" rel="nofollow">PySoundFile</a> package. By default it will return exactly what you request: a numpy array containing the sound file samples in double-precision (<code>Float64</code>) format in the range <code>-1.0</code> to <code>+1.0</code>.</p>
1
2016-09-04T18:06:01Z
[ "python", "matlab", "audio" ]
Deploy webapp on GAE then do changes online from GAE console
39,316,090
<p>I deployed a webapp2 python application on GAE. Is there any way with which i can explore the source code or make changes in the project files from GAE console. Is it possible that if i only want to update a single .py file on already deployed app rather than again deploying the whole project?</p>
0
2016-09-04T10:45:39Z
39,319,187
<p>I think you're looking for this :</p> <p><a href="https://console.cloud.google.com/code/develop" rel="nofollow">https://console.cloud.google.com/code/develop</a></p> <p>I pushed my code on Google Cloud Platform with git, and I'm able to change text files directly online.</p> <p>The doc is here : <a href="https://cloud.google.com/source-repositories/" rel="nofollow">https://cloud.google.com/source-repositories/</a></p>
1
2016-09-04T16:40:12Z
[ "python", "google-app-engine" ]
python : Bootstrapping by random sampling
39,316,142
<p>I have an array like this,</p> <pre><code>[[ 5.80084178e-05 1.20779787e-02 -2.65970238e-02] [ -1.36810406e-02 6.85722519e-02 -2.60280724e-01] [ 4.21996519e-01 -1.43644036e-01 2.12904690e-01] [ 3.03098198e-02 1.50170659e-02 -1.09683402e-01] [ -1.50776089e-03 7.22369575e-03 -3.71181228e-02] [ -3.04448275e-01 -3.66987035e-01 1.44618682e-01] [ -1.46744916e-01 3.47112167e-01 3.09550267e-01] [ 1.16567762e-03 1.72858807e-02 -9.39297514e-02] [ 1.25896836e-04 1.61310167e-02 -6.00253128e-02] [ 1.65062798e-02 1.96933143e-02 -4.26540031e-02] [ -3.78020965e-03 7.51770012e-03 -3.67852984e-02]] </code></pre> <p>And I want to select any <code>n</code> (ex: 1000) number of random rows from these so the output will be:</p> <pre><code>[[ -1.36810406e-02 1.72858807e-02 -4.26540031e-02] [ 1.16567762e-03 7.51770012e-03 -2.60280724e-01] .... .... .... ]] </code></pre> <p>i.e. the output rows are made by randomly selecting values from each column. The number of possible samples from above 11x3 array is 11*11*11 .</p> <p>Can someone help me to do this in python?</p>
-1
2016-09-04T10:53:29Z
39,316,373
<p>If the above initial 11x3 array is 'A' ,</p> <pre><code>import random arr=np.zeros(shape=(1000,5)) for k in range(0,1000) : B=[] for i in range(0,3): B.append(random.choice(A.transpose()[i])) arr[k]=B </code></pre> <p>simply, 'arr' will give me what I am looking for. But isn't there a better, existing algorithm for this?</p>
0
2016-09-04T11:23:04Z
[ "python" ]
Python: write at the specific position in a file
39,316,183
<p>I have two files one having let suppose list of keys while other file have keys and value pair written like below.</p> <blockquote> <p>keys```values</p> </blockquote> <p>Now, assuming I have to search for each keys in the later file having key value pair and on matching the keys, have to write some value for specific key at the value's position.</p> <p>Here is my code, which on running matches the pattern, shows the exact output at the console but on writing in the file writes at the end of the file instead.</p> <pre><code>import re with open('perceive.txt','r') as jawabdo: for harsawal in jawabdo: with open('answers.txt','ab+') as letmethink: for spquestion in letmethink: sawal,jawab = spquestion.split("```") matching = re.match(sawal.lstrip('\r'),harsawal) if matching: size = len(jawab) if(size == 1): jawab = "coming soon" letmethink.write(jawab) print('Answers written successfully!!!') letmethink.close() jawabdo.close() </code></pre> <p><strong>Note:</strong> perceive.txt is the file with keys while answers.txt is the file having key```value pair.</p>
1
2016-09-04T10:59:01Z
39,317,027
<p>There's no possible way to write in a specific place in a text file</p> <p>A good alternative is:</p> <ul> <li>Read the file <code>everything = letmethink.read()</code></li> <li>Insert new data <code>everything = everything[:pos] + new_data + everything[pos + 1:]</code></li> <li>Delete the file <code>letmethink.truncate()</code></li> <li>Completely replace the file <code>letmethink.write(everything)</code></li> </ul> <p>If you don't want to do this then you have to use a database and sqlite3, with which you can insert data in specific locations</p>
1
2016-09-04T12:41:33Z
[ "python", "file-handling" ]
Issue calling method outside class python
39,316,211
<p>I'm working on a python assingment involving creating and using a class with several methods. I won't post the whole thing as it'll be simpler to point out my issue if I instead show an example of what I'm trying to do.</p> <pre><code>class Fruit(self,color,name): def __init__(self, color, name): self.color = color self.name = name def return_list(self, index): print fruit_list[index] fruit_list = [] fruit_1 = Fruit("red", "apple") fruit_list.append(fruit_1.color) fruit_list.append(fruit_1.name) </code></pre> <p>So the above code works. My issue is getting return_list to work when used outside of the class, as so:</p> <pre><code>fruit_choice = int(raw_input("What fruit would you like?")) Fruit.return_list(fruit_choice) </code></pre> <p>Basically I'm trying to create a method that when called, outputs the item at an index within a list, the index being specified by user input (i.e fruit_choice = 0, printed item is first element of list.)</p> <p>I have a basic understanding of classes, but getting a somewhat vague method to work like return_list is a little unintuitive. The error message I get:</p> <pre><code>Fruit.return_list(fruit_choice) TypeError: unbound method return_list() must be called with Fruit instance as first argument (got int instance instead) </code></pre> <p>I know that if I got the code to work the output would be "red" if input was 0 instead of "red,"apple", but that's an issue for another time.</p> <p>If someone could point out to me what I'm doing wrong in creating/calling the return_list method, please and thanks.</p>
0
2016-09-04T11:02:36Z
39,316,333
<p>Basically you are calling an instance method without an instance that's why you are getting this error</p> <pre><code> TypeError: unbound method return_list() must be called with Fruit instance as first argument (got int instance instead) </code></pre> <p>The corrected code</p> <pre><code> fruit_1.return_list(fruit_choice) </code></pre> <p>The way you are doing is the behaviour of static methods, they are called without an instance. Please go through some oops programming like instance methods and static methods in python.</p> <p>Hope it helps :)</p>
1
2016-09-04T11:18:05Z
[ "python", "list", "python-2.7", "class", "methods" ]
Issue calling method outside class python
39,316,211
<p>I'm working on a python assingment involving creating and using a class with several methods. I won't post the whole thing as it'll be simpler to point out my issue if I instead show an example of what I'm trying to do.</p> <pre><code>class Fruit(self,color,name): def __init__(self, color, name): self.color = color self.name = name def return_list(self, index): print fruit_list[index] fruit_list = [] fruit_1 = Fruit("red", "apple") fruit_list.append(fruit_1.color) fruit_list.append(fruit_1.name) </code></pre> <p>So the above code works. My issue is getting return_list to work when used outside of the class, as so:</p> <pre><code>fruit_choice = int(raw_input("What fruit would you like?")) Fruit.return_list(fruit_choice) </code></pre> <p>Basically I'm trying to create a method that when called, outputs the item at an index within a list, the index being specified by user input (i.e fruit_choice = 0, printed item is first element of list.)</p> <p>I have a basic understanding of classes, but getting a somewhat vague method to work like return_list is a little unintuitive. The error message I get:</p> <pre><code>Fruit.return_list(fruit_choice) TypeError: unbound method return_list() must be called with Fruit instance as first argument (got int instance instead) </code></pre> <p>I know that if I got the code to work the output would be "red" if input was 0 instead of "red,"apple", but that's an issue for another time.</p> <p>If someone could point out to me what I'm doing wrong in creating/calling the return_list method, please and thanks.</p>
0
2016-09-04T11:02:36Z
39,316,352
<p>You seem to have a misunderstanding of Classes and class instances.</p> <p>The <code>return_list</code> function you have defined is part of the <code>Fruit</code> class, i.e. each instance of the <code>Fruit</code> class contains this method. But the use of this function, which is to return a specific fruit from fruit list, is independent of the individual <code>Fruit</code> instances, which means this method should not have been in the <code>Fruit</code> class in the first place.</p> <p>The signature of class definition <code>class Fruit(self,color,name)</code> is wrong. It should be <code>class Fruit:</code>. The initial parameters should be defined as parameters to the <code>__init__</code> method.</p> <p>The list <code>fruit_list</code> should contain <code>Fruit</code> instances. The program could be written as:</p> <pre><code>class Fruit: def __init__(self, color, name): self.color = color self.name = name def __str__(self): return 'I am a ' + self.color + ' ' + self.name fruit_list = [] fruit_1 = Fruit("red", "apple") fruit_list.append(fruit_1) fruit_choice = int(raw_input("What fruit would you like?")) print(fruit_list[fruit_choice]) </code></pre> <p>Printing a Python object calls the <code>__str__</code> magic method.</p> <p>If you do really want to have a separate function which returns a <code>Fruit</code> from the <code>fruit_list</code>, you can define a function outside the class (but these seem unnecessary when you can directly access the instance using the index):</p> <pre><code>def return_list(list, index): return list[index] </code></pre> <p>or</p> <pre><code>def return_list(index): global fruit_list return fruit_list[index] </code></pre> <p>If you try to print the entire list using <code>print(fruit_list)</code> the output is:</p> <pre><code>[&lt;__main__.Fruit instance at 0x110091cf8&gt;] </code></pre> <p>That is because Python does not call <code>__str__</code> on each instance when you print a list of instances. You can print the <code>fruit_list</code> by doing:</p> <pre><code>for fruit in fruit_list: print(fruit) </code></pre>
0
2016-09-04T11:19:54Z
[ "python", "list", "python-2.7", "class", "methods" ]
Issue calling method outside class python
39,316,211
<p>I'm working on a python assingment involving creating and using a class with several methods. I won't post the whole thing as it'll be simpler to point out my issue if I instead show an example of what I'm trying to do.</p> <pre><code>class Fruit(self,color,name): def __init__(self, color, name): self.color = color self.name = name def return_list(self, index): print fruit_list[index] fruit_list = [] fruit_1 = Fruit("red", "apple") fruit_list.append(fruit_1.color) fruit_list.append(fruit_1.name) </code></pre> <p>So the above code works. My issue is getting return_list to work when used outside of the class, as so:</p> <pre><code>fruit_choice = int(raw_input("What fruit would you like?")) Fruit.return_list(fruit_choice) </code></pre> <p>Basically I'm trying to create a method that when called, outputs the item at an index within a list, the index being specified by user input (i.e fruit_choice = 0, printed item is first element of list.)</p> <p>I have a basic understanding of classes, but getting a somewhat vague method to work like return_list is a little unintuitive. The error message I get:</p> <pre><code>Fruit.return_list(fruit_choice) TypeError: unbound method return_list() must be called with Fruit instance as first argument (got int instance instead) </code></pre> <p>I know that if I got the code to work the output would be "red" if input was 0 instead of "red,"apple", but that's an issue for another time.</p> <p>If someone could point out to me what I'm doing wrong in creating/calling the return_list method, please and thanks.</p>
0
2016-09-04T11:02:36Z
39,316,370
<p>Here's a possible solution to your problem:</p> <pre><code>class Fruit(): def __init__(self, color, name): self.color = color self.name = name def __str__(self): return "Color: {0} Name: {1}".format(self.color, self.name) class FruitBasket(): def __init__(self): self.fruits = [] def get_fruit(self, index): try: value = self.fruits[index] return value except Exception as e: print "Error with index {0} -&gt; {1}".format(index, e) if __name__ == "__main__": basket = FruitBasket() names = ["apple", "orange", "lemon"] colors = ["green", "orange", "yellow"] for name, color in zip(names, colors): fruit = Fruit(color, name) basket.fruits.append(fruit) print basket.get_fruit(0) print basket.get_fruit(1) print basket.get_fruit(2) basket.get_fruit(3) </code></pre> <p>Few comments about the above code:</p> <ul> <li>Fruit object doesn't have more responsabilities than setting up a fruit with a certain name &amp; color, that's pretty much. One fruit shouldn't contain any list of fruits, that should be the responsability of another object</li> <li>FruitBasket is the container of fruits, you could do perfectly this without using OOP but for the sake of this question, this is a valid option to hold many fruits</li> </ul> <p>With respect to your error, the other answers and comments are already pointing out what's wrong. Also, about <code>class Fruit(self,color,name):</code>, don't do that, in that sentence you're declaring the class type, not the constructor.</p> <p>I'd strongly recommend you try to follow some of the many <a href="https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/" rel="nofollow">OOP python tutorials</a> out there.</p>
0
2016-09-04T11:22:45Z
[ "python", "list", "python-2.7", "class", "methods" ]
Python 3: How to convert array to list of dictionary?
39,316,241
<pre><code>def get_list(name, ids): single_database = {} database = [] for id in ids: single_database['id'] = id single_database['name'] = name database.append(single_database.copy()) return database input = [{'name': 'David', 'id': ['d1','d2']}, {'name':'John', 'id': ['j1','j2']}] for single_database in input: get_list(single_database['name'], single_database['id']) </code></pre> <p>Hello, I want to convert the above "input" array to list of dictionary, so I wrote the code to convert them. However, "get_list" function only release the last dictionary. So, how to get all list of dictionary and keep using "get_list" function. Also, except my way, there is any way to convert this input faster ?</p> <p>This is the output I want:</p> <pre><code>{'id': 'd1', 'name': 'David'} {'id': 'd2', 'name': 'David'} {'id': 'j1', 'name': 'John'} {'id': 'j2', 'name': 'John'} </code></pre>
0
2016-09-04T11:07:32Z
39,316,282
<p>This should work</p> <pre><code>list_of_dicts = [ {'id': id, 'name': d['name']} for d in input for id in d['id'] ] </code></pre> <p>or in a more verbose form:</p> <pre><code>def get_list(input): list_of_dicts = [] for d in input: for id in d['id']: list_of_dicts.append({ 'id': id, 'name': d['name'] }) return list_of_dicts </code></pre> <p>In general, try to avoid temporary variables (like your <code>single_database</code>) and use literals instead.</p> <p>Also, <code>input</code> is a poor choice for a variable name, since it hides an important built-in.</p>
8
2016-09-04T11:11:43Z
[ "python", "arrays", "dictionary" ]
Python 3: How to convert array to list of dictionary?
39,316,241
<pre><code>def get_list(name, ids): single_database = {} database = [] for id in ids: single_database['id'] = id single_database['name'] = name database.append(single_database.copy()) return database input = [{'name': 'David', 'id': ['d1','d2']}, {'name':'John', 'id': ['j1','j2']}] for single_database in input: get_list(single_database['name'], single_database['id']) </code></pre> <p>Hello, I want to convert the above "input" array to list of dictionary, so I wrote the code to convert them. However, "get_list" function only release the last dictionary. So, how to get all list of dictionary and keep using "get_list" function. Also, except my way, there is any way to convert this input faster ?</p> <p>This is the output I want:</p> <pre><code>{'id': 'd1', 'name': 'David'} {'id': 'd2', 'name': 'David'} {'id': 'j1', 'name': 'John'} {'id': 'j2', 'name': 'John'} </code></pre>
0
2016-09-04T11:07:32Z
39,316,287
<p>You can build this in single line of code, Beauty of python</p> <pre><code>result = [{'id':j,'name':i['name']} for i in input_dict for j in i['id']] </code></pre> <p><strong>Result</strong> </p> <pre><code>[{'id': 'd1', 'name': 'David'}, {'id': 'd2', 'name': 'David'}, {'id': 'j1', 'name': 'John'}, {'id': 'j2', 'name': 'John'}] </code></pre>
2
2016-09-04T11:12:28Z
[ "python", "arrays", "dictionary" ]
Change to recognized encoding when reading a text file?
39,316,250
<p>When a text file is open for reading using (say) UTF-8 encoding, is it possible to change encoding during the reading?</p> <p><strong>Motivation:</strong> It hapens that you need to read a text file that was written using non-default encoding. The text format may contain the information about the used encoding. Let an HTML file be the example, or XML, or ASCIIDOC, and many others. In such cases, the lines above the encoding information are allowed to contain only ASCII or some default encoding.</p> <p>In Python, it is possible to read the file in binary mode, and translate the lines of <code>bytes</code> type to <code>str</code> on your own. When the information about the encoding is found on some line, you just switch the encoding to be used when converting the lines to unicode strings.</p> <p>In Python 3, text files are implemented using <code>TextIOBase</code> that defines also the <code>encoding</code> attribute, the <code>buffer</code>, and other things.</p> <p>Is there any nice way to change the encoding information (used for decoding the <code>bytes</code>) so that the next lines would be decoded in the wanted way? </p>
0
2016-09-04T11:09:18Z
39,316,713
<p>Classic usage is:</p> <ul> <li>Open the file in binary format (bytes string)</li> <li>read a chunk and guess the encoding (For instance with a simple scanning or using RegEx)</li> </ul> <p>Then:</p> <ul> <li>close the file and re-open it in text mode with the found encoding Or</li> <li>move to the beginning: seek(0), read the whole content as a bytes string then decode the content using the found encoding.</li> </ul> <p>See this example: <a href="http://code.activestate.com/recipes/363841-detect-character-encoding-in-an-xml-file/" rel="nofollow">Detect character encoding in an XML file (Python recipe)</a> <em>note:</em> the code is a little old, but useful.</p>
1
2016-09-04T12:05:10Z
[ "python", "file", "python-3.x", "encoding" ]
Sending data from html to database
39,316,259
<p>The following partial code is a mix of HTML and python. Where a products' values (<code>item_name, description, item_price</code>) of the table <code>products</code> from my database are laid out on HTML and has a "add to cart" input button next to each item.</p> <pre><code>{% for product in products %} &lt;li&gt; &lt;b&gt;Name/Model:&lt;/b&gt; {{ product['item_name'] }}&lt;br&gt; &lt;b&gt;Description:&lt;/b&gt; {{ product['description'] }}&lt;br&gt; &lt;b&gt;Price: &lt;/b&gt; {{ product['item_price'] }}$ &lt;input type="submit" value="Add to cart"/&gt; &lt;/li&gt; {% endfor %} </code></pre> <p>When add to cart is pressed, is there a way to send the information of the product next to that button to my other table called item_cart? </p> <p>I'm very very new to this kind of mixed language projects, if you need extra code to help you help solve my problem ask in the comments and i will share the part of code you need.</p>
0
2016-09-04T11:10:35Z
39,317,213
<p>Yes you can, you just need to create a view to do it.</p> <p>Your view will have a parameter that will take <code>product.product_id</code>, like so:</p> <pre><code>def addToCart(request, product_id): p = Product.objects.filter(product_id = product_id) #put the product in your member's cart table, </code></pre> <p>Then in your template, your "add to cart" input button will call:</p> <pre><code>"/addToCart/{{ product.product_id }}/" </code></pre> <p>I hope this gives you some direction.</p>
0
2016-09-04T13:05:29Z
[ "python", "django", "django-forms" ]
How to make sure output is same length?
39,316,275
<p>I want to know is there a way in python to make sure that the output is the same length , by adding white space or something like that.</p> <pre><code>78364721 apple 3 3 9 35619833 orange 4 2 8 46389121 chicken 1 10 10 total price of order £ 27 </code></pre> <p>I want :</p> <pre><code>78364721 apple 3 3 9 35619833 orange 4 2 8 46389121 chicken 1 10 10 total price of order £ 27 </code></pre> <p>Current Code :</p> <pre><code>All_list=[items,product_list,items2,indprice_list,newprice_list] for a in zip(*All_list): print(*a) print("total price of order","£",total_price) 46389121 chicken 2 10 20 total price of order £ 40 46389121 chicken 2 10 20 total price of order £ 40 </code></pre>
0
2016-09-04T11:11:19Z
39,316,464
<p>Here's a simple example using <a href="https://docs.python.org/3/library/string.html#format-string-syntax" rel="nofollow">format string syntax</a>:</p> <pre><code># -*- coding: utf-8 -*- dataframe = [ [78364721, "apple", 3, 3, 9], [35619833, "orange", 4, 2, 8], [46389121, "chicken", 1, 10, 10] ] for row in dataframe: print('{:8d} {:10s}{:3d}{:3d}{:3d}'.format( row[0], row[1], row[2], row[3], row[4])) print('total price of order \u00a3 {0}'.format( sum([row[4] for row in dataframe]))) </code></pre> <p>If you want anything fancier than this I'd recommend you start using <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a></p>
0
2016-09-04T11:33:15Z
[ "python", "python-3.x" ]
Error while stemming arabic text in file using ISRIStemmer
39,316,345
<p>I am trying to stem the contents of a text file (text.txt) in Arabic Language using nltk.stem.isri . The text.txt file contains the following Arabic text:</p> <p>تتنوع المشاعر التي يشعر بها الإنسان خلال حياته، وتكون هذه المشاعر تبعاً لمواقف أو أشخاص معينين، ويعتبر الحب أحد المشاعر الجميلة التي تصيب الإنسان فتغير من نظرته للعالم من حوله ويصبح إيجابياً أكثر، وهي العلاقة العاطفية التي تجمع بين الرجل والمرأة أو بين الأشخاص المختلفين في حياته، وما تجره من مشاعر الاهتمام والمودة واللطف. الحب أيضاً حالةٌ من الانجذاب والإعجاب بين الأشخاص، ويقال بأنه نوعٌ من الكيمياء المتبادلة، إذ يعبر عن نوعٍ من التفاعل بين الناس، وفي الحب يفرز الجسم هرمون الأوكسيتوسين وهو الهرمون الذي يدعى بهرمون المحبين والمحبة الذي يفرزه الجسم فور اللقاء بين الأحبة، وفيما يلي من سطورٍ سنتحدث عن بعض المعلومات العامة حول الحب بشيءٍ من التفصيل والتوضيح.</p> <p>I used the following code by referring to a previous question: <a href="http://stackoverflow.com/questions/16835372/python-stemming-words-in-a-file">Python Stemming words in a File</a></p> <pre><code># -*- coding: UTF-8 -*- from nltk.stem.isri import ISRIStemmer def stemming_text_1(): with open('test.txt', 'r') as f: for line in f: print line singles = [] stemmer = ISRIStemmer() for plural in line.split(): singles.append(stemmer.stem(plural)) print ' '.join(singles) stemming_text_1() </code></pre> <p>It prints the contents of the file and this error:</p> <pre><code>/home/waheeb/anaconda2/lib/python2.7/site-packages/nltk/stem/isri.py:154: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal if token in self.stop_words: Traceback (most recent call last): File "Arabic_stem.py", line 15, in &lt;module&gt; stemming_text_1() File "Arabic_stem.py", line 12, in stemming_text_1 singles.append(stemmer.stem(plural)) File "/home/waheeb/anaconda2/lib/python2.7/site-packages/nltk/stem /isri.py", line 156, in stem token = self.pre32(token) # remove length three and length two prefixes in this order File "/home/waheeb/anaconda2/lib/python2.7/site-packages/nltk/stem /isri.py", line 198, in pre32 if word.startswith(pre3): UnicodeDecodeError: 'ascii' codec can't decode byte 0xd8 in position 0: ordinal not in range(128) </code></pre>
0
2016-09-04T11:19:20Z
39,316,537
<p>Try decoding the lines from the file to <em>unicode</em> before passing it to the stemmer. I am assuming that your input file is encoded as UTF8 (seems likely looking at the error), however, you can change the encoding as suits:</p> <pre><code>for line in f: line = line.decode('utf8') # use the correct encoding here ... </code></pre> <p>Alternatively you can use <a href="https://docs.python.org/2/library/io.html#io.open" rel="nofollow"><code>io.open()</code></a>, specify the encoding, and Python will decode the incoming stream to unicode:</p> <pre><code>with io.open('test.txt', encoding='utf8') as f: ... </code></pre>
1
2016-09-04T11:41:53Z
[ "python", "nltk", "arabic" ]
Get continuous dataframe in pandas by filling the missing month with 0
39,316,392
<p>I have a pandas dataframe as shown below where I have Month-Year, need to get the continuous dataframe which should include count as 0 if no rows are found for that month. Excepcted output is shown below. </p> <h2>Input dataframe</h2> <pre><code>Month | Count -------------- Jan-15 | 10 Feb-15 | 100 Mar-15 | 20 Jul-15 | 10 Sep-15 | 11 Oct-15 | 1 Dec-15 | 15 </code></pre> <h2>Expected Output</h2> <pre><code>Month | Count -------------- Jan-15 | 10 Feb-15 | 100 Mar-15 | 20 Apr-15 | 0 May-15 | 0 Jun-15 | 0 Jul-15 | 10 Aug-15 | 0 Sep-15 | 11 Oct-15 | 1 Nov-15 | 0 Dec-15 | 15 </code></pre>
-5
2016-09-04T11:25:02Z
39,316,502
<p>You can set the Month column as the index. It looks like Excel input, if so, it will be parsed at 01.01.2015 so you can resample it as follows:</p> <pre><code>df.set_index('Month').resample('MS').asfreq().fillna(0) Out: Count Month 2015-01-01 10.0 2015-02-01 100.0 2015-03-01 20.0 2015-04-01 0.0 2015-05-01 0.0 2015-06-01 0.0 2015-07-01 10.0 2015-08-01 0.0 2015-09-01 11.0 2015-10-01 1.0 2015-11-01 0.0 2015-12-01 15.0 </code></pre> <p>If the month column is not recognized as date, you need to convert it first:</p> <pre><code>df['Month'] = pd.to_datetime(df['Month'], format='%b-%y') </code></pre>
1
2016-09-04T11:37:45Z
[ "python", "pandas", "resampling" ]
Multidimensionnal array class and line object in Python
39,316,443
<p>I have a question that spawned from writing my own class to manage a two-dimension table.</p> <p>I started by creating a simple class as follows, creating an empty_line object that was copied as much as needed to create the number of lines:</p> <pre><code>class Table(object): """Table class, allows the creation of new lines and columns to the table""" def __init__(self, col = 1, lines = 1, defaultcontent=''): self.columns = col self.lines = lines self.empty_line = [defaultcontent for i in range(self.columns)] self.table = [self.empty_line for j in range(self.lines)] def add_line(self): self.table.append(self.empty_line) self.lines += 1 def add_column(self): self.empty_line.append('') for i in range(self.lines): self.table[i].append('') </code></pre> <p>However, after I created a table, for example with <code>table = Table(5,3)</code>, and do an assignment with <code>table.table[1][2] = 'something'</code>, I realised the <code>'something'</code> found itself in every line, and that I couldn't change a single line without having the others changed. Also, <code>self.empty_line</code> was changed.</p> <p>After a little while, I wrapped my head around the problem being in the <code>self.empty_line</code> usage. I rewrote my class, this time taking out the <code>self.empty_line</code> and replacing it with the primitive <code>['' for i in range(self.columns)]</code> (and of course also correcting the bug in the <code>add_column()</code> method that would add two columns instead of just one!).</p> <p>My problem went away, but a question still lingers: Shouldn't the <code>self.table = [self.empty_line for j in range(self.lines)]</code> create a copy of the <code>self.empty_line</code> object for every new line, instead of somehow 'linking' the same <code>self.empty_line</code> instance (that gets changed).</p> <p>So what am I doing wrong, and where is the hole in my knowledge about python objects?</p>
1
2016-09-04T11:30:50Z
39,316,572
<p>In your code:</p> <pre><code>self.empty_line = [defaultcontent for i in range(self.columns)] self.table = [self.empty_line for j in range(self.lines)] </code></pre> <p>The empty_line is copied in every line of the table using swallow copy. You copied only references, not the default content.</p> <p>To fix that:</p> <pre><code>self.table = [[default_content] * self.columns for _ in range(self.lines)] </code></pre> <p>Same problem with add_line. Don't store empty_line but use default_content instead.</p> <pre><code>self.table.append([self.default_content] * self.columns) ... </code></pre> <p>See: <a href="http://stackoverflow.com/questions/28684154/python-copy-a-list-of-lists">Python copy a list of lists</a></p>
1
2016-09-04T11:45:14Z
[ "python", "object", "multidimensional-array" ]
OpenCV giving wrong color to colored images on loading
39,316,447
<p>I'm loading in a color image in Python OpenCV and plotting the same. However, the image I get has it's colors all mixed up. </p> <p>Here is the code:</p> <pre><code>import cv2 import numpy as np from numpy import array, arange, uint8 from matplotlib import pyplot as plt img = cv2.imread('lena_caption.png', cv2.IMREAD_COLOR) bw_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) images = [] images.append(img) images.append(bw_img) titles = ['Original Image','BW Image'] for i in xrange(len(images)): plt.subplot(1,2,i+1),plt.imshow(images[i],'gray') plt.title(titles[i]) plt.xticks([]),plt.yticks([]) plt.show() </code></pre> <p>Here is the original image: <a href="http://i.stack.imgur.com/o9G7e.png" rel="nofollow"><img src="http://i.stack.imgur.com/o9G7e.png" alt="enter image description here"></a></p> <p>And here is the plotted image: <a href="http://i.stack.imgur.com/KagWq.png" rel="nofollow"><img src="http://i.stack.imgur.com/KagWq.png" alt="enter image description here"></a></p>
0
2016-09-04T11:31:18Z
39,316,695
<p>OpenCV uses BGR as its default colour order for images, matplotlib uses RGB. When you display an image loaded with OpenCv in matplotlib the channels will be back to front. </p> <p>The easiest way of fixing this is to use OpenCV to explicitly convert it back to RGB, much like you do when creating the greyscale image.</p> <pre><code> RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) </code></pre> <p>And then use that in your plot.</p>
2
2016-09-04T12:01:29Z
[ "python", "image", "opencv", "colors" ]
Should functions take extra arguments for the sake of testing?
39,316,449
<p>I am writing tests for a program I intend to write that checks for certain lines in configuration files.</p> <p>For example, the program might check that the line: AllowConnections- is contained in the file SomeFile.conf.</p> <p>My function stub does not take any arguments because I know the file that I am going to be checking.</p> <p>I am trying to write a tests for this function that check the behavior for different SomeFile.conf files, but I don't see how I could do this. It is possible to change SomeFile.conf in the setup and teardown test functions, but this seems like a bad way to test. Should I change the function so that it can accept a file argument just for the sake of testing?</p>
0
2016-09-04T11:31:28Z
39,316,506
<p>It would be quite possible to define the function as</p> <pre><code>def checkline_in_file(filename="SomeFile.conf"): </code></pre> <p>Using a default value for the filename. In testing it can be overridden. In production you don't need to give it an argument.</p> <p>Later on, when phb decides that all file extensions must have exactly 3 characters, it is a one character change.</p>
0
2016-09-04T11:38:03Z
[ "python", "testing" ]
Should functions take extra arguments for the sake of testing?
39,316,449
<p>I am writing tests for a program I intend to write that checks for certain lines in configuration files.</p> <p>For example, the program might check that the line: AllowConnections- is contained in the file SomeFile.conf.</p> <p>My function stub does not take any arguments because I know the file that I am going to be checking.</p> <p>I am trying to write a tests for this function that check the behavior for different SomeFile.conf files, but I don't see how I could do this. It is possible to change SomeFile.conf in the setup and teardown test functions, but this seems like a bad way to test. Should I change the function so that it can accept a file argument just for the sake of testing?</p>
0
2016-09-04T11:31:28Z
39,316,539
<p>The code you test, and the code you run should be same.</p> <p>I do not recommend using a filename, because now you are dealing with (in one function) opening the file - and the errors associated with that part, and then confirming the file format (the actual purpose of the function).</p> <p>It sounds to me that your function's job is to check if the file's contents contain a specific string. So, this function should take any type of content element (an iterable) and then as long as the key string is not found, the function should return None/False/Fail condition - and your test should check for that.</p>
1
2016-09-04T11:42:11Z
[ "python", "testing" ]
App Engine module import issue
39,316,511
<p>I am writing unit tests for a Flask based application running on App Engine. </p> <p>As per the <a href="https://cloud.google.com/appengine/docs/python/tools/localunittesting" rel="nofollow">documentation</a>, I have included the following lines</p> <pre><code>import sys sys.path.insert(1, '/Users/vinay/tools/google_appengine') sys.path.insert(1, '/Users/vinay/tools/google_appengine/lib/yaml/lib') sys.path.insert(1, '/Users/vinay/App-Engine/zion-alpha/lib') </code></pre> <p>Here is the full test file. </p> <pre><code>import sys sys.path.insert(1, '/Users/vinay/tools/google_appengine') sys.path.insert(1, '/Users/vinay/tools/google_appengine/lib/yaml/lib') sys.path.insert(1, '/Users/vinay/App-Engine/zion-alpha/lib') from pprint import pprint pprint(sys.path) from google.appengine.ext import ndb from webtest import TestApp from app import create_app from Tests.base_test import TestBase app = TestApp(create_app()) class AppTest(TestBase): def test_index(self): response = app.get('/') self.assertEqual(response.content_type, 'text/plain') self.assertEqual('Hello World', response.body) </code></pre> <p>When I run this script I get the following error. </p> <pre><code>/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Applications/PyCharm.app/Contents/helpers/pycharm/utrunner.py /Users/vinay/App-Engine/zion-alpha/Tests/handler_tests.py true Testing started at 10:31 AM ... Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pycharm/utrunner.py", line 121, in &lt;module&gt; modules = [loadSource(a[0])] File "/Applications/PyCharm.app/Contents/helpers/pycharm/utrunner.py", line 43, in loadSource module = imp.load_source(moduleName, fileName) File "/Users/vinay/App-Engine/zion-alpha/Tests/handler_tests.py", line 10, in &lt;module&gt; from google.appengine.ext import ndb ImportError: No module named appengine.ext ['/Users/vinay/App-Engine/zion-alpha/Tests', '/Users/vinay/App-Engine/zion-alpha/lib', '/Users/vinay/tools/google_appengine/lib/yaml/lib', '/Users/vinay/tools/google_appengine', '/Library/Python/2.7/site-packages/python_gflags-2.0-py2.7.egg', '/Library/Python/2.7/site-packages/xunitparser-1.3.3-py2.7.egg', '/Library/Python/2.7/site-packages/setuptools-20.6.7-py2.7.egg', '/Library/Python/2.7/site-packages', '/Users/vinay/tools/google_appengine/lib/apiclient', '/Users/vinay/tools/google_appengine/lib/markupsafe-0.15', '/Users/vinay/tools/google_appengine/lib/concurrent', '/Users/vinay/tools/google_appengine/lib/distutils', '/Users/vinay/tools/google_appengine/lib/httplib2', '/Users/vinay/tools/google_appengine/lib/fancy_urllib', '/Users/vinay/tools/google_appengine/lib/oauth2client', '/Users/vinay/tools/google_appengine/lib/cacerts', '/Users/vinay/tools/google_appengine/lib/requests', '/Users/vinay/tools/google_appengine/lib/cherrypy', '/Users/vinay/tools/google_appengine/lib/ipaddr', '/Users/vinay/tools/google_appengine/lib/prettytable', '/Users/vinay/tools/google_appengine/lib/grizzled', '/Users/vinay/App-Engine/zion-alpha/lib', '/Users/vinay/tools/google_appengine/lib/rsa', '/Users/vinay/tools/google_appengine/lib/oauth2', '/Users/vinay/tools/google_appengine/lib/pyasn1', '/Users/vinay/tools/google_appengine/lib/sqlcmd', '/Users/vinay/tools/google_appengine/lib/webob-1.2.3', '/Users/vinay/tools/google_appengine/lib/antlr3', '/Users/vinay/tools/google_appengine/lib/jinja2-2.6', '/Users/vinay/tools/google_appengine/lib/endpoints-1.0', '/Users/vinay/tools/google_appengine/lib/graphy', '/Users/vinay/tools/google_appengine/lib/websocket', '/Users/vinay/tools/google_appengine/lib/google-api-python-client', '/Users/vinay/tools/google_appengine/lib/setuptools-0.6c11', '/Users/vinay/tools/google_appengine/lib/yaml-3.10', '/Users/vinay/tools/google_appengine/lib/docker', '/Users/vinay/tools/google_appengine', '/Users/vinay/tools/google_appengine/lib/mox', '/Users/vinay/tools/google_appengine/lib/django-1.9', '/Users/vinay/tools/google_appengine/lib/six', '/Users/vinay/tools/google_appengine/lib/webapp2-2.5.2', '/Users/vinay/tools/google_appengine/lib/deprecated_enum', '/Users/vinay/tools/google_appengine/lib/portpicker', '/Users/vinay/tools/google_appengine/lib/argparse', '/Users/vinay/tools/google_appengine/lib/uritemplate', '/Users/vinay/tools/google_appengine/lib/protorpc-1.0', '/Users/vinay/tools/google_appengine/lib/PyAMF-0.7.2', '/Users/vinay/tools/google_appengine/lib/simplejson', '/Users/vinay/App-Engine/zion-alpha', '/Users/vinay/tools/google_appengine/lib/PyAMF-0.6.1', '/Users/vinay/tools/google_appengine/lib/pyasn1_modules', '/Users/vinay/tools/google_appengine/lib/python-gflags', '/Applications/PyCharm.app/Contents/helpers/pycharm', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/var/root/Library/Python/2.7/lib/python/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages'] Process finished with exit code 1 </code></pre> <p>The package is located at the right location. </p> <pre><code>bash-3.2$ ls google_appengine google_appengine_1.9.40.zip bash-3.2$ pwd /Users/vinay/tools bash-3.2$ </code></pre>
0
2016-09-04T11:38:37Z
39,319,017
<p>Looks like you don't have the <code>google_appengine</code> package where you think you do. You will not see an error if you try to add a nonexistent path to your sys path. Add this between lines 5 and 7 to check your path:</p> <pre><code>from pprint import pprint pprint(sys.path) </code></pre> <p>Check for more than 1 appengine packs in paths. Navigate to each to make sure it's really there.</p>
0
2016-09-04T16:21:45Z
[ "python", "python-2.7", "google-app-engine" ]
Python pandas conditional column dealing with None
39,316,521
<p>If I have pandas data like this:</p> <pre><code>s1 s2 s3 1 None 1 1 2 1 2 2 2 1 2 None </code></pre> <p>I want to add a new column 's' whose value will be None if the values of s1, s2 and s3 don't match. If they match (I want to ignore None in this comparision) the value should be the common value. So the output will be </p> <pre><code>s1 s2 s3 s 1 None 1 1 (Ignoring None in comparision here) 1 2 1 None 2 2 2 2 1 2 None None </code></pre> <p>What is the best way to introduce this new conditional column in pandas?</p>
1
2016-09-04T11:39:26Z
39,316,584
<p>Assuming your columns are numeric and None's are treated as NaN's, you can do:</p> <pre><code>df['s'] = np.where(df.std(axis=1)==0, df.mean(axis=1), np.nan) df Out: s1 s2 s3 s 0 1 NaN 1.0 1.0 1 1 2.0 1.0 NaN 2 2 2.0 2.0 2.0 3 1 2.0 NaN NaN </code></pre> <p>This is based on the fact that if all values are equal, the standard deviation of that row will be 0, and the mean will be equal to the those numbers. Both mean and the standard deviation calculations ignore NaNs. </p> <p>If the first assumption is not correct, please replace None's first:</p> <pre><code>df = df.replace({'None': np.nan}) </code></pre> <p>where np is numpy (<code>import numpy as np</code>).</p>
1
2016-09-04T11:46:46Z
[ "python", "pandas" ]
How to do sum in Loop
39,316,646
<p>I have a exercise ,Input data will contain the total count of pairs to process in the first line. The following lines will contain pairs themselves - one pair at each line. Answer should contain the results separated by spaces. My code:</p> <pre><code> n = int(raw_input()) sum = 0 for i in range(n): y = raw_input().split(" ") for i in y: sum = sum + int(i) print sum </code></pre> <p>With my code , I come the Sum together, but I will that the results to come separated by spaces . Thanks for yours help .</p>
-2
2016-09-04T11:54:52Z
39,316,746
<p>Uh oh, it looks like you're reusing the same variable <code>i</code> in the inner loop as the outer loop -- this is bad practice and can lead to bugs down the road. </p> <p>What you're doing currently is adding both elements in each pair to sum and then printing that at the end, you can fix this in two different ways.</p> <ol> <li><p>You can sum each pair, convert the sum to a string, and then concatenate that with your the rest of the sums as strings, or</p></li> <li><p>You can print the sum of each pair immediately after summing them with <code>print sum,</code> which will print the number without the newline so that you can print all the results on a single line.</p></li> </ol>
0
2016-09-04T12:08:16Z
[ "python", "loops", "sum" ]
How to do sum in Loop
39,316,646
<p>I have a exercise ,Input data will contain the total count of pairs to process in the first line. The following lines will contain pairs themselves - one pair at each line. Answer should contain the results separated by spaces. My code:</p> <pre><code> n = int(raw_input()) sum = 0 for i in range(n): y = raw_input().split(" ") for i in y: sum = sum + int(i) print sum </code></pre> <p>With my code , I come the Sum together, but I will that the results to come separated by spaces . Thanks for yours help .</p>
-2
2016-09-04T11:54:52Z
39,317,164
<p>with your current code what you get is the total sum of all the given numbers, to get the sum per line you need to initialize your counter in the outer loop, and then print it, and as you want to print all it in the same line there are several ways to do it, like save it in a list or telling <a href="https://docs.python.org/2/reference/simple_stmts.html#print" rel="nofollow">print</a> that don't print a new, line which is done by adding a <code>,</code> at the end like <code>print x,</code> with that in mind then the changes needed are</p> <pre><code>n = int(raw_input()) for i in range(n): pairs = raw_input().split() #by default split use spaces pair_sum = 0 for p in pairs: pair_sum += int(p) # a += b is the same as a = a + b print pair_sum, print "" # to print a new line so any future print is not done in the same line as the previous one </code></pre> <p>that was the version with print per line, next is the version using list</p> <pre><code>n = int(raw_input()) resul_per_line = [] for i in range(n): pairs = raw_input().split() #by default split use spaces pair_sum = 0 for p in pairs: pair_sum += int(p) # a += b is the same as a = a + b resul_per_line.append( str(pair_sum) ) #conver each number to a string to use with join bellow print " ".join(resul_per_line) </code></pre> <p>with either of the above let said for example that the input data is</p> <pre><code>3 1 2 40 50 600 700 </code></pre> <p>then the result would be</p> <pre><code>3 90 1300 </code></pre> <hr> <p>some parts of the above code can be simplify by using <a href="https://docs.python.org/2/library/functions.html#print" rel="nofollow">built in</a> functions like <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map</code></a> and <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum</code></a>, for example this part</p> <pre><code> pair_sum = 0 for p in pairs: pair_sum += int(p) </code></pre> <p>can become</p> <pre><code> pair_sum = sum( map(int,pairs) ) </code></pre>
0
2016-09-04T13:00:08Z
[ "python", "loops", "sum" ]
How to import from Qt:: namespase (Qt5, Python3.x)?
39,316,693
<p>For my application I need to set some widget parameters like alignment (<code>Qt::AlignBottom</code>) and others. But I can't import them (other PyQt5 staff imports withot any issues).</p> <p>Using this code</p> <pre><code>from PyQt5 import Qt progressBar = QProgressBar(splash) progressBar.setAlignment(Qt.AlignBottom) </code></pre> <p>I got following error:</p> <pre><code>Traceback (most recent call last): File "run_app.py", line 50, in &lt;module&gt; runSemApp(sys.argv) File "run_app.py", line 32, in runSemApp progressBar.setAlignment(Qt.AlignBottom) AttributeError: 'module' object has no attribute 'AlignBottom' </code></pre> <p>And using this one works:</p> <pre><code>from PyQt5.Qt import * progressBar = QProgressBar(splash) progressBar.setAlignment(Qt.AlignBottom) </code></pre> <p>Though I have working sollution I would like to import only <code>Qt.AlignBottom</code> and not <code>*</code>. And why <code>Qt.AlignBottom</code> doesn't work with <code>from PyQt5 import Qt</code>?</p>
1
2016-09-04T12:01:12Z
39,317,267
<p>You can do this</p> <pre><code>&gt;&gt;&gt; from PyQt5.QtCore import Qt &gt;&gt;&gt; Qt.AlignBottom 64 &gt;&gt;&gt; </code></pre> <p>You can't import <code>AlignBottom</code> only because QtCore is not a package itself, it's just a module on it's own (a single file). it's important to know that <strong>all packages are modules, but not all modules are packages</strong></p> <p>so this won't work</p> <pre><code>import PyQt5.QtCore.Qt ImportError: No module named 'PyQt5.QtCore.Qt'; 'PyQt5.QtCore' is not a package &gt;&gt;&gt; import PyQt5.QtCore &gt;&gt;&gt; QtCore &lt;module 'PyQt5.QtCore' from '/usr/lib/python3.5/site-packages/PyQt5/QtCore.so'&gt; &gt;&gt;&gt; import PyQt5 &gt;&gt;&gt; PyQt5 &lt;module 'PyQt5' from '/usr/lib/python3.5/site-packages/PyQt5/__init__.py'&gt; &gt;&gt;&gt; </code></pre> <p>Looking at the output you can see that <code>QtCore</code> is a single file which contains a class <code>Qt</code> that contains other classes and methods on which <code>AlignBottom</code> is part of, you can see that with.</p> <pre><code>&gt;&gt;&gt; from PyQt5.QtCore import Qt &gt;&gt;&gt; help(Qt) </code></pre> <p>On the otherhand PyQt5 is a package (folder containing other modules) points to it's <code>__init__.py</code></p> <p>i'll suggest you read the <a href="https://docs.python.org/3/tutorial/modules.html" rel="nofollow">docs</a> on Modules and this <a href="http://stackoverflow.com/questions/7948494/whats-the-difference-between-a-python-module-and-a-python-package">SO</a> question</p>
1
2016-09-04T13:11:39Z
[ "python", "qt", "python-3.x", "pyqt5" ]
How to import from Qt:: namespase (Qt5, Python3.x)?
39,316,693
<p>For my application I need to set some widget parameters like alignment (<code>Qt::AlignBottom</code>) and others. But I can't import them (other PyQt5 staff imports withot any issues).</p> <p>Using this code</p> <pre><code>from PyQt5 import Qt progressBar = QProgressBar(splash) progressBar.setAlignment(Qt.AlignBottom) </code></pre> <p>I got following error:</p> <pre><code>Traceback (most recent call last): File "run_app.py", line 50, in &lt;module&gt; runSemApp(sys.argv) File "run_app.py", line 32, in runSemApp progressBar.setAlignment(Qt.AlignBottom) AttributeError: 'module' object has no attribute 'AlignBottom' </code></pre> <p>And using this one works:</p> <pre><code>from PyQt5.Qt import * progressBar = QProgressBar(splash) progressBar.setAlignment(Qt.AlignBottom) </code></pre> <p>Though I have working sollution I would like to import only <code>Qt.AlignBottom</code> and not <code>*</code>. And why <code>Qt.AlignBottom</code> doesn't work with <code>from PyQt5 import Qt</code>?</p>
1
2016-09-04T12:01:12Z
39,349,139
<p>I think the confusion here is that PyQt has a special virtual module called <code>Qt</code>, which imports <em>everything</em> into a single namespace. This is a quite useful feature, but it's a real shame that the name clash with <code>QtCore.Qt</code> wasn't avoided.</p> <p>In the first example, the error can be "fixed" by using the somewhat weird-looking <code>Qt.Qt.AlignBottom</code>. But obviously, explicitly importing from <code>QtCore</code> is a much better solution. It's also worth noting that the <code>PyQt5</code> package is a lazy loader, so <code>import PyQt5</code> will just import an empty namespace with no access to the other modules.</p>
2
2016-09-06T12:33:36Z
[ "python", "qt", "python-3.x", "pyqt5" ]
How should I multiply 1d-array in 3d-array by 2d-matrix with numpy
39,316,715
<p>I want bellow calculation.Values used in this example are variable in real case.</p> <pre><code> A = [[1,1,1],[2,1,1]] B =[[[1,2,3],[2,2,2]],[[1,1,2],[1,1,1]]] result = apply_some_function(A,B) &gt;&gt; result = [[[6,7],[6,8]], [[4,5],[3,4]]] </code></pre> <p>Is their any efficient way satisfy above calculation with numpy. In fact, I don't understand clearly how to applicate numpy for multi dimensional array. So if you know helpful document to understand manipulation multi dimensional array rules, I'm very glad if you let me know.</p>
0
2016-09-04T12:05:13Z
39,316,801
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow"><code>np.tensordot</code></a> or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>. </p> <pre><code>In [19]: np.tensordot(B, A, (-1, -1)) Out[19]: array([[[6, 7], [6, 8]], [[4, 5], [3, 4]]]) In [20]: np.einsum('ij,klj-&gt;kli', A, B) Out[20]: array([[[6, 7], [6, 8]], [[4, 5], [3, 4]]]) </code></pre> <hr> <p>Both of these functions compute sums of products. Thus, they are generalizations of matrix multiplication. </p> <p>It is often helpful to pay attention to the shape of the arrays. If we make <code>A</code>, <code>B</code>, and <code>result</code> NumPy arrays:</p> <pre><code>A = np.array([[1,1,1],[2,1,1]]) B = np.array([[[1,2,3],[2,2,2]],[[1,1,2],[1,1,1]]]) result = np.array([[[6,7],[6,8]], [[4,5],[3,4]]]) </code></pre> <p>then </p> <pre><code>In [6]: A.shape Out[6]: (2, 3) In [7]: B.shape Out[7]: (2, 2, 3) In [9]: result.shape Out[9]: (2, 2, 2) </code></pre> <p>Notice that the axis of length 3 in <code>A</code> and <code>B</code> disappears in <code>result</code>. That suggests the sum (of products) is being taken over the last axis of <code>A</code> and <code>B</code>. </p> <p>The <code>(-1, -1)</code> in <code>np.tensordot(B, A, (-1, -1))</code> tells <code>np.tensordot</code> to sum over the last axes of <code>A</code> and <code>B</code>.</p> <p>Similarly, the <code>'ij,klj-&gt;kli'</code> in <code>np.einsum('ij,klj-&gt;kli', A, B)</code> says that if <code>A</code> has indices <code>i</code> and <code>j</code> and if <code>B</code> has indices <code>k</code>, <code>l</code> and <code>j</code>, then the result should have indices <code>k</code>,<code>l</code>,<code>i</code>. Notice the <code>j</code> index disappears. The <code>j</code> index is the last index in <code>A</code> and <code>B</code>. Thus, <code>'ij,klj-&gt;kli'</code> tells <code>np.einsum</code> to sum over the last index of <code>A</code> and <code>B</code>.</p> <p>The only thing left to do is figure out the correct order of the <code>k</code>, <code>l</code> and <code>i</code> indices. Since each axis in <code>result</code> has the same length, the shape of the <code>result</code> gives no clue. I found the correct order by trial and error.</p>
3
2016-09-04T12:13:53Z
[ "python", "arrays", "numpy" ]
Python - Minimum of list of tuples using min(list, key=func) how to improve efficiency
39,316,823
<p>Given a list <code>templates</code> of tuples <code>(region, calc_3d_harmonics(region))</code> where <code>calc_3d_harmonics</code> is some function that returns a signature for each region, I need to find the region with the minimal score (the actual score doesn't matter).</p> <p>The score of a region is given by <code>calc_harmonics_distance(calc_3d_harmonics(region),query_harmonics, radius)</code>, a function that calculates the distance between two harmonic signatures given some radius (query_harmonics and radius are computed beforehand). </p> <p>My current solution is:</p> <pre><code>query_harmonics = calc_3d_harmonics(query_region) ref_region, score = min(templates, key=lambda t: calc_3d_harmonics_distance(t[1], query_harmonics, radius)) </code></pre> <p>A team member suggested that I use the following instead:</p> <pre><code>query_harmonics = calc_3d_harmonics(query_region) ref_region, score = min([(t[0], calc_harmonics_distance(t[1], query_harmonics, radius)) for t in templates], key=lambda x: x[1]) </code></pre> <p>Note: Both <code>calc_3d_harmonics</code> and <code>calc_harmonics_distance</code> are very slow and heavy functions. Also, <code>score</code> can be replace by <code>_</code>.</p> <p>He claims that his suggestion might result in a better runtime (although it would not be significant since the harmonics functions are the major operations). If <code>min(list, key=func)</code> creates a list of the keys, then our versions are equivalent (and mine's shorter), but if it computes the key every time he thinks mine will be slower.</p> <p>Which way is faster? I think there must be a better (runtime-wise) way to do this (perhaps using numpy?) and would like to hear some suggestions.</p>
1
2016-09-04T12:17:23Z
39,317,001
<p>When in doubt, do not guess, <a href="https://docs.python.org/3/library/profile.html" rel="nofollow">profile it</a>.</p> <p>Putting all of your code behind, we may refer to cPython implementation. We can see, that <code>min</code> function uses <a href="https://github.com/python/cpython/blob/master/Python/bltinmodule.c#L1482" rel="nofollow"><code>min_max</code> helper</a>. In this helper we can locate where <a href="https://github.com/python/cpython/blob/master/Python/bltinmodule.c#L1520" rel="nofollow">key function is computed</a>.</p> <p>Minimal excerpt would be:</p> <pre><code>while (( item = PyIter_Next(it) )) { /* get the value from the key function */ if (keyfunc != NULL) { val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL); if (val == NULL) goto Fail_it_item; } /* no key function; the value is the item */ else { val = item; Py_INCREF(val); } // comparision logic for min/max } </code></pre> <p>Source code states clearly that key function is computed once for each element in sorted iterable. On the other hand, key function result is thrown away after sorting is complete. So case comes down to if you are planning on reusing key function values later.</p>
0
2016-09-04T12:38:36Z
[ "python", "list", "numpy", "tuples", "min" ]
Python - Minimum of list of tuples using min(list, key=func) how to improve efficiency
39,316,823
<p>Given a list <code>templates</code> of tuples <code>(region, calc_3d_harmonics(region))</code> where <code>calc_3d_harmonics</code> is some function that returns a signature for each region, I need to find the region with the minimal score (the actual score doesn't matter).</p> <p>The score of a region is given by <code>calc_harmonics_distance(calc_3d_harmonics(region),query_harmonics, radius)</code>, a function that calculates the distance between two harmonic signatures given some radius (query_harmonics and radius are computed beforehand). </p> <p>My current solution is:</p> <pre><code>query_harmonics = calc_3d_harmonics(query_region) ref_region, score = min(templates, key=lambda t: calc_3d_harmonics_distance(t[1], query_harmonics, radius)) </code></pre> <p>A team member suggested that I use the following instead:</p> <pre><code>query_harmonics = calc_3d_harmonics(query_region) ref_region, score = min([(t[0], calc_harmonics_distance(t[1], query_harmonics, radius)) for t in templates], key=lambda x: x[1]) </code></pre> <p>Note: Both <code>calc_3d_harmonics</code> and <code>calc_harmonics_distance</code> are very slow and heavy functions. Also, <code>score</code> can be replace by <code>_</code>.</p> <p>He claims that his suggestion might result in a better runtime (although it would not be significant since the harmonics functions are the major operations). If <code>min(list, key=func)</code> creates a list of the keys, then our versions are equivalent (and mine's shorter), but if it computes the key every time he thinks mine will be slower.</p> <p>Which way is faster? I think there must be a better (runtime-wise) way to do this (perhaps using numpy?) and would like to hear some suggestions.</p>
1
2016-09-04T12:17:23Z
39,317,089
<p><code>min(lst, key=func)</code> calls <code>func</code> once on each item of <code>lst</code> (and that also applies to the key function of <code>max</code>, <code>list.sort</code> and <code>sorted</code>). So if <code>lst</code> contains duplicated items then the key function does unnecessary work, unless you use a memoizing key function.</p> <p>To illustrate, here are a couple of key functions that print their arg when called. <code>kf</code> is a normal key function, <code>kf_cached</code> uses a default mutable dictionary to do memoizing.</p> <pre><code>def kf(n): print(' Key', n) return int(n) def kf_cached(n, cache={}): if n in cache: print(' Cached', n) return cache[n] print(' Key', n) cache[n] = k = int(n) return k a = '14142' u = max(a, key=kf) print('max', u, '\n') u = max(a, key=kf_cached) print('max', u) </code></pre> <p><strong>output</strong></p> <pre><code> Key 1 Key 4 Key 1 Key 4 Key 2 max 4 Key 1 Key 4 Cached 1 Cached 4 Key 2 max 4 </code></pre>
1
2016-09-04T12:50:55Z
[ "python", "list", "numpy", "tuples", "min" ]
Python Pandas: Best strategy to import heterogenious csv file
39,316,831
<p>I have a inhomogenious csv-File I want to read into pandas. The file looks like that:</p> <pre><code>2016-01-01; 1.00; 2.00 2016-01-02; 1,10; 2.05 2016-01-03; 0.95; 1.90 Some other text in here 2016-01-04; 1.01; 2.04 Some more text there 2016-01-05; 1.06; 2.07 </code></pre> <p>I only need the text lines so I can skip the lines starting with a date. I tried several strategies to read that in and filter our the required data but nothing worked so far. What I know is the Text-lines always start with a special word ("some" in this example). However, there is no fixed line number that can be used.</p>
2
2016-09-04T12:18:10Z
39,317,017
<p>If you'd like to discard lines starting with a single special <em>character</em>, you can use the <code>comment</code> parameter of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>, as noted by @cel in the comment above. </p> <p>Otherwise, you can use regular Python logic for filtering out items from an iterator, and use <code>CStringIO</code>.</p> <p>For example, to discard the lines starting with <code>"some"</code>, you can use:</p> <pre><code>import CStringIO buf = StringIO.StringIO('\n'.join((l for l in open('stuff.txt') if not l.startswith('Some')))) pd.read_csv(buf, sep=';') </code></pre> <p>Conversely, if you actually only need lines starting with <code>"some"</code>, then use</p> <pre><code>buf = StringIO.StringIO('\n'.join((l for l in open('stuff.txt') if l.startswith('Some')))) </code></pre>
2
2016-09-04T12:40:58Z
[ "python", "pandas" ]
Determine how many decimal digits of a float are precise
39,316,849
<p>In my real-life problem, I multiply the size of a widget, with a <code>size_hint</code> which can be anything from <code>0.</code> to <code>1.</code>. Assuming the minimum size of a widget is <code>0</code> and the max size is <code>10,000</code>, on which digit should I expect the error to occur, when I multiply <code>size * size_hint</code>? </p> <p>For example* on <code>0.1</code> the error occurs on the.. </p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; Decimal.from_float(.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') # ^ # |_ here </code></pre> <p>.. 18th decimal digit.</p> <p>On the other hand, the error below occurs on the 14th decimal </p> <pre><code>&gt;&gt;&gt; 1001*.2 200.20000000000002 </code></pre> <p><strong>Questions</strong>: </p> <ul> <li>Is there a way to determine on which exactly decimal digit the error will occur? </li> <li>Is there a difference between Python 2 and Python 3?</li> </ul> <p>Using decimals instead of floats is not a option, and that both <code>size</code> and <code>size_hint</code> are provided by the user.</p> <hr> <p>*<sub> I used <a href="https://docs.python.org/3.5/library/fractions.html" rel="nofollow"><code>Fraction</code></a> since <code>&gt;&gt;&gt; 0.1</code> is displayed as.. <code>0.1</code> in the console, but I think this is related to how it's printed, not how it's stored. </sub></p>
0
2016-09-04T12:21:01Z
39,317,030
<p>I'd recommend you take a read to <a href="https://docs.python.org/3/whatsnew/3.5.html#pep-485-a-function-for-testing-approximate-equality" rel="nofollow">pep485</a></p> <p>Using <code>==</code> operator to compare floating-point values is not the right way to go, instead consider using <a href="https://docs.python.org/3/library/math.html#math.isclose" rel="nofollow">math.isclose</a> or <a href="https://docs.python.org/3/library/cmath.html#cmath.isclose" rel="nofollow">cmath.isclose</a>, here's a little example using your values:</p> <pre><code>try: from math import isclose v1 = 101 * 1 / 5 v2 = 101 * (1 / 5) except: v1 = float(101) * float(1) / float(5) v2 = float(101) * (float(1) / float(5)) def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): return abs(a - b) &lt;= max(rel_tol * max(abs(a), abs(b)), abs_tol) print("v1==v2 {0}".format(v1 == v2)) print("isclose(v1,v2) {0}".format(isclose(v1, v2))) </code></pre> <p>As you can see, I'm explicitly casting to float in <strong>python 2.x</strong> and using the function provided in the documentation, with <strong>python 3.x</strong> I just use directly your values and the provided function from math module.</p>
0
2016-09-04T12:42:02Z
[ "python", "floating-point", "precision", "significant-digits" ]
Determine how many decimal digits of a float are precise
39,316,849
<p>In my real-life problem, I multiply the size of a widget, with a <code>size_hint</code> which can be anything from <code>0.</code> to <code>1.</code>. Assuming the minimum size of a widget is <code>0</code> and the max size is <code>10,000</code>, on which digit should I expect the error to occur, when I multiply <code>size * size_hint</code>? </p> <p>For example* on <code>0.1</code> the error occurs on the.. </p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; Decimal.from_float(.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') # ^ # |_ here </code></pre> <p>.. 18th decimal digit.</p> <p>On the other hand, the error below occurs on the 14th decimal </p> <pre><code>&gt;&gt;&gt; 1001*.2 200.20000000000002 </code></pre> <p><strong>Questions</strong>: </p> <ul> <li>Is there a way to determine on which exactly decimal digit the error will occur? </li> <li>Is there a difference between Python 2 and Python 3?</li> </ul> <p>Using decimals instead of floats is not a option, and that both <code>size</code> and <code>size_hint</code> are provided by the user.</p> <hr> <p>*<sub> I used <a href="https://docs.python.org/3.5/library/fractions.html" rel="nofollow"><code>Fraction</code></a> since <code>&gt;&gt;&gt; 0.1</code> is displayed as.. <code>0.1</code> in the console, but I think this is related to how it's printed, not how it's stored. </sub></p>
0
2016-09-04T12:21:01Z
39,317,152
<p>If we assume that the size of the widget is stored exactly, then there are 2 sources of error: the conversion of <code>size_hint</code> from decimal -> binary, and the multiplication. In Python, these should both be correctly rounded to nearest, so each should have relative error of half an ulp (<a href="https://en.wikipedia.org/wiki/Unit_in_the_last_place" rel="nofollow">unit in the last place</a>). Since the second operation is a multiplication we can just add the bounds to get a total relative error which will be bounded 1 ulp, or 2<sup>-53</sup>.</p> <p>Converting to decimal:</p> <pre><code>&gt;&gt;&gt; math.trunc(math.log10(2.0**-53)) -15 </code></pre> <p>this means you should be accurate to 15 significant figures.</p> <p>There shouldn't be any difference between Python 2 and 3: Python has long been fairly strict about floating point behaviour, the only change I'm aware of is the behaviour of the <code>round</code> function, which isn't used here.</p>
2
2016-09-04T12:58:52Z
[ "python", "floating-point", "precision", "significant-digits" ]
Determine how many decimal digits of a float are precise
39,316,849
<p>In my real-life problem, I multiply the size of a widget, with a <code>size_hint</code> which can be anything from <code>0.</code> to <code>1.</code>. Assuming the minimum size of a widget is <code>0</code> and the max size is <code>10,000</code>, on which digit should I expect the error to occur, when I multiply <code>size * size_hint</code>? </p> <p>For example* on <code>0.1</code> the error occurs on the.. </p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; Decimal.from_float(.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') # ^ # |_ here </code></pre> <p>.. 18th decimal digit.</p> <p>On the other hand, the error below occurs on the 14th decimal </p> <pre><code>&gt;&gt;&gt; 1001*.2 200.20000000000002 </code></pre> <p><strong>Questions</strong>: </p> <ul> <li>Is there a way to determine on which exactly decimal digit the error will occur? </li> <li>Is there a difference between Python 2 and Python 3?</li> </ul> <p>Using decimals instead of floats is not a option, and that both <code>size</code> and <code>size_hint</code> are provided by the user.</p> <hr> <p>*<sub> I used <a href="https://docs.python.org/3.5/library/fractions.html" rel="nofollow"><code>Fraction</code></a> since <code>&gt;&gt;&gt; 0.1</code> is displayed as.. <code>0.1</code> in the console, but I think this is related to how it's printed, not how it's stored. </sub></p>
0
2016-09-04T12:21:01Z
39,323,523
<p>To answer the decimal to double-precision floating-point conversion part of your question...</p> <p>The conversion of decimal fractions between 0.0 and 0.1 will be good to <a href="http://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/" rel="nofollow">15-16 decimal digits</a> (Note: you start counting at the first non-zero digit after the point.)</p> <p>0.1 = 0.1000000000000000055511151231257827021181583404541015625 is good to 16 digits (rounded to 17 it is 0.10000000000000001; rounded to 16 it is 0.1).</p> <p>0.2 = 0.200000000000000011102230246251565404236316680908203125 is also good to 16 digits.</p> <p>(An example only good to 15 digits:</p> <p>0.81 = 0.810000000000000053290705182007513940334320068359375)</p>
1
2016-09-05T03:26:14Z
[ "python", "floating-point", "precision", "significant-digits" ]
TypeError: hash must be unicode or bytes, not None
39,316,867
<p>I am working on Flask project works with mongoengine. Register code hashed to password with <strong>passlib.hash</strong> when user registered. When I try to read password in login authentication I've got this error.</p> <p><strong>TypeError: hash must be unicode or bytes, not None</strong></p> <p><a href="http://i.stack.imgur.com/b6bud.png" rel="nofollow"><img src="http://i.stack.imgur.com/b6bud.png" alt="enter image description here"></a></p> <p><strong>Traceback:</strong></p> <pre><code>TypeError TypeError: hash must be unicode or bytes, not appname.models.User Traceback (most recent call last) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/*/**/***/***/appname/views.py", line 207, in login if sha256_crypt.verify(u''+ passW,user): File "/*/**/***/***/appname/env/lib/python2.7/site-packages/passlib/utils/handlers.py", line 567, in verify self = cls.from_string(hash, **context) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/passlib/handlers/sha2_crypt.py", line 285, in from_string hash = to_unicode(hash, "ascii", "hash") File "/*/**/***/***/appname/env/lib/python2.7/site-packages/passlib/utils/__init__.py", line 617, in to_unicode raise ExpectedStringError(source, param) TypeError: hash must be unicode or bytes, not appname.models.User The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error. To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side. You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection: dump() shows all variables in the frame dump(obj) dumps all that's known about the object </code></pre> <p>Here is my <strong>views.py</strong> codes:</p> <pre><code>@app.route("/login", methods=['GET','POST']) def login(): if current_user.is_authenticated: flash("You're already registered", "info") return redirect(url_for('profile')+('/'+current_user.slug)) form = LoginForm() passW = form.password.data if request.method == 'POST': form = LoginForm() if form.validate_on_submit(): user = User.objects(email=form.email.data, password=str(passW)).first() if sha256_crypt.verify(passW, user): login_user(user, form.remember_me.data) slug = slugify(user.name) flash('We are glad you came {}.'.format(user.name),'success') return redirect(request.args.get('next') or url_for('profile', slug=slug)) else: flash('Wrong username or password.','danger') return render_template("login.html", form=form, title="Cp-Login") return render_template("login.html", form=form, title="Cp-Login") </code></pre> <p>Any help will be appreciated.</p>
1
2016-09-04T12:23:18Z
39,317,257
<p>I guess the problem is here:</p> <pre><code>user = User.objects(email=form.email.data, password=str(passW)).first() </code></pre> <p>If your database can't find any match user, user will be none. So you'd better use if else to tell if the user exist first.</p> <h3>EDIT</h3> <p>From the doc in Passlib, </p> <pre><code>&gt;&gt;&gt; # import the hash algorithm &gt;&gt;&gt; from passlib.hash import sha256_crypt &gt;&gt;&gt; # generate new salt, and hash a password &gt;&gt;&gt; hash = sha256_crypt.encrypt("toomanysecrets") &gt;&gt;&gt; hash '$5$rounds=80000$zvpXD3gCkrt7tw.1$QqeTSolNHEfgryc5oMgiq1o8qCEAcmye3FoMSuvgToC' &gt;&gt;&gt; # verifying the password &gt;&gt;&gt; sha256_crypt.verify("toomanysecrets", hash) True &gt;&gt;&gt; sha256_crypt.verify("joshua", hash) False </code></pre> <p>Your code</p> <pre><code>if sha256_crypt.verify(passW, user): </code></pre> <p>should be </p> <pre><code>if sha256_crypt.verify(passW, user.password): </code></pre> <p>if you store user's password use Passlib. But usually you should use django build-in <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#authenticating-users" rel="nofollow">authenticating</a> to do something like this.</p>
1
2016-09-04T13:10:05Z
[ "python", "unicode", "hash", "flask", "typeerror" ]
TypeError: hash must be unicode or bytes, not None
39,316,867
<p>I am working on Flask project works with mongoengine. Register code hashed to password with <strong>passlib.hash</strong> when user registered. When I try to read password in login authentication I've got this error.</p> <p><strong>TypeError: hash must be unicode or bytes, not None</strong></p> <p><a href="http://i.stack.imgur.com/b6bud.png" rel="nofollow"><img src="http://i.stack.imgur.com/b6bud.png" alt="enter image description here"></a></p> <p><strong>Traceback:</strong></p> <pre><code>TypeError TypeError: hash must be unicode or bytes, not appname.models.User Traceback (most recent call last) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/*/**/***/***/appname/env/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/*/**/***/***/appname/views.py", line 207, in login if sha256_crypt.verify(u''+ passW,user): File "/*/**/***/***/appname/env/lib/python2.7/site-packages/passlib/utils/handlers.py", line 567, in verify self = cls.from_string(hash, **context) File "/*/**/***/***/appname/env/lib/python2.7/site-packages/passlib/handlers/sha2_crypt.py", line 285, in from_string hash = to_unicode(hash, "ascii", "hash") File "/*/**/***/***/appname/env/lib/python2.7/site-packages/passlib/utils/__init__.py", line 617, in to_unicode raise ExpectedStringError(source, param) TypeError: hash must be unicode or bytes, not appname.models.User The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error. To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side. You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection: dump() shows all variables in the frame dump(obj) dumps all that's known about the object </code></pre> <p>Here is my <strong>views.py</strong> codes:</p> <pre><code>@app.route("/login", methods=['GET','POST']) def login(): if current_user.is_authenticated: flash("You're already registered", "info") return redirect(url_for('profile')+('/'+current_user.slug)) form = LoginForm() passW = form.password.data if request.method == 'POST': form = LoginForm() if form.validate_on_submit(): user = User.objects(email=form.email.data, password=str(passW)).first() if sha256_crypt.verify(passW, user): login_user(user, form.remember_me.data) slug = slugify(user.name) flash('We are glad you came {}.'.format(user.name),'success') return redirect(request.args.get('next') or url_for('profile', slug=slug)) else: flash('Wrong username or password.','danger') return render_template("login.html", form=form, title="Cp-Login") return render_template("login.html", form=form, title="Cp-Login") </code></pre> <p>Any help will be appreciated.</p>
1
2016-09-04T12:23:18Z
39,320,293
<p>Just as @aison said above I had to change objects variable with the objects field variable as user.password </p> <pre><code>if sha256_crypt.verify(passW, user.password): </code></pre> <p>Also needed to change model queryset itself. I removed the password field in the query, beacuse the password already verifying sha256_crypt statement after the form validation above</p> <p><strong>before modifying</strong></p> <pre><code>user = User.objects(email=form.email.data, password=str(passW)).first() </code></pre> <p><strong>after modifying</strong></p> <pre><code>user = User.objects(email=form.email.data).first() </code></pre> <p>Hash verify statement that @aison suggested do the rest</p> <pre><code>if sha256_crypt.verify(passW, user.password): </code></pre>
0
2016-09-04T18:40:59Z
[ "python", "unicode", "hash", "flask", "typeerror" ]
Unable to parse data from weather website
39,316,881
<p>Hey i want to parse weather data from the following website: <a href="http://www.indiaweather.gov.in" rel="nofollow">http://www.indiaweather.gov.in</a></p> <p>If you observe you have a search bar which lets you enter any indian city's name and when you hit go you end up on a page with the weather data for that city.</p> <p>Could anyone help me with a script which will allow me to enter the city's name, and will display the city's weather data?</p> <p>I didn't know how to parse the data.</p> <p>Thanks!</p>
-2
2016-09-04T12:24:31Z
39,318,224
<p>You could use Beautiful Soup! to get your desired data between specific html tags. If you want to do it yourself you could post your data by calling the site's api. first install requests. <code>pip install requests</code> then</p> <pre><code>import re import requests # the data is between align="left"&gt;&lt;font size="3px"&gt; and &lt;/font&gt; in each specific part so we use re to find it def find_data(line): return re.search('align="left"&gt;&lt;font size="3px"&gt;(.*?)&lt;/font&gt;', line).group(1) params = { 'tags': city_name, 'submit': 'Go' } response = requests.post('http://www.indiaweather.gov.in/?page_id=942', data=params).content.splitlines() try: current_temp = find_data(response[357]) max_temp = find_data(response[362]) min_temp = find_data(response[369]) last_day_rainfall = find_data(response[376]) current_wind_direction = find_data(response[382]) current_wind_speed = find_data(response[389]) current_dew_point = find_data(response[396]) current_sea_level_pressure = find_data(response[403]) print(current_temp, max_temp, min_temp, last_day_rainfall, current_wind_direction, current_wind_speed, current_dew_point, current_sea_level_pressure) except IndexError: print('No Info Found For %s' % params['tags']) </code></pre>
-1
2016-09-04T14:56:06Z
[ "python", "html", "parsing", "beautifulsoup", "weather" ]
Cannot get unique IDs for a string python2.7
39,316,897
<p>I am trying to make unique ID from a list of words. I want these numbers to be globally unique. For example, if another list appears, I want the unique ID to be the same e.g. for "density", the ID might be <code>151111911</code>, and this will be the same if "density" occurs in a different list.</p> <p>As you can see, my current method is not working using <code>id</code> and <code>intern</code> - the ID for <code>rrb</code> is exactly the same as <code>lrb</code>.</p> <pre><code>featureList = [u'guinea', u'bissau', u'compared', u'countriesthe', u'population', u'density', u'guinea', u'bissau', u'similar', u'iran', u'afghanistan', u'cameroon', u'panama', u'montenegro', u'guinea', u'belarus', u'palau', u'location_slot', u'south', u'africa', u'respective', u'population', u'density', u'lrb', u'capita', u'per', u'square', u'kilometer', u'rrb', u'global', u'rank', u'number_slot', u'years', u'growthguinea', u'bissau', u'population', u'density', u'positive', u'growth', u'lrb', u'rrb', u'last', u'years', u'lrb', u'rrb', u'LOCATION_SLOT~-appos+LOCATION~-prep_of', u'LOCATION~-prep_of+that~-prep_to', u'that~-prep_to+similar~prep_with', u'similar~prep_with+density~prep_of', u'density~prep_of+NUMBER~appos', u'NUMBER~appos+NUMBER~amod', u'NUMBER~amod+NUMBER_SLOT'] featureVector = mydefaultdict(mydouble) for featureID,featureVal in enumerate(featureList): print "featureID is",featureID print "featureVal is ",featureVal print "Encoded feature value is", id(intern(str(featureVal.encode("utf-8")))) featureVector[featureID] = featureVal featureID is 0 featureVal is guinea Encoded feature value is 4569583120.0 featureID is 1 featureVal is bissau Encoded feature value is 4569581632.0 featureID is 2 featureVal is compared Encoded feature value is 4569583120.0 featureID is 3 featureVal is countriesthe Encoded feature value is 4567944360.0 featureID is 4 featureVal is population Encoded feature value is 4347153072.0 featureID is 5 featureVal is density Encoded feature value is 4455561472.0 featureID is 6 featureVal is guinea Encoded feature value is 4569581632.0 featureID is 7 featureVal is bissau Encoded feature value is 4569583120.0 featureID is 8 featureVal is similar Encoded feature value is 4496118144.0 featureID is 9 featureVal is iran Encoded feature value is 4569583120.0 featureID is 10 featureVal is afghanistan Encoded feature value is 4569581632.0 featureID is 11 featureVal is cameroon Encoded feature value is 4569583120.0 featureID is 12 featureVal is panama Encoded feature value is 4569581632.0 featureID is 13 featureVal is montenegro Encoded feature value is 4569583120.0 featureID is 14 featureVal is guinea Encoded feature value is 4569581632.0 featureID is 15 featureVal is belarus Encoded feature value is 4569583120.0 featureID is 16 featureVal is palau Encoded feature value is 4569581632.0 featureID is 17 featureVal is location_slot Encoded feature value is 4567944360.0 featureID is 18 featureVal is south Encoded feature value is 4569583120.0 featureID is 19 featureVal is africa Encoded feature value is 4569581632.0 featureID is 20 featureVal is respective Encoded feature value is 4569583120.0 featureID is 21 featureVal is population Encoded feature value is 4347153072.0 featureID is 22 featureVal is density Encoded feature value is 4455561472.0 featureID is 23 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 24 featureVal is capita Encoded feature value is 4569581632.0 featureID is 25 featureVal is per Encoded feature value is 4455914152.0 featureID is 26 featureVal is square Encoded feature value is 4347127296.0 featureID is 27 featureVal is kilometer Encoded feature value is 4569581632.0 featureID is 28 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 29 featureVal is global Encoded feature value is 4346597072.0 featureID is 30 featureVal is rank Encoded feature value is 4346629984.0 featureID is 31 featureVal is number_slot Encoded feature value is 4569583120.0 featureID is 32 featureVal is years Encoded feature value is 4569581632.0 featureID is 33 featureVal is growthguinea Encoded feature value is 4567944360.0 featureID is 34 featureVal is bissau Encoded feature value is 4569583120.0 featureID is 35 featureVal is population Encoded feature value is 4347153072.0 featureID is 36 featureVal is density Encoded feature value is 4455561472.0 featureID is 37 featureVal is positive Encoded feature value is 4514096160.0 featureID is 38 featureVal is growth Encoded feature value is 4569583120.0 featureID is 39 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 40 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 41 featureVal is last Encoded feature value is 4346568112.0 featureID is 42 featureVal is years Encoded feature value is 4569583120.0 featureID is 43 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 44 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 45 featureVal is LOCATION_SLOT~-appos+LOCATION~-prep_of Encoded feature value is 4538026784.0 featureID is 46 featureVal is LOCATION~-prep_of+that~-prep_to Encoded feature value is 6043251168.0 featureID is 47 featureVal is that~-prep_to+similar~prep_with Encoded feature value is 6043251168.0 featureID is 48 featureVal is similar~prep_with+density~prep_of Encoded feature value is 6043251168.0 featureID is 49 featureVal is density~prep_of+NUMBER~appos Encoded feature value is 6043251168.0 featureID is 50 featureVal is NUMBER~appos+NUMBER~amod Encoded feature value is 6043247024.0 featureID is 51 featureVal is NUMBER~amod+NUMBER_SLOT Encoded feature value is 6043247024.0 </code></pre> <p>What am I doing wrong? The reason I need to convert these into floats or numbers is that the above sentence would go into a classifier that needs to use numerical/vectorized features.</p>
0
2016-09-04T12:26:18Z
39,317,081
<p>You could directly use the <code>hash()</code> function in Python. Hash function will return a unique hash which can be used as an ID for any given string as is your case but it may differ on different platforms (32 bit/64 bit, OS, python version)</p> <pre><code>hash("answer") -8597262460139880008 </code></pre> <p>If you want hashes to be same then you can use Pythons <code>hashlibs</code> module but that won't give you numbers. It will return a hash string.</p> <pre><code>import hashlib test = hashlib.sha224() test.update("HI How are you") test.hexdigest() '3284ec5f391e0c6b4f974d3bc317a77bb50875081d2bcb2436fc2001' </code></pre> <p>You can choose from various algorithms</p> <pre><code> hashlib.algorithms ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512') </code></pre>
-1
2016-09-04T12:48:55Z
[ "python", "string", "python-2.7", "hash", "unique" ]
Cannot get unique IDs for a string python2.7
39,316,897
<p>I am trying to make unique ID from a list of words. I want these numbers to be globally unique. For example, if another list appears, I want the unique ID to be the same e.g. for "density", the ID might be <code>151111911</code>, and this will be the same if "density" occurs in a different list.</p> <p>As you can see, my current method is not working using <code>id</code> and <code>intern</code> - the ID for <code>rrb</code> is exactly the same as <code>lrb</code>.</p> <pre><code>featureList = [u'guinea', u'bissau', u'compared', u'countriesthe', u'population', u'density', u'guinea', u'bissau', u'similar', u'iran', u'afghanistan', u'cameroon', u'panama', u'montenegro', u'guinea', u'belarus', u'palau', u'location_slot', u'south', u'africa', u'respective', u'population', u'density', u'lrb', u'capita', u'per', u'square', u'kilometer', u'rrb', u'global', u'rank', u'number_slot', u'years', u'growthguinea', u'bissau', u'population', u'density', u'positive', u'growth', u'lrb', u'rrb', u'last', u'years', u'lrb', u'rrb', u'LOCATION_SLOT~-appos+LOCATION~-prep_of', u'LOCATION~-prep_of+that~-prep_to', u'that~-prep_to+similar~prep_with', u'similar~prep_with+density~prep_of', u'density~prep_of+NUMBER~appos', u'NUMBER~appos+NUMBER~amod', u'NUMBER~amod+NUMBER_SLOT'] featureVector = mydefaultdict(mydouble) for featureID,featureVal in enumerate(featureList): print "featureID is",featureID print "featureVal is ",featureVal print "Encoded feature value is", id(intern(str(featureVal.encode("utf-8")))) featureVector[featureID] = featureVal featureID is 0 featureVal is guinea Encoded feature value is 4569583120.0 featureID is 1 featureVal is bissau Encoded feature value is 4569581632.0 featureID is 2 featureVal is compared Encoded feature value is 4569583120.0 featureID is 3 featureVal is countriesthe Encoded feature value is 4567944360.0 featureID is 4 featureVal is population Encoded feature value is 4347153072.0 featureID is 5 featureVal is density Encoded feature value is 4455561472.0 featureID is 6 featureVal is guinea Encoded feature value is 4569581632.0 featureID is 7 featureVal is bissau Encoded feature value is 4569583120.0 featureID is 8 featureVal is similar Encoded feature value is 4496118144.0 featureID is 9 featureVal is iran Encoded feature value is 4569583120.0 featureID is 10 featureVal is afghanistan Encoded feature value is 4569581632.0 featureID is 11 featureVal is cameroon Encoded feature value is 4569583120.0 featureID is 12 featureVal is panama Encoded feature value is 4569581632.0 featureID is 13 featureVal is montenegro Encoded feature value is 4569583120.0 featureID is 14 featureVal is guinea Encoded feature value is 4569581632.0 featureID is 15 featureVal is belarus Encoded feature value is 4569583120.0 featureID is 16 featureVal is palau Encoded feature value is 4569581632.0 featureID is 17 featureVal is location_slot Encoded feature value is 4567944360.0 featureID is 18 featureVal is south Encoded feature value is 4569583120.0 featureID is 19 featureVal is africa Encoded feature value is 4569581632.0 featureID is 20 featureVal is respective Encoded feature value is 4569583120.0 featureID is 21 featureVal is population Encoded feature value is 4347153072.0 featureID is 22 featureVal is density Encoded feature value is 4455561472.0 featureID is 23 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 24 featureVal is capita Encoded feature value is 4569581632.0 featureID is 25 featureVal is per Encoded feature value is 4455914152.0 featureID is 26 featureVal is square Encoded feature value is 4347127296.0 featureID is 27 featureVal is kilometer Encoded feature value is 4569581632.0 featureID is 28 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 29 featureVal is global Encoded feature value is 4346597072.0 featureID is 30 featureVal is rank Encoded feature value is 4346629984.0 featureID is 31 featureVal is number_slot Encoded feature value is 4569583120.0 featureID is 32 featureVal is years Encoded feature value is 4569581632.0 featureID is 33 featureVal is growthguinea Encoded feature value is 4567944360.0 featureID is 34 featureVal is bissau Encoded feature value is 4569583120.0 featureID is 35 featureVal is population Encoded feature value is 4347153072.0 featureID is 36 featureVal is density Encoded feature value is 4455561472.0 featureID is 37 featureVal is positive Encoded feature value is 4514096160.0 featureID is 38 featureVal is growth Encoded feature value is 4569583120.0 featureID is 39 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 40 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 41 featureVal is last Encoded feature value is 4346568112.0 featureID is 42 featureVal is years Encoded feature value is 4569583120.0 featureID is 43 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 44 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 45 featureVal is LOCATION_SLOT~-appos+LOCATION~-prep_of Encoded feature value is 4538026784.0 featureID is 46 featureVal is LOCATION~-prep_of+that~-prep_to Encoded feature value is 6043251168.0 featureID is 47 featureVal is that~-prep_to+similar~prep_with Encoded feature value is 6043251168.0 featureID is 48 featureVal is similar~prep_with+density~prep_of Encoded feature value is 6043251168.0 featureID is 49 featureVal is density~prep_of+NUMBER~appos Encoded feature value is 6043251168.0 featureID is 50 featureVal is NUMBER~appos+NUMBER~amod Encoded feature value is 6043247024.0 featureID is 51 featureVal is NUMBER~amod+NUMBER_SLOT Encoded feature value is 6043247024.0 </code></pre> <p>What am I doing wrong? The reason I need to convert these into floats or numbers is that the above sentence would go into a classifier that needs to use numerical/vectorized features.</p>
0
2016-09-04T12:26:18Z
39,317,092
<p>You could use the words themselves, a hash of the words, or can even convert the string into a number.</p>
1
2016-09-04T12:51:19Z
[ "python", "string", "python-2.7", "hash", "unique" ]
Cannot get unique IDs for a string python2.7
39,316,897
<p>I am trying to make unique ID from a list of words. I want these numbers to be globally unique. For example, if another list appears, I want the unique ID to be the same e.g. for "density", the ID might be <code>151111911</code>, and this will be the same if "density" occurs in a different list.</p> <p>As you can see, my current method is not working using <code>id</code> and <code>intern</code> - the ID for <code>rrb</code> is exactly the same as <code>lrb</code>.</p> <pre><code>featureList = [u'guinea', u'bissau', u'compared', u'countriesthe', u'population', u'density', u'guinea', u'bissau', u'similar', u'iran', u'afghanistan', u'cameroon', u'panama', u'montenegro', u'guinea', u'belarus', u'palau', u'location_slot', u'south', u'africa', u'respective', u'population', u'density', u'lrb', u'capita', u'per', u'square', u'kilometer', u'rrb', u'global', u'rank', u'number_slot', u'years', u'growthguinea', u'bissau', u'population', u'density', u'positive', u'growth', u'lrb', u'rrb', u'last', u'years', u'lrb', u'rrb', u'LOCATION_SLOT~-appos+LOCATION~-prep_of', u'LOCATION~-prep_of+that~-prep_to', u'that~-prep_to+similar~prep_with', u'similar~prep_with+density~prep_of', u'density~prep_of+NUMBER~appos', u'NUMBER~appos+NUMBER~amod', u'NUMBER~amod+NUMBER_SLOT'] featureVector = mydefaultdict(mydouble) for featureID,featureVal in enumerate(featureList): print "featureID is",featureID print "featureVal is ",featureVal print "Encoded feature value is", id(intern(str(featureVal.encode("utf-8")))) featureVector[featureID] = featureVal featureID is 0 featureVal is guinea Encoded feature value is 4569583120.0 featureID is 1 featureVal is bissau Encoded feature value is 4569581632.0 featureID is 2 featureVal is compared Encoded feature value is 4569583120.0 featureID is 3 featureVal is countriesthe Encoded feature value is 4567944360.0 featureID is 4 featureVal is population Encoded feature value is 4347153072.0 featureID is 5 featureVal is density Encoded feature value is 4455561472.0 featureID is 6 featureVal is guinea Encoded feature value is 4569581632.0 featureID is 7 featureVal is bissau Encoded feature value is 4569583120.0 featureID is 8 featureVal is similar Encoded feature value is 4496118144.0 featureID is 9 featureVal is iran Encoded feature value is 4569583120.0 featureID is 10 featureVal is afghanistan Encoded feature value is 4569581632.0 featureID is 11 featureVal is cameroon Encoded feature value is 4569583120.0 featureID is 12 featureVal is panama Encoded feature value is 4569581632.0 featureID is 13 featureVal is montenegro Encoded feature value is 4569583120.0 featureID is 14 featureVal is guinea Encoded feature value is 4569581632.0 featureID is 15 featureVal is belarus Encoded feature value is 4569583120.0 featureID is 16 featureVal is palau Encoded feature value is 4569581632.0 featureID is 17 featureVal is location_slot Encoded feature value is 4567944360.0 featureID is 18 featureVal is south Encoded feature value is 4569583120.0 featureID is 19 featureVal is africa Encoded feature value is 4569581632.0 featureID is 20 featureVal is respective Encoded feature value is 4569583120.0 featureID is 21 featureVal is population Encoded feature value is 4347153072.0 featureID is 22 featureVal is density Encoded feature value is 4455561472.0 featureID is 23 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 24 featureVal is capita Encoded feature value is 4569581632.0 featureID is 25 featureVal is per Encoded feature value is 4455914152.0 featureID is 26 featureVal is square Encoded feature value is 4347127296.0 featureID is 27 featureVal is kilometer Encoded feature value is 4569581632.0 featureID is 28 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 29 featureVal is global Encoded feature value is 4346597072.0 featureID is 30 featureVal is rank Encoded feature value is 4346629984.0 featureID is 31 featureVal is number_slot Encoded feature value is 4569583120.0 featureID is 32 featureVal is years Encoded feature value is 4569581632.0 featureID is 33 featureVal is growthguinea Encoded feature value is 4567944360.0 featureID is 34 featureVal is bissau Encoded feature value is 4569583120.0 featureID is 35 featureVal is population Encoded feature value is 4347153072.0 featureID is 36 featureVal is density Encoded feature value is 4455561472.0 featureID is 37 featureVal is positive Encoded feature value is 4514096160.0 featureID is 38 featureVal is growth Encoded feature value is 4569583120.0 featureID is 39 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 40 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 41 featureVal is last Encoded feature value is 4346568112.0 featureID is 42 featureVal is years Encoded feature value is 4569583120.0 featureID is 43 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 44 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 45 featureVal is LOCATION_SLOT~-appos+LOCATION~-prep_of Encoded feature value is 4538026784.0 featureID is 46 featureVal is LOCATION~-prep_of+that~-prep_to Encoded feature value is 6043251168.0 featureID is 47 featureVal is that~-prep_to+similar~prep_with Encoded feature value is 6043251168.0 featureID is 48 featureVal is similar~prep_with+density~prep_of Encoded feature value is 6043251168.0 featureID is 49 featureVal is density~prep_of+NUMBER~appos Encoded feature value is 6043251168.0 featureID is 50 featureVal is NUMBER~appos+NUMBER~amod Encoded feature value is 6043247024.0 featureID is 51 featureVal is NUMBER~amod+NUMBER_SLOT Encoded feature value is 6043247024.0 </code></pre> <p>What am I doing wrong? The reason I need to convert these into floats or numbers is that the above sentence would go into a classifier that needs to use numerical/vectorized features.</p>
0
2016-09-04T12:26:18Z
39,317,181
<p>From the <a href="https://docs.python.org/2.7/library/functions.html#intern]" rel="nofollow">docs</a></p> <blockquote> <p>Interned strings are not immortal (like they used to be in Python 2.2 and before); you must keep a reference to the return value of intern() around to benefit from it.</p> </blockquote> <p>At the time the next string is interned the previous strings may be deleted, and the new one may occasionally get the same id. So keep the references in a container. I'll use a dict:</p> <pre><code>featureList = [u'guinea', u'bissau', u'compared', u'countriesthe', u'population', u'density', u'guinea', u'bissau', u'similar', u'iran', u'afghanistan', u'cameroon', u'panama', u'montenegro', u'guinea', u'belarus', u'palau', u'location_slot', u'south', u'africa', u'respective', u'population', u'density', u'lrb', u'capita', u'per', u'square', u'kilometer', u'rrb', u'global', u'rank', u'number_slot', u'years', u'growthguinea', u'bissau', u'population', u'density', u'positive', u'growth', u'lrb', u'rrb', u'last', u'years', u'lrb', u'rrb', u'LOCATION_SLOT~-appos+LOCATION~-prep_of', u'LOCATION~-prep_of+that~-prep_to', u'that~-prep_to+similar~prep_with', u'similar~prep_with+density~prep_of', u'density~prep_of+NUMBER~appos', u'NUMBER~appos+NUMBER~amod', u'NUMBER~amod+NUMBER_SLOT'] # dict of id:featureVal pairs seen = {} for featureID,featureVal in enumerate(featureList): print "featureID is",featureID print "featureVal is ",featureVal interned = intern(str(featureVal.encode("utf-8"))) interned_id = id(interned) # ensure that no other string with the same id has been seen assert interned_id not in seen or seen[interned_id] == featureVal # change this to seen[interned_id] = None and you'll (probably) get AssertionError # from the line above seen[interned_id] = interned print "Encoded feature value is", interned_id </code></pre>
2
2016-09-04T13:02:46Z
[ "python", "string", "python-2.7", "hash", "unique" ]
Cannot get unique IDs for a string python2.7
39,316,897
<p>I am trying to make unique ID from a list of words. I want these numbers to be globally unique. For example, if another list appears, I want the unique ID to be the same e.g. for "density", the ID might be <code>151111911</code>, and this will be the same if "density" occurs in a different list.</p> <p>As you can see, my current method is not working using <code>id</code> and <code>intern</code> - the ID for <code>rrb</code> is exactly the same as <code>lrb</code>.</p> <pre><code>featureList = [u'guinea', u'bissau', u'compared', u'countriesthe', u'population', u'density', u'guinea', u'bissau', u'similar', u'iran', u'afghanistan', u'cameroon', u'panama', u'montenegro', u'guinea', u'belarus', u'palau', u'location_slot', u'south', u'africa', u'respective', u'population', u'density', u'lrb', u'capita', u'per', u'square', u'kilometer', u'rrb', u'global', u'rank', u'number_slot', u'years', u'growthguinea', u'bissau', u'population', u'density', u'positive', u'growth', u'lrb', u'rrb', u'last', u'years', u'lrb', u'rrb', u'LOCATION_SLOT~-appos+LOCATION~-prep_of', u'LOCATION~-prep_of+that~-prep_to', u'that~-prep_to+similar~prep_with', u'similar~prep_with+density~prep_of', u'density~prep_of+NUMBER~appos', u'NUMBER~appos+NUMBER~amod', u'NUMBER~amod+NUMBER_SLOT'] featureVector = mydefaultdict(mydouble) for featureID,featureVal in enumerate(featureList): print "featureID is",featureID print "featureVal is ",featureVal print "Encoded feature value is", id(intern(str(featureVal.encode("utf-8")))) featureVector[featureID] = featureVal featureID is 0 featureVal is guinea Encoded feature value is 4569583120.0 featureID is 1 featureVal is bissau Encoded feature value is 4569581632.0 featureID is 2 featureVal is compared Encoded feature value is 4569583120.0 featureID is 3 featureVal is countriesthe Encoded feature value is 4567944360.0 featureID is 4 featureVal is population Encoded feature value is 4347153072.0 featureID is 5 featureVal is density Encoded feature value is 4455561472.0 featureID is 6 featureVal is guinea Encoded feature value is 4569581632.0 featureID is 7 featureVal is bissau Encoded feature value is 4569583120.0 featureID is 8 featureVal is similar Encoded feature value is 4496118144.0 featureID is 9 featureVal is iran Encoded feature value is 4569583120.0 featureID is 10 featureVal is afghanistan Encoded feature value is 4569581632.0 featureID is 11 featureVal is cameroon Encoded feature value is 4569583120.0 featureID is 12 featureVal is panama Encoded feature value is 4569581632.0 featureID is 13 featureVal is montenegro Encoded feature value is 4569583120.0 featureID is 14 featureVal is guinea Encoded feature value is 4569581632.0 featureID is 15 featureVal is belarus Encoded feature value is 4569583120.0 featureID is 16 featureVal is palau Encoded feature value is 4569581632.0 featureID is 17 featureVal is location_slot Encoded feature value is 4567944360.0 featureID is 18 featureVal is south Encoded feature value is 4569583120.0 featureID is 19 featureVal is africa Encoded feature value is 4569581632.0 featureID is 20 featureVal is respective Encoded feature value is 4569583120.0 featureID is 21 featureVal is population Encoded feature value is 4347153072.0 featureID is 22 featureVal is density Encoded feature value is 4455561472.0 featureID is 23 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 24 featureVal is capita Encoded feature value is 4569581632.0 featureID is 25 featureVal is per Encoded feature value is 4455914152.0 featureID is 26 featureVal is square Encoded feature value is 4347127296.0 featureID is 27 featureVal is kilometer Encoded feature value is 4569581632.0 featureID is 28 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 29 featureVal is global Encoded feature value is 4346597072.0 featureID is 30 featureVal is rank Encoded feature value is 4346629984.0 featureID is 31 featureVal is number_slot Encoded feature value is 4569583120.0 featureID is 32 featureVal is years Encoded feature value is 4569581632.0 featureID is 33 featureVal is growthguinea Encoded feature value is 4567944360.0 featureID is 34 featureVal is bissau Encoded feature value is 4569583120.0 featureID is 35 featureVal is population Encoded feature value is 4347153072.0 featureID is 36 featureVal is density Encoded feature value is 4455561472.0 featureID is 37 featureVal is positive Encoded feature value is 4514096160.0 featureID is 38 featureVal is growth Encoded feature value is 4569583120.0 featureID is 39 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 40 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 41 featureVal is last Encoded feature value is 4346568112.0 featureID is 42 featureVal is years Encoded feature value is 4569583120.0 featureID is 43 featureVal is lrb Encoded feature value is 4537993216.0 featureID is 44 featureVal is rrb Encoded feature value is 4537993216.0 featureID is 45 featureVal is LOCATION_SLOT~-appos+LOCATION~-prep_of Encoded feature value is 4538026784.0 featureID is 46 featureVal is LOCATION~-prep_of+that~-prep_to Encoded feature value is 6043251168.0 featureID is 47 featureVal is that~-prep_to+similar~prep_with Encoded feature value is 6043251168.0 featureID is 48 featureVal is similar~prep_with+density~prep_of Encoded feature value is 6043251168.0 featureID is 49 featureVal is density~prep_of+NUMBER~appos Encoded feature value is 6043251168.0 featureID is 50 featureVal is NUMBER~appos+NUMBER~amod Encoded feature value is 6043247024.0 featureID is 51 featureVal is NUMBER~amod+NUMBER_SLOT Encoded feature value is 6043247024.0 </code></pre> <p>What am I doing wrong? The reason I need to convert these into floats or numbers is that the above sentence would go into a classifier that needs to use numerical/vectorized features.</p>
0
2016-09-04T12:26:18Z
39,317,379
<p>Perhaps the easiest way is to use a <code>defaultdict</code> with a <code>itertools.count</code> with a <code>float</code> as its starting position, eg:</p> <pre><code>from collections import defaultdict from itertools import count # Start from 1.0 and increment by one - can change to start from any value or even add a step # eg: `count(716345.0, 9)` will start at at 716345.0 and increment by 9 for new keys unique_id = defaultdict(lambda c=count(1.0): next(c)) featureList = [u'guinea', u'bissau', u'compared', u'countriesthe', u'population', u'density', u'guinea', u'bissau', u'similar', u'iran', u'afghanistan', u'cameroon', u'panama', u'montenegro', u'guinea', u'belarus', u'palau', u'location_slot'] for feature in featureList: print(feature, unique_id[feature]) </code></pre> <p>This prints:</p> <pre><code>guinea 1.0 bissau 2.0 compared 3.0 countriesthe 4.0 population 5.0 density 6.0 guinea 1.0 bissau 2.0 similar 7.0 iran 8.0 afghanistan 9.0 cameroon 10.0 panama 11.0 montenegro 12.0 guinea 1.0 belarus 13.0 palau 14.0 location_slot 15.0 </code></pre> <p>We can do a couple of other checks:</p> <pre><code>unique_id['cameroon'] # 10.0 unique_id['this is new'] # 16.0 </code></pre>
1
2016-09-04T13:23:40Z
[ "python", "string", "python-2.7", "hash", "unique" ]
TypeError when indexing numpy array using numba
39,316,939
<p>I need to sum up elements in a 1D <code>numpy</code> array (below: <code>data</code>) based on another array with information on class memberships (<code>labels</code>). I use <code>numba</code>in the code below to speed it up. However, If I dot not explicitly cast with <code>int()</code> in the line <code>ret[int(find(labels, g))] += y</code>, I reveice an error message:</p> <p><code>TypeError: unsupported array index type ?int64</code></p> <p>Is there a better workaround that explicit casting?</p> <pre><code>import numpy as np from numba import jit labels = np.array([45, 85, 99, 89, 45, 86, 348, 764]) n = int(1e3) data = np.random.random(n) groups = np.random.choice(a=labels, size=n, replace=True) @jit(nopython=True) def find(seq, value): for ct, x in enumerate(seq): if x == value: return ct @jit(nopython=True) def subsumNumba(data, groups, labels): ret = np.zeros(len(labels)) for y, g in zip(data, groups): # not working without casting with int() ret[int(find(labels, g))] += y return ret </code></pre>
1
2016-09-04T12:30:32Z
39,317,766
<p>The problem is that <code>find</code> can either return an <code>int</code> or <code>None</code> if it doesn't find anything, thus I think the <code>?int64</code> error. To avoid casting, you need to provide an <code>int</code> return value when <code>find</code> exits without finding the desired value and then handle it in the caller. </p>
1
2016-09-04T14:07:48Z
[ "python", "numba" ]
issue using Singleton pattern with tkinter Photoimage/Tk in python
39,316,971
<p>Wrote the following code to display a chessboard using Tkinter in Python:</p> <pre><code>import tkinter as tk class Gui(tk.Tk): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls, *args, **kwargs) cls._instance.__initialized = False return cls._instance def __init__(self): if self.__initialized: return self.__initialized = True super().__init__() class Color(object): white =(0xff,0xff,0xff) black =(0x00,0x00,0x00) class Tile(tk.PhotoImage): @staticmethod def putTile(image, color, width, height, coordinates): pix = "#%02x%02x%02x" % color coor = (coordinates[0]*width, coordinates[1]*height) line = "{" + " ".join([pix]*width) + "}" image.put(" ".join([line]*height),coor) class Grid(tk.PhotoImage): def __init__(self,grid): super().__init__(width=10*len(grid), height=10*len(grid[0])) for x in range(len(grid)): for y in range(len(grid[x])): Tile.putTile(self,Color.white if grid[x][y]==1 else Color.black,10,10,(x,y)) class ChessBoard(Grid): chessboard = 4 * ([4 * [0,1]] + [4 * [1,0]]) def __init__(self): super().__init__(self.chessboard) </code></pre> <p>So <code>Gui()</code> is implemented as a singleton pattern. Also <code>tk.Tk.__init__()</code> is made to be called only once, otherwice I got a window everytime <code>Gui()</code> was called.</p> <p>I would expect the following to display a window with a chessboard:<br> <b>Case 1:</b></p> <pre><code>label = tk.Label(Gui(), image=ChessBoard()) label.pack() Gui().mainloop() </code></pre> <p>This creates an empty window without errors or warnings. A print statement shows that method <code>tilePut</code> is indeed called.</p> <p>Only when I add an additional <code>Gui()</code> statement in my program, as shown below, everyting works perfectly and a chessboard is printed.</p> <p><b>Case 2:</b></p> <pre><code>Gui() label = tk.Label(Gui(), image=ChessBoard()) label.pack() Gui().mainloop() </code></pre> <p>So I guess the <code>image.put</code> call requires a <code>Gui()</code> to exist. Though if I try the following code:</p> <p><b>Case 3:</b></p> <pre><code>board = ChessBoard() label = tk.Label(Gui(), image=board) label.pack() Gui().mainloop() </code></pre> <p>I get an error about calling <code>image.put</code> too soon. Considering I do not get this same error in case 1, I am surprised case 1 does not work. Can anyone explain why?</p>
0
2016-09-04T12:34:34Z
39,317,359
<p>The answer to your questions boils down to two factors:</p> <ol> <li>The root window must exist before you can create an image</li> <li>You must keep a reference to the image or tkinter will destroy the image data when it does garbage collection.</li> </ol> <p>The proper way to use this code would be to first create an instance of <code>Gui</code>, then create <code>Chessboard</code> and save what is returned in a variable. You can then use these references in the rest of your code.</p> <p>This is the common way to accomplish that:</p> <pre><code>root = Gui() chessboard = ChessBoard() label = tk.Label(root, image=chessboard) label.pack() root.mainloop() </code></pre> <p>Since you are defining <code>Gui</code> as a singleton, the following will also work. However, I think the use of a singleton adds complexity and makes the code less clear since it looks like you are creating three instances of <code>Gui</code>:</p> <pre><code>Gui() chessboard = ChessBoard() label = tk.Label(Gui(), image=chessboard) label.pack() Gui().mainloop() </code></pre>
1
2016-09-04T13:21:54Z
[ "python", "tkinter", "singleton" ]
Regex to match swedish words but not numbers
39,317,008
<p>So I have made a regex (in Python) that currently matches all words but ignores special characters.</p> <pre><code>/([\wåäöÅÄÖ]+)/g </code></pre> <p>However, it also matches numbers. How can I make it so that it does not match numbers?</p>
0
2016-09-04T12:39:38Z
39,317,050
<p>The <code>\w</code> character class is equivalent to <code>[A-Za-z0-9_]</code>.</p> <p>So maybe:</p> <pre><code>[åäöÅÄÖA-Za-z_]+ </code></pre> <p>will be better choice </p>
3
2016-09-04T12:44:00Z
[ "python", "regex" ]
Pass current value(instance) in the udpate form
39,317,156
<p>I have an api for updating the object. But update form shows empty field. How can i show form filled with current value? If i want to show current value filled in just django, i would do formname(instance=object). How can i do similar in DRF when using RetrieveAPIView. </p> <pre><code>class RestaurantUpdateAPI(RetrieveAPIView): queryset = Restaurant.objects.all() serializer_class = RestaurantCreateUpdateSerializer def perform_update(self, serializer): print('serializer',serializer) instance = serializer.save() # send_email_confirmation(user=self.request.user, modified=instance) </code></pre> <p>This code gives me empty form. i want the name field should have name of restaurant, city should have city name and so on.</p> <p>How can this be done in DRF RetrieveAPIView?</p> <p><a href="http://i.stack.imgur.com/jTenj.png" rel="nofollow"><img src="http://i.stack.imgur.com/jTenj.png" alt="enter image description here"></a></p>
0
2016-09-04T12:59:24Z
39,317,858
<p>You api url is ../edit/..., so I think you wanna use this api to edit your restaurant.(btw, REST API should not use "edit" in it, you just use http method to handle this). In your case, if you want use get method and post method at the same time.You should use <a href="http://www.django-rest-framework.org/api-guide/generic-views/#retrieveupdatedestroyapiview" rel="nofollow">RetrieveUpdateDestroyAPIView</a></p> <blockquote> <p>Used for read-write-delete endpoints to represent a single model instance.</p> <p>Provides get, put, patch and delete method handlers.</p> <p>Extends: GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin</p> </blockquote>
0
2016-09-04T14:16:08Z
[ "python", "django", "python-3.x", "django-rest-framework" ]
Name duplicates previous WSGI daemon definition
39,317,200
<p>I'm changing the domain name of a site. For a period I want the old domain name and the new domain name to point to the site. I'm running a Python Django site.</p> <p>My original Apache2 conf works fine and the basis is:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerAdmin name@gmail.com ServerName originalsite.co.uk ServerAlias www.originalsite.co.uk DocumentRoot /var/www/originalsite WSGIDaemonProcess originalsite python-path=/var/www/originalsite:/var/www/originalsite/env/lib/python2.7/site-packages WSGIProcessGroup originalsite WSGIScriptAlias / /var/www/originalsite/originalsite/wsgi.py ... &lt;/VirtualHost&gt; </code></pre> <p>I set up a new conf file with only the following changes:</p> <pre><code> ServerName newsite.co.uk ServerAlias www.newsite.co.uk </code></pre> <p>And I'm getting the following error:</p> <blockquote> <p>Name duplicates previous WSGI daemon definition.</p> </blockquote> <p>How do I fix this? Thanks for your help</p>
0
2016-09-04T13:04:11Z
39,317,370
<p>change <code>originalsite</code> name </p> <p>not in the directory address just the name like </p> <pre><code>WSGIDaemonProcess somethingelse python-path=/var/www/originalsite:/var/www/originalsite/env/‌​lib/python2.7/site-p‌​ackages </code></pre> <p>and </p> <pre><code>WSGIProcessGroup somethingelse </code></pre>
0
2016-09-04T13:22:28Z
[ "python", "django", "apache", "mod-wsgi" ]
Name duplicates previous WSGI daemon definition
39,317,200
<p>I'm changing the domain name of a site. For a period I want the old domain name and the new domain name to point to the site. I'm running a Python Django site.</p> <p>My original Apache2 conf works fine and the basis is:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerAdmin name@gmail.com ServerName originalsite.co.uk ServerAlias www.originalsite.co.uk DocumentRoot /var/www/originalsite WSGIDaemonProcess originalsite python-path=/var/www/originalsite:/var/www/originalsite/env/lib/python2.7/site-packages WSGIProcessGroup originalsite WSGIScriptAlias / /var/www/originalsite/originalsite/wsgi.py ... &lt;/VirtualHost&gt; </code></pre> <p>I set up a new conf file with only the following changes:</p> <pre><code> ServerName newsite.co.uk ServerAlias www.newsite.co.uk </code></pre> <p>And I'm getting the following error:</p> <blockquote> <p>Name duplicates previous WSGI daemon definition.</p> </blockquote> <p>How do I fix this? Thanks for your help</p>
0
2016-09-04T13:04:11Z
39,322,401
<p>The reason for the error is because the name of a mod_wsgi daemon process group must be unique across the whole Apache installation. It is not possible to use the same daemon process group name in different <code>VirtualHost</code> definitions. This is necessary to avoid conflicts when working out what daemon process group is being referred to in certain situations.</p>
0
2016-09-04T23:39:48Z
[ "python", "django", "apache", "mod-wsgi" ]
Advice on how I should structure program
39,317,241
<p>For the program I am trying to design, I am checking that certain conditions exist in configuration files. For example, that the line: <strong>ThisExists</strong> is in the program, or that <strong>ThisIsFirst</strong> exists in the file followed by <strong>ThisAlsoExists</strong> somewhere later down in the file.</p> <p>I looked for an efficient approach which might be used in this situation but couldn't find any.</p> <p>My current idea is basically to just iterate over the file(s) multiple times each time I want to check a condition. So I would have functions:</p> <p>def checkA(file)</p> <p>def checkB(file)</p> <p>. . .</p> <p>To me this seems inefficient as I have to iterate for every condition I want to check.</p> <p>Initially I thought I could just iterate once, checking each line for every condition I want to verify. But I don't think I can do that as conditions which can be multi line require information about more than one line at a time.</p> <p>Is the way I outlined the only way to do this, or is there a more efficient approach? </p> <p>I am trying to provide an example below.</p> <pre><code>def main(): file = open(filename) result1 = checkA(file) result2 = checkB(file) """This is a single line check function""" def checkA(file) conditionExists = False for line in file: if(line == "SomeCondition"): conditionExists = True return conditionExists """This is a multi line check function""" def checkB(file) conditionExists = False conditionStarted = False for line in file: if(line == "Start"): conditionStarted = True elif(line == "End" and conditionStarted): conditionExists = True return conditionExists </code></pre>
0
2016-09-04T13:08:44Z
39,318,134
<p>If available libraries (configparser etc.) aren't enough I would probably use regular expressions.</p> <pre><code>import re check_a = re.compile('^SomeCondition$', flags=re.MULTILINE) check_b = re.compile('^Start(?:.|\n)*?End$', flags=re.MULTILINE) def main(file_name): with open(file_name, 'r') as file_object: file_content = file_object.read() result_1 = bool(check_a.search(file_content)) result_2 = bool(check_b.search(file_content)) </code></pre> <p>It's not the most user friendly approach – especially if the matching conditions are complex – but I think the pay-off for learning regex is great.</p> <p>xkcd tells us that regex both can be a <a href="http://xkcd.com/208/" rel="nofollow">super power</a> and a <a href="https://xkcd.com/1171/" rel="nofollow">problem</a>.</p>
0
2016-09-04T14:47:13Z
[ "python", "parsing" ]
Advice on how I should structure program
39,317,241
<p>For the program I am trying to design, I am checking that certain conditions exist in configuration files. For example, that the line: <strong>ThisExists</strong> is in the program, or that <strong>ThisIsFirst</strong> exists in the file followed by <strong>ThisAlsoExists</strong> somewhere later down in the file.</p> <p>I looked for an efficient approach which might be used in this situation but couldn't find any.</p> <p>My current idea is basically to just iterate over the file(s) multiple times each time I want to check a condition. So I would have functions:</p> <p>def checkA(file)</p> <p>def checkB(file)</p> <p>. . .</p> <p>To me this seems inefficient as I have to iterate for every condition I want to check.</p> <p>Initially I thought I could just iterate once, checking each line for every condition I want to verify. But I don't think I can do that as conditions which can be multi line require information about more than one line at a time.</p> <p>Is the way I outlined the only way to do this, or is there a more efficient approach? </p> <p>I am trying to provide an example below.</p> <pre><code>def main(): file = open(filename) result1 = checkA(file) result2 = checkB(file) """This is a single line check function""" def checkA(file) conditionExists = False for line in file: if(line == "SomeCondition"): conditionExists = True return conditionExists """This is a multi line check function""" def checkB(file) conditionExists = False conditionStarted = False for line in file: if(line == "Start"): conditionStarted = True elif(line == "End" and conditionStarted): conditionExists = True return conditionExists </code></pre>
0
2016-09-04T13:08:44Z
39,318,379
<p>For a software engineering perspective, your current approach has the some nice advantages. The logic of the functions are fully decoupled from one another and can be separately debugged and tested. The complexity of each individual function is low. And this approach allows you to easily incorporate various checks that do not have a parallel structure.</p>
1
2016-09-04T15:12:22Z
[ "python", "parsing" ]
How to use a global variable for all class methods in Python?
39,317,260
<ul> <li><p>I have a <code>Person</code> class, which holds an <code>age</code> property, now I need to make it accessible in all method inside <code>Person</code> class, so that all methods work properly</p></li> <li><p>My code is as following:</p></li> </ul> <pre class="lang-py prettyprint-override"><code>class Person: #age = 0 def __init__(self,initialAge): # Add some more code to run some checks on initialAge if(initialAge &lt; 0): print("Age is not valid, setting age to 0.") age = 0 age = initialAge def amIOld(self): # Do some computations in here and print out the correct statement to the console if(age &lt; 13): print("You are young.") elif(age&gt;=13 and age&lt;18): print("You are a teenager.") else: print("You are old.") def yearPasses(self): # Increment the age of the person in here Person.age += 1 # I am having trouble with this method t = int(input()) for i in range(0, t): age = int(input()) p = Person(age) p.amIOld() for j in range(0, 3): p.yearPasses() p.amIOld() print("") </code></pre> <ul> <li><p><code>yearPasses()</code> is supposed to increase the <code>age</code> by 1, but now it doesn't do anything when called</p></li> <li><p>How do I adapt it to make it work?</p></li> </ul>
-1
2016-09-04T13:10:45Z
39,317,452
<p>You need <code>age</code> to be an instance attribute of the Person class. To do that, you use the <code>self.age</code> syntax, like this:</p> <pre><code>class Person: def __init__(self, initialAge): # Add some more code to run some checks on initialAge if initialAge &lt; 0: print("Age is not valid, setting age to 0.") self.age = 0 self.age = initialAge def amIOld(self): # Do some computations in here and print out the correct statement to the console if self.age &lt; 13: print("You are young.") elif 13 &lt;= self.age &lt;= 19: print("You are a teenager.") else: print("You are old.") def yearPasses(self): # Increment the age of the person in here self.age += 1 #test age = 12 p = Person(age) for j in range(9): print(j, p.age) p.amIOld() p.yearPasses() </code></pre> <p><strong>output</strong></p> <pre><code>0 12 You are young. 1 13 You are a teenager. 2 14 You are a teenager. 3 15 You are a teenager. 4 16 You are a teenager. 5 17 You are a teenager. 6 18 You are a teenager. 7 19 You are a teenager. 8 20 You are old. </code></pre> <hr> <p>Your original code had statements like </p> <pre><code>age = initialAge </code></pre> <p>in its methods. That just creates a local object named <code>age</code> in the method. Such objects don't exist outside the method, and are cleaned up when the method terminates, so the next time you call the method its old value of <code>age</code> has been lost. </p> <p><code>self.age</code> is an attribute of the class instance. Any method of the class can access and modify that attribute using the <code>self.age</code> syntax, and each instance of the class has its own attributes, so when you create multiple instances of the Person class each one will have its own <code>.age</code>. </p> <p>It's also possible to create objects which are attributes of the class itself. That allows all instances of the class to share a single object. Eg, </p> <pre><code>Person.count = 0 </code></pre> <p>creates a class attribute named <code>.count</code> of the Person class. You can also create a class attribute by putting an assignment statement outside a method. Eg,</p> <pre><code>class Person: count = 0 def __init__(self, initialAge): Person.count += 1 # Add some more code to run some checks on initialAge #Etc </code></pre> <p>would keep track of how many Person instances your program has created so far.</p>
1
2016-09-04T13:31:09Z
[ "python", "class", "object", "methods", "instance" ]
Python: Polygon does not close (shapely
39,317,261
<p>When creating a polygon using the Shapely, I push 4 vertices in the the polygon function. The output should be a tuple with 5 elements (the first vertex is doubled, and described as the last one too).</p> <p>It seems, however, that the order of the input vertices I pass to the function has impact the result: sometime the polygon is described with 5 vertices (as it should) and sometimes with 4 - meaning, it`s not a closed polygon (or in other words - it is not a polygon at all) It must be some bug.</p> <p>In the following example, the only difference between poly1 and poly 2 is the order of the vertices I pass. The direction is exactly the same though:</p> <pre><code>from shapely.geometry import Polygon print ('poly1 = ', Polygon([(620, 420, 500), (620, 420, 0), (620, 40, 0),(620, 40, 500)])) print ('poly2 = ',Polygon([(620, 40, 500), (620, 420, 500), (620, 420, 0), (620, 40, 0)])) </code></pre> <p>However, the result is different - one is a closed polygon, the other is open. The type of both, btw, is still a shapely polygon.</p> <pre><code>poly1 = POLYGON Z ((620 420 500, 620 420 0, 620 40 0, 620 40 500, 620 420 500)) poly2 = POLYGON Z ((620 40 500, 620 420 500, 620 420 0, 620 40 0)) </code></pre> <p>Any solution? </p>
1
2016-09-04T13:10:50Z
39,347,117
<p>I think it is related with the third coordinate. In the documentation (<a href="http://toblerity.org/shapely/manual.html" rel="nofollow">shapely doc</a>), it tells: </p> <blockquote> <p>A third z coordinate value may be used when constructing instances, but has no effect on geometric analysis. All operations are performed in the x-y plane.</p> </blockquote> <p>This means that shapely simply does not process the z coordinate. In your example, if you erase the z coordinate, you get:</p> <pre><code>[(620, 420), (620, 420), (620, 40), (620, 40)] [(620, 40), (620, 420), (620, 420), (620, 40)] </code></pre> <p>When you pass a linear string to build a polygon, shapely Polygon constructor checks if the last point is equal to the first one. If not, the point is added to get a linear ring. In the second case, as far as shapely can see, the last coordinate is already repeated and there is no need to add any other point.</p>
1
2016-09-06T10:45:55Z
[ "python", "shapely" ]
How to test that a function only accepts a certain type?
39,317,275
<p>I want to ensure that <code>twist_data</code> only gets a list of integers as an argument, and add a unit test.</p> <pre><code> def twist_data(n): n=list(n) a=[] b=[] for i in n: if i&lt;=0: a.append(i) if i&gt;0: b.append(i) n=[len(a),sum(b)] return n gum=[2,4,5,-6,-7,] print (twist_data (gum)) </code></pre>
-1
2016-09-04T13:12:30Z
39,321,774
<pre><code>def all_ints(numbers): return all(isinstance(number, int) for number in numbers) def validate_list(numbers): return all((isinstance(numbers, list), all_ints(numbers)) def twist_data(numbers): if not validate_list(numbers): raise TypeError('"numbers" must be of type "list", where all elements integers') positives, negatives = [], [] for number in numbers: if number &lt;= 0: negatives.append(number) if i &gt; 0: positives.append(number) return [len(negatives), sum(positives)] </code></pre> <p>While not generally Pythonic to do explicit type checking sometimes it's unavoidable. This is a pretty straight forward way to do so. However it's easier to ask for forgiveness than to ask for permission so this is another possibility:</p> <pre><code>def twist_data(numbers): positives, negatives = [], [] try: for number in numbers: if number &lt;= 0: negatives.append(number) if i &gt; 0: positives.append(number) return [len(negatives), sum(positives)] except TypeError: raise TypeError('"numbers" must be of type "list", where all elements integers') </code></pre> <p>Here a <code>TypeError</code> is raised if you try to do a comparison between non-comparable types. You can then catch the exception and reraise with your own message. </p> <p>Also do try to avoid single letter variable names. It'll be much easier to keep track of what's going on.</p>
0
2016-09-04T21:47:18Z
[ "python", "unit-testing" ]
Retrieve data from a collection(mongo),modify the returned object and insert it into another mongo collection
39,317,353
<pre><code>{ "name" : "XYZ", "phone" : 12345, "emp_id" : 9999, "sal" : 5000 } </code></pre> <p>I want to add data on this record and store it into another database. I have tried this:</p> <pre><code>db=connection.testing results=db.test.find({"name":"XYZ"}) for i in results: i.append('dept':'Marketing') db.test.insert_one(i) (please ignore the insertion being done on the same connection) Error: i.append('dept':'Marketing') ^ SyntaxError: invalid syntax </code></pre> <p>How to add data in the dictionary form or JSON form?</p>
0
2016-09-04T13:21:03Z
39,318,979
<p>since <code>i</code> in your example seems to be a dictionary, you most likely need something like <code>i.update({'dept': 'Marketing'})</code> or <code>i['dept']='Marketing'</code> in order to introduce new key/value pair </p>
1
2016-09-04T16:17:39Z
[ "python", "mongodb", "pymongo" ]
' | ' operator between python set objects
39,317,373
<p>Recently while making changes to a python module someone else wrote which does some processing on Pandas dataframe I came across a line of code which looks like this :</p> <p><code> indices_invalid_entries = \ list(set(indices_invalid_entries) | set(list(df[pd.isnull(df[i])].index))) </code></p> <p>where indices_invalid_enteries is initially an empty list. So basically what we are doing here is checking for Dataframe indexes in certain columns where there is <strong>NULL</strong> values.</p> <p>Now I know what <strong>set, list, pd.isnull</strong> functions do.</p> <p>But what can't seem to get is what purpose is the <em>BITWISE</em> <strong>OR</strong> operator <strong>|</strong> here. How will Bitwise OR(ing) of objects gonna store Indices of Invalid Enteries?</p> <p>Can someone explain? Thanks</p>
1
2016-09-04T13:23:05Z
39,317,454
<p>You can always try it out:</p> <pre><code>&gt;&gt;&gt; x = set([1,2,3]) &gt;&gt;&gt; y = set([2,3,4]) &gt;&gt;&gt; x | y set([1, 2, 3, 4]) &gt;&gt;&gt; </code></pre>
4
2016-09-04T13:31:34Z
[ "python", "pandas", "numpy" ]
' | ' operator between python set objects
39,317,373
<p>Recently while making changes to a python module someone else wrote which does some processing on Pandas dataframe I came across a line of code which looks like this :</p> <p><code> indices_invalid_entries = \ list(set(indices_invalid_entries) | set(list(df[pd.isnull(df[i])].index))) </code></p> <p>where indices_invalid_enteries is initially an empty list. So basically what we are doing here is checking for Dataframe indexes in certain columns where there is <strong>NULL</strong> values.</p> <p>Now I know what <strong>set, list, pd.isnull</strong> functions do.</p> <p>But what can't seem to get is what purpose is the <em>BITWISE</em> <strong>OR</strong> operator <strong>|</strong> here. How will Bitwise OR(ing) of objects gonna store Indices of Invalid Enteries?</p> <p>Can someone explain? Thanks</p>
1
2016-09-04T13:23:05Z
39,317,479
<p>As explained in the <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">documentation</a>, the | operator is the <strong>union operator</strong>.</p> <p>So as you mentioned in you answer, </p> <pre><code>indices_invalid_entries &lt;-- union(indices_invalid_entries,df[pd.isnull(df[i])].index) </code></pre> <p>And the general case:</p> <pre><code>Union = A | B # where A,b,Union are sets </code></pre>
3
2016-09-04T13:34:28Z
[ "python", "pandas", "numpy" ]
Hosting static website with Django
39,317,434
<p>I have Django app running live on AWS at, <code>www.domain.com/admin</code>. It doesn't posses any html pages, we only make use of Django-Admin.</p> <p>Now I have to host a website at <code>www.domain.com</code>. I have my website package in this form,</p> <pre><code>site |-sass |-js |-img |-fonts |-css |-index.html </code></pre> <p>I copy-pasted my <code>site</code> folder inside my Django app at <code>my_django_app/templates/</code></p> <p>Also, added this :</p> <pre><code>url(r'^$', TemplateView.as_view(template_name='site/index.html')), </code></pre> <p>inside <code>my_django_app/my_django_app/urls.py</code>.</p> <p>And, updated my <code>settings.py</code> with,</p> <pre><code>STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'templates/site'), ] </code></pre> <p>Now when I runserver and go to <code>www.domain.com</code>, it loads my html file without CSS, JS and Images.</p> <p>Please suggest me what I am doing wrong.</p> <p>I am a beginner to python and also never hosted a website ever before.</p>
0
2016-09-04T13:29:50Z
39,317,948
<p>This answer is a reply to <a href="http://stackoverflow.com/questions/39317434/hosting-static-website-with-django?noredirect=1#comment65967301_39317434">this comment</a>, not an answer to the original question.</p> <ol> <li><p>In your Apache config, change: <code>WSGIScriptAlias /</code> to <code>WSGIScriptAlias /admin</code>.</p></li> <li><p>Add this before the <code>&lt;/VirtualHost&gt;</code> closing tag:</p> <pre><code>Alias / /path/to/static/site/ &lt;Directory /path/to/static/site/&gt; Options Indexes FollowSymLinks AllowOverride All Order Deny,Allow Allow from all &lt;/Directory&gt; </code></pre></li> </ol> <p>I haven't tested it, but I believe this should work.</p>
1
2016-09-04T14:25:23Z
[ "python", "django", "django-templates", "django-admin" ]
Is this an efficient way to compute a moving average?
39,317,436
<p>I've some <code>{open|high|low|close}</code> market data. I want to compute a Simple Moving Average from the <code>close</code> value of each row.</p> <p>I've had a look around and couldn't find a simple way to do this. I've computed it via the below method. I want to know if there is a better way:</p> <pre><code>data = get_data_period_symbol('1h', 'EURUSD') empty_list = np.zeros(len(data)) data['SMA10'] = empty_list ma = 10 for i in range(ma-1, len(data)): vals = data['&lt;CLOSE&gt;'][i-(ma-1):i+1].tolist() mean = np.average(vals) index = data.index[i] data.set_value(index, 'SMA10', mean) </code></pre>
1
2016-09-04T13:29:54Z
39,317,607
<pre><code>data['SMA10'] = pd.rolling_mean(data['&lt;CLOSE&gt;'][:], 10) </code></pre> <p>Was my original found solution, however you get a warning saying it's deprecated</p> <p>Therefore:</p> <pre><code>data['SMA10'] = data['&lt;CLOSE&gt;'][:].rolling(window=10, center=False).mean() </code></pre>
1
2016-09-04T13:50:31Z
[ "python", "pandas", "dataframe", "moving-average" ]
Is this an efficient way to compute a moving average?
39,317,436
<p>I've some <code>{open|high|low|close}</code> market data. I want to compute a Simple Moving Average from the <code>close</code> value of each row.</p> <p>I've had a look around and couldn't find a simple way to do this. I've computed it via the below method. I want to know if there is a better way:</p> <pre><code>data = get_data_period_symbol('1h', 'EURUSD') empty_list = np.zeros(len(data)) data['SMA10'] = empty_list ma = 10 for i in range(ma-1, len(data)): vals = data['&lt;CLOSE&gt;'][i-(ma-1):i+1].tolist() mean = np.average(vals) index = data.index[i] data.set_value(index, 'SMA10', mean) </code></pre>
1
2016-09-04T13:29:54Z
39,317,656
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html" rel="nofollow"><code>np.convolve</code></a> as suggested in this <a href="http://stackoverflow.com/a/22621523/6614295">answer</a>. So something like this should work:</p> <pre><code>data.loc[ma-1:, "SMA10"] = np.convolve(data["&lt;CLOSE&gt;"], np.ones((ma,))/ma, mode="valid") </code></pre> <p>PS: I just saw your own answer, which is actually a much nicer solution!</p>
0
2016-09-04T13:56:32Z
[ "python", "pandas", "dataframe", "moving-average" ]
Is this an efficient way to compute a moving average?
39,317,436
<p>I've some <code>{open|high|low|close}</code> market data. I want to compute a Simple Moving Average from the <code>close</code> value of each row.</p> <p>I've had a look around and couldn't find a simple way to do this. I've computed it via the below method. I want to know if there is a better way:</p> <pre><code>data = get_data_period_symbol('1h', 'EURUSD') empty_list = np.zeros(len(data)) data['SMA10'] = empty_list ma = 10 for i in range(ma-1, len(data)): vals = data['&lt;CLOSE&gt;'][i-(ma-1):i+1].tolist() mean = np.average(vals) index = data.index[i] data.set_value(index, 'SMA10', mean) </code></pre>
1
2016-09-04T13:29:54Z
39,317,753
<p>Pandas provides all the tools you'll need for this kind of thing. Assuming you have your data indexed by time:</p> <pre><code>data['SMA10'] = data['&lt;close&gt;'].rolling(window=10).mean() </code></pre> <p>Voila. </p> <p>Edit: I suppose just note the newer api usage. Quoting from the <a href="http://pandas.pydata.org/pandas-docs/stable/computation.html#rolling-windows" rel="nofollow">Pandas docs</a>:</p> <blockquote> <p>Warning Prior to version 0.18.0, pd.rolling_<em>, pd.expanding_</em>, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. objects and a corresponding method call.</p> </blockquote>
3
2016-09-04T14:06:27Z
[ "python", "pandas", "dataframe", "moving-average" ]
Shifting x labels in Matplotlib, Ipython
39,317,551
<p>I'm trying to make three charts in one output with matplotlib in an ipython notebook. When I output the chart is correct for the fisrt one, but on the second and third the x labels are messed up, and there are more cells in the second and third chart. I want them all to be uniform. </p> <pre><code>fig, axs = plt.subplots(1,3, figsize=(15,10)) ax0, ax1, ax2 = axs.flat labels = ['Asian', 'Black', 'Hispanic', 'Unknown', 'White'] day1M = day1df[(day1df.Gender == "M")] day15M = day15df[(day15df.Gender == "M")] day30M = day30df[(day30df.Gender == "M")] grouped1 = day1M.groupby("Race").size() grouped15 = day15M.groupby("Race").size() grouped30= day30M.groupby("Race").size() x = range(len(grouped1)) ax0.bar(x, grouped1) ax0.set_xticklabels(labels, rotation='vertical') x = range(len(grouped15)) ax1.bar(x, grouped15) ax1.set_xticklabels(labels, rotation='vertical') x = range(len(grouped30)) ax2.bar(x, grouped30) ax2.set_xticklabels(labels, rotation='vertical') </code></pre> <p>and here is what the current output looks like</p> <p><a href="http://i.stack.imgur.com/JpYnO.png" rel="nofollow"><img src="http://i.stack.imgur.com/JpYnO.png" alt="Chart1"></a></p>
0
2016-09-04T13:43:18Z
39,319,365
<p>You should almost never use <code>set_xticklabels</code> because it is (under the hood) just using a <code>FixedFormatter</code> to tick labels. If you do not also set the locator to be <code>FixedLocator</code>, then the tick labels are applied, in sequence, to the ticks.</p> <p>As of mpl 1.5, there is a <code>tick_label</code> kwarg to <code>bar</code> <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.bar" rel="nofollow">(docs)</a> that will automatically label your bars. I suspect you want to do something like</p> <pre><code>ax.bar(x, data, tick_label=labels, align='center') </code></pre>
0
2016-09-04T16:58:40Z
[ "python", "pandas", "matplotlib", "ipython" ]
Converting GET request parameter to int ... if it is numeric
39,317,681
<p>lets say i'm showing some data to user , i want user to be able to perform some sort of filtering on a numeric field in the database using a <code>GET</code> form so i have something like this </p> <pre><code>code = request.GET.get('code') condition = {} if( code is not None and int(code) &gt; 0 ): condition['code'] = int(code) Somemodel.objects.filter(**condition) </code></pre> <p>but this works only if i code contains a number otherwise i get this error </p> <pre><code>invalid literal for int() with base 10: '' </code></pre> <p>so what is the pythonic way to handle this problem ? should i use <code>try/except</code> block? i perfer to handle this in the same <code>if</code> statement considering i might add other filters </p>
-1
2016-09-04T13:59:06Z
39,317,745
<p>The reason you are getting this error because int() expects the value in number it can be in the form string but it should be a number like "22","33" etc are valid .</p> <p>But in your case you are passing empty that's why its raising an error. You can achieve your desired output using type(), it helps you in checking the type of number</p> <p>So the modified code is</p> <pre><code> code = request.GET.get('code') condition = {} if( code is not None and type(code) == int ): condition['code'] = int(code) Somemodel.objects.filter(**condition) </code></pre> <p>Hope it helps :)</p>
0
2016-09-04T14:05:54Z
[ "python", "django", "python-3.x", "django-1.9" ]
Converting GET request parameter to int ... if it is numeric
39,317,681
<p>lets say i'm showing some data to user , i want user to be able to perform some sort of filtering on a numeric field in the database using a <code>GET</code> form so i have something like this </p> <pre><code>code = request.GET.get('code') condition = {} if( code is not None and int(code) &gt; 0 ): condition['code'] = int(code) Somemodel.objects.filter(**condition) </code></pre> <p>but this works only if i code contains a number otherwise i get this error </p> <pre><code>invalid literal for int() with base 10: '' </code></pre> <p>so what is the pythonic way to handle this problem ? should i use <code>try/except</code> block? i perfer to handle this in the same <code>if</code> statement considering i might add other filters </p>
-1
2016-09-04T13:59:06Z
39,317,846
<p><code>isnumeric</code> could check if <code>code</code> can be <em>casted</em> to <code>int</code> and also check that <code>code</code> is positive (when converted to integer) thus replacing <code>int(code) &gt; 0</code>:</p> <pre><code>if code is not None and code.isnumeric(): condition['code'] = int(code) </code></pre>
1
2016-09-04T14:15:08Z
[ "python", "django", "python-3.x", "django-1.9" ]
Converting GET request parameter to int ... if it is numeric
39,317,681
<p>lets say i'm showing some data to user , i want user to be able to perform some sort of filtering on a numeric field in the database using a <code>GET</code> form so i have something like this </p> <pre><code>code = request.GET.get('code') condition = {} if( code is not None and int(code) &gt; 0 ): condition['code'] = int(code) Somemodel.objects.filter(**condition) </code></pre> <p>but this works only if i code contains a number otherwise i get this error </p> <pre><code>invalid literal for int() with base 10: '' </code></pre> <p>so what is the pythonic way to handle this problem ? should i use <code>try/except</code> block? i perfer to handle this in the same <code>if</code> statement considering i might add other filters </p>
-1
2016-09-04T13:59:06Z
39,317,989
<p>You should use a Django form with one or more IntegerFields; they do this conversion for you, then you can get the result from <code>cleaned_data</code>.</p>
1
2016-09-04T14:30:27Z
[ "python", "django", "python-3.x", "django-1.9" ]
Pandas Mean for Certain Column
39,317,702
<p>I have a pandas dataframe like that:</p> <p><a href="http://i.stack.imgur.com/KOZan.png" rel="nofollow"><img src="http://i.stack.imgur.com/KOZan.png" alt="enter image description here"></a></p> <p>How can I able to calculate mean (min/max, median) for specific column if Cluster==1 or CLuster==2?</p> <p>Thanks!</p>
0
2016-09-04T14:00:55Z
39,317,744
<p>You can create new df with only the relevant rows, using:</p> <pre><code>newdf = df[df['cluster'].isin([1,2)] newdf.mean(axis=1) </code></pre> <p>In order to calc mean of a specfic column you can:</p> <pre><code>newdf["page"].mean(axis=1) </code></pre>
1
2016-09-04T14:05:23Z
[ "python", "pandas", "numpy" ]
Pandas Mean for Certain Column
39,317,702
<p>I have a pandas dataframe like that:</p> <p><a href="http://i.stack.imgur.com/KOZan.png" rel="nofollow"><img src="http://i.stack.imgur.com/KOZan.png" alt="enter image description here"></a></p> <p>How can I able to calculate mean (min/max, median) for specific column if Cluster==1 or CLuster==2?</p> <p>Thanks!</p>
0
2016-09-04T14:00:55Z
39,317,806
<h2>Simple intuitive answer</h2> <p>First pick the rows of interest, then average then pick the columns of interest.</p> <pre><code>clusters_of_interest = [1, 2] columns_of_interest = ['page'] # rows of interest newdf = df[ df.CLUSTER.isin(clusters_of_interest) ] # average and pick columns of interest newdf.mean(axis=0)[ columns_of_interest ] </code></pre> <h2>More advanced</h2> <pre><code># Create groups object according to the value in the 'cluster' column grp = df.groupby('CLUSTER') # apply functions of interest to all cluster groupings data_agg = grp.agg( ['mean' , 'max' , 'min' ] ) </code></pre> <p>This is also a good <a href="http://www.shanelynn.ie/summarising-aggregation-and-grouping-data-in-python-pandas/" rel="nofollow">link</a> which describes aggregation techniques. It should be noted that the "simple answer" averages over clusters 1 AND 2 or whatever is specified in the <code>clusters_of_interest</code> while the <code>.agg</code> function averages over each group of values having the same <code>CLUSTER</code> value.</p>
0
2016-09-04T14:11:27Z
[ "python", "pandas", "numpy" ]
Pandas Mean for Certain Column
39,317,702
<p>I have a pandas dataframe like that:</p> <p><a href="http://i.stack.imgur.com/KOZan.png" rel="nofollow"><img src="http://i.stack.imgur.com/KOZan.png" alt="enter image description here"></a></p> <p>How can I able to calculate mean (min/max, median) for specific column if Cluster==1 or CLuster==2?</p> <p>Thanks!</p>
0
2016-09-04T14:00:55Z
39,317,833
<p>You can do it in one line, using <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">boolean indexing</a>. For example you can do something like:</p> <pre><code>import numpy as np import pandas as pd # This will just produce an example DataFrame df = pd.DataFrame({'a':np.arange(30), 'Cluster':np.ones(30,dtype=np.int)}) df.loc[10:19, "Cluster"] *= 2 df.loc[20:, "Cluster"] *= 3 # This line is all you need df.loc[(df['Cluster']==1)|(df['Cluster']==2), 'a'].mean() </code></pre> <p>The boolean indexing array is <code>True</code> for the correct clusters. <code>a</code> is just the name of the column to compute the mean over.</p>
0
2016-09-04T14:14:00Z
[ "python", "pandas", "numpy" ]
Pandas Mean for Certain Column
39,317,702
<p>I have a pandas dataframe like that:</p> <p><a href="http://i.stack.imgur.com/KOZan.png" rel="nofollow"><img src="http://i.stack.imgur.com/KOZan.png" alt="enter image description here"></a></p> <p>How can I able to calculate mean (min/max, median) for specific column if Cluster==1 or CLuster==2?</p> <p>Thanks!</p>
0
2016-09-04T14:00:55Z
39,317,855
<p>If you meant take the mean only where Cluster is 1 or 2, then the other answers here address your issue. If you meant take a separate mean for each value of Cluster, you can use pandas' aggregation functions, including <code>groupyby</code> and <code>agg</code>:</p> <pre><code>df.groupby("Cluster").mean() </code></pre> <p>is the simplest and will take means of all columns, grouped by Cluster.</p> <pre><code>df.groupby("Cluster").agg({"duration" : np.mean}) </code></pre> <p>is an example where you are taking the mean of just one specific column, grouped by cluster. You can also use <code>np.min</code>, <code>np.max</code>, <code>np.median</code>, etc.</p> <p>The <code>groupby</code> method produces a <code>GroupBy</code> object, which is something like but not like a <code>DataFrame</code>. Think of it as the <code>DataFrame</code> grouped, waiting for aggregation to be applied to it. The <code>GroupBy</code> object has simple built-in aggregation functions that apply to all columns (the <code>mean()</code> in the first example), and also a more general aggregation function (the <code>agg()</code> in the second example) that you can use to apply specific functions in a variety of ways. One way of using it is passing a <code>dict</code> of column names keyed to functions, so specific functions can be applied to specific columns.</p>
1
2016-09-04T14:16:00Z
[ "python", "pandas", "numpy" ]
Domain error with square roots
39,317,746
<p>I am trying to copy a code from the book I am learning from. The program is supposed to find the square roots of a quadratic function but once I run the module in IDLE I get an error.</p> <pre><code>#This is a program to find the square roots of a quadratic function. import math def main(): print ("this is a program to find square roots of a quadratic function") print() a,b,c = eval(input("enter the value of the coefficients respectively")) discRoot = math.sqrt( b * b - 4 * a * c ) root1 = ( - b + discRoot ) / 2 * a root2 = ( - b - discRoot ) / 2 * a print ("The square roots of the equation are : ", root1, root2 ) print() main() </code></pre> <p>I am getting the following error :</p> <pre><code>Traceback (most recent call last): File "/home/ubuntu/Desktop/untitled.py", line 21, in &lt;module&gt; main() File "/home/ubuntu/Desktop/untitled.py", line 13, in main discRoot = math.sqrt( b * b - 4 * a * c ) ValueError: math domain error </code></pre> <p>What exactly am I doing wrong here ? Is it because the discRoor value is turning out to be negative ? </p>
0
2016-09-04T14:05:58Z
39,317,875
<p>Everytime <code>b * b - 4 * a * c</code> is a negative number, <code>math.sqrt(b * b - 4 * a * c)</code> will raise a <code>ValueError</code>.</p> <p>Either check that before, or use <code>sqrt</code> from the <a href="https://docs.python.org/3.4/library/cmath.html" rel="nofollow"><code>cmath</code></a> module to allow complex roots:</p> <pre><code>. . delta = b * b - 4 * a * c if delta &gt; 0: discRoot = math.sqrt(delta) else: print("No solutions") . . </code></pre> <p>Or allow complex roots:</p> <pre><code>import cmath . . discRoot = cmath.sqrt( b * b - 4 * a * c ) . . </code></pre>
1
2016-09-04T14:18:45Z
[ "python", "python-3.x" ]
Domain error with square roots
39,317,746
<p>I am trying to copy a code from the book I am learning from. The program is supposed to find the square roots of a quadratic function but once I run the module in IDLE I get an error.</p> <pre><code>#This is a program to find the square roots of a quadratic function. import math def main(): print ("this is a program to find square roots of a quadratic function") print() a,b,c = eval(input("enter the value of the coefficients respectively")) discRoot = math.sqrt( b * b - 4 * a * c ) root1 = ( - b + discRoot ) / 2 * a root2 = ( - b - discRoot ) / 2 * a print ("The square roots of the equation are : ", root1, root2 ) print() main() </code></pre> <p>I am getting the following error :</p> <pre><code>Traceback (most recent call last): File "/home/ubuntu/Desktop/untitled.py", line 21, in &lt;module&gt; main() File "/home/ubuntu/Desktop/untitled.py", line 13, in main discRoot = math.sqrt( b * b - 4 * a * c ) ValueError: math domain error </code></pre> <p>What exactly am I doing wrong here ? Is it because the discRoor value is turning out to be negative ? </p>
0
2016-09-04T14:05:58Z
39,317,907
<p>I'm guessing you're taking the square root of a negative number which is not in the domain of the <code>math.sqrt</code> function. It will raise a <code>ValueError</code>. You can get rid of this just by checking the discriminant. The discriminant is the bit inside the root. If it is negative, there are no solutions. If it is 0, one solution. If it is positive, then continue solving:</p> <pre><code>discriminant = b * b - 4 * a * c if discriminant &lt; 0: print("No solution") elif discriminant == 0: root1 = (-b) / 2 * a #do stuff else: discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / 2 * a root2 = (-b - discRoot) / 2 * a # do stuff with roots </code></pre>
0
2016-09-04T14:21:55Z
[ "python", "python-3.x" ]
Matplotlib figure size in Jupyter reset by inlining in Jupyter
39,317,796
<p>This question is more of a curiosity.</p> <p>To change the default fig size to a custom one in matplotlib, one does</p> <pre><code>from matplotlib import rcParams from matplotlib import pyplot as plt rcParams['figure.figsize'] = 15, 9 </code></pre> <p>after that, figure appears with chosen size. </p> <p>Now, I'm finding something new (never happened/noticed before just now): in a Jupyter notebook, when inlining matplotlib as </p> <pre><code>%matplotlib inline </code></pre> <p>this apparently overwrites the <code>rcParams</code> dictionary restoring the default value for the figure size. Hence in oder to be able to set the size, I have to inline <code>matplotlib</code> <em>before</em> changing the values of the <code>rcParams</code> dictionary. </p> <p>I am on a Mac OS 10.11.6, matplotlib version 1.5.1, Python 2.7.10, Jupyter 4.1.</p>
0
2016-09-04T14:10:25Z
39,327,020
<p>IPython's inline backend <a href="https://github.com/ipython/ipykernel/blob/4.5.0/ipykernel/pylab/config.py#L45" rel="nofollow">sets some rcParams</a> when it is initialized. This is configurable, and you can override it with your own configuration:</p> <pre><code># in ~/.ipython/ipython_config.py c.InlineBackend.rc = { 'figure.figsize': (15, 9) } </code></pre> <p>The above would <strong>replace</strong> all of the rcParams that the inline backend sets, and you get total control. If you already have a matplotlib style that works nicely for inline output, you can tell the backend to leave everything alone:</p> <pre><code>c.InlineBackend.rc = {} </code></pre> <p>If you want to change just a few values, rather than overriding the whole thing, you can use the dictionary <code>.update</code> method:</p> <pre><code>c.InlineBackend.rc.update({'figure.figsize': (15, 9)}) </code></pre> <p>In the future, the inline backend should be doing its defaults via matplotlib's nice new style mechanism, which should make it behave nicer in terms of respecting your preferences and allowing easier customization.</p>
1
2016-09-05T08:56:57Z
[ "python", "matplotlib", "plot", "jupyter" ]
Detecting if an arc has been clicked in pygame
39,317,909
<p>I am currently trying to digitalize an boardgame I invented (repo: <a href="https://github.com/zutn/King_of_the_Hill" rel="nofollow">https://github.com/zutn/King_of_the_Hill</a>). To make it work I need to check if one of the tiles (the arcs) on this <a href="http://i.stack.imgur.com/DTXzF.jpg" rel="nofollow">board</a> have been clicked. So far I have not been able to figure a way without giving up the pygame.arc function for drawing. If I use the x,y position of the position clicked, I can't figure a way out to determine the exact outline of the arc to compare to. I thought about using a color check, but this would only tell me if any of the tiles have been clicked. So is there a convenient way to test if an arc has been clicked in pygame or do I have to use sprites or something completely different? Additionally in a later step units will be included, that are located on the tiles. This would make the solution with the angle calculation postet below much more diffcult. </p>
0
2016-09-04T14:22:04Z
39,350,866
<p>This is a simple arc class that will detect if a point is contained in the arc, but it will only work with circular arcs.</p> <pre><code>import pygame from pygame.locals import * import sys from math import atan2, pi class CircularArc: def __init__(self, color, center, radius, start_angle, stop_angle, width=1): self.color = color self.x = center[0] # center x position self.y = center[1] # center y position self.rect = [self.x - radius, self.y - radius, radius*2, radius*2] self.radius = radius self.start_angle = start_angle self.stop_angle = stop_angle self.width = width def draw(self, canvas): pygame.draw.arc(canvas, self.color, self.rect, self.start_angle, self.stop_angle, self.width) def contains(self, x, y): dx = x - self.x # x distance dy = y - self.y # y distance greater_than_outside_radius = dx*dx + dy*dy &gt;= self.radius*self.radius less_than_inside_radius = dx*dx + dy*dy &lt;= (self.radius- self.width)*(self.radius- self.width) # Quickly check if the distance is within the right range if greater_than_outside_radius or less_than_inside_radius: return False rads = atan2(-dy, dx) # Grab the angle # convert the angle to match up with pygame format. Negative angles don't work with pygame.draw.arc if rads &lt; 0: rads = 2 * pi + rads # Check if the angle is within the arc start and stop angles return self.start_angle &lt;= rads &lt;= self.stop_angle </code></pre> <p>Here's some example usage of the class. Using it requires a center point and radius instead of a rectangle for creating the arc.</p> <pre><code>pygame.init() black = ( 0, 0, 0) width = 800 height = 800 screen = pygame.display.set_mode((width, height)) distance = 100 tile_num = 4 ring_width = 20 arc = CircularArc((255, 255, 255), [width/2, height/2], 100, tile_num*(2*pi/7), (tile_num*(2*pi/7))+2*pi/7, int(ring_width*0.5)) while True: fill_color = black for event in pygame.event.get(): # quit if the quit button was pressed if event.type == pygame.QUIT: pygame.quit(); sys.exit() x, y = pygame.mouse.get_pos() # Change color when the mouse touches if arc.contains(x, y): fill_color = (200, 0, 0) screen.fill(fill_color) arc.draw(screen) # screen.blit(debug, (0, 0)) pygame.display.update() </code></pre>
1
2016-09-06T13:56:19Z
[ "python", "pygame", "collision-detection" ]
dataframe math in pandas
39,317,959
<p><strong>TOTALLY RE WROTE ORIGINAL QUESTION</strong></p> <p>I read raw data from a csv file "CloseWeight4.csv"</p> <pre><code>df=pd.read_csv('CloseWeights4.csv') Date Symbol ClosingPrice Weight 3/1/2010 OGDC 116.51 0.1820219 3/2/2010 OGDC 117.32 0.1820219 3/3/2010 OGDC 116.4 0.1820219 3/4/2010 OGDC 116.58 0.1820219 3/5/2010 OGDC 117.61 0.1820219 3/1/2010 WTI 78.7 0.5348142 3/2/2010 WTI 79.68 0.5348142 3/3/2010 WTI 80.87 0.5348142 3/4/2010 WTI 80.21 0.5348142 3/5/2010 WTI 81.5 0.5348142 3/1/2010 FX 85.07 0.1312427 3/2/2010 FX 85.1077 0.1312427 3/3/2010 FX 85.049 0.1312427 3/4/2010 FX 84.9339 0.1312427 3/5/2010 FX 84.8 0.1312427 3/1/2010 PIB 98.1596499 0.1519211 3/2/2010 PIB 98.1596499 0.1519211 3/3/2010 PIB 98.1764222 0.1519211 3/4/2010 PIB 98.1770656 0.1519211 3/5/2010 PIB 98.1609364 0.1519211 </code></pre> <p>From Which I generate a dataframe df2</p> <pre><code>df2=df.iloc[:,0:3].pivot('Date', 'Symbol', 'ClosingPrice') df2 Out[10]: Symbol FX OGDC PIB WTI Date 2010-03-01 85.0700 116.51 98.159650 78.70 2010-03-02 85.1077 117.32 98.159650 79.68 2010-03-03 85.0490 116.40 98.176422 80.87 2010-03-04 84.9339 116.58 98.177066 80.21 2010-03-05 84.8000 117.61 98.160936 81.50 </code></pre> <p>from this I calculate returns using:</p> <pre><code>ret=np.log(df2/df2.shift(1)) In [12] ret Out[12]: Symbol FX OGDC PIB WTI Date 2010-03-01 NaN NaN NaN NaN 2010-03-02 0.000443 0.006928 0.000000 0.012375 2010-03-03 -0.000690 -0.007873 0.000171 0.014824 2010-03-04 -0.001354 0.001545 0.000007 -0.008195 2010-03-05 -0.001578 0.008796 -0.000164 0.015955 </code></pre> <p>I have weights of each security from df </p> <pre><code>df3=df.iloc[:,[1,3]].drop_duplicates().reset_index(drop=True) df3 Out[14]: Weight Symbol OGDC 0.182022 WTI 0.534814 FX 0.131243 PIB 0.151921 </code></pre> <p>I am trying to get the following weighted return results for each day but don't know how to do the math in pandas:</p> <pre><code>Date Portfolio_weighted_returns 2010-03-02 0.008174751 2010-03-03 0.006061657 2010-03-04 -0.005002414 2010-03-05 0.009058151 where the Portfolio_weighted_returns of 2010-03-02 is calculated as follows: 0.006928*0.182022+.012375*0.534814+0.000443*0.131243+0*0.151921 = 0.007937512315 </code></pre> <p>I then need to have these results multiplied by a decay factor where the decay factor is defineD as decFac =decay^(t). Using a decay = 0.5 gives decFac values of:</p> <pre><code>Date decFac 2010-03-02 0.0625 2010-03-03 0.125 2010-03-04 0.25 2010-03-05 0.5 </code></pre> <p>I then need to take the SQRT of the sum of the squared Portfolio_weighted_returns for each day multiplied by the respective decFac as such:</p> <pre><code>SQRT(Sum(0.008174751^2*.0625+0.006061657^2*.125+(-0.005002414^2)*.25+.009058151^2*.5)) = 0.007487 </code></pre>
1
2016-09-04T14:26:31Z
39,318,180
<pre><code>import numpy as np import pandas as pd </code></pre> <h2>define the variables</h2> <pre><code>data = np.mat(''' 85.0700 116.51 98.159650 78.70; 85.1077 117.32 98.159650 79.68; 85.0490 116.40 98.176422 80.87; 84.9339 116.58 98.177066 80.21; 84.8000 117.61 98.160936 81.50''') cols = ['FX', 'OGDC' , 'PIB' , 'WTI'] dts = pd.Series( data=pd.date_range('2010-03-01', '2010-03-05'), name='Date' ) df2 = pd.DataFrame( data=data, columns=cols, index=dts ) # this is your df3 variable wgt = pd.DataFrame( data=[0.131243, 0.182022, 0.151921, 0.534814], index=pd.Series(cols, name='Symbol') , columns=['Weight'] ) </code></pre> <p>To calculate daily returns I use the <code>.shift</code> operator</p> <pre><code># Calculate the daily returns for each security df_ret = np.log( df2 / df2.shift(1) ) # FX OGDC PIB WTI # Date # 2010-03-01 NaN NaN NaN NaN # 2010-03-02 0.000443 0.006928 0.000000 0.012375 # 2010-03-03 -0.000690 -0.007873 0.000171 0.014824 # 2010-03-04 -0.001354 0.001545 0.000007 -0.008195 # 2010-03-05 -0.001578 0.008796 -0.000164 0.015955 </code></pre> <p>You need to multiply the <code>Weight</code> column of <code>wgt</code> with <code>ret</code> to get the desired result. <code>wgt['Weight']</code> will return a <code>pd.Series</code> which is more like a 1-D array than a 2D array which a <code>pd.DataFrame</code> can be generally thought of.</p> <pre><code>df_wgt_ret = wgt['Weight'] * df_ret # FX OGDC PIB WTI # Date # 2010-03-01 NaN NaN NaN NaN # 2010-03-02 0.000081 0.003705 0.000000e+00 0.001880 # 2010-03-03 -0.000126 -0.004210 2.242285e-05 0.002252 # 2010-03-04 -0.000247 0.000826 8.609014e-07 -0.001245 # 2010-03-05 -0.000287 0.004704 -2.156434e-05 0.002424 </code></pre> <p>Sum over the columns (axis=1) to get the portfolio returns. Note this returns a <code>pd.Series</code> not a dataframe</p> <pre><code>port_ret = df_wgt_ret.sum(axis=1) # Date # 2010-03-01 NaN # 2010-03-02 0.005666 # 2010-03-03 -0.002061 # 2010-03-04 -0.000664 # 2010-03-05 0.006820 </code></pre> <p>Finally, multiply the decay rate with the portfolio, note that because the operation happens over the columns you need to </p> <pre><code>total_ret = (port_ret * sr_dec).sum() final_res = total_ret**0.5 </code></pre> <h2>The One liner</h2> <p>I'm assuming <code>decFac</code> is a dataframe with column name <code>decFac</code> and using <code>df3</code> and <code>ret</code> as you've defined them.</p> <pre><code>result = (( (df3.Weight * ret).sum(axis=1)**2 * decFac.decFac ).sum())**.5 </code></pre>
0
2016-09-04T14:51:46Z
[ "python", "pandas", "dataframe" ]
dataframe math in pandas
39,317,959
<p><strong>TOTALLY RE WROTE ORIGINAL QUESTION</strong></p> <p>I read raw data from a csv file "CloseWeight4.csv"</p> <pre><code>df=pd.read_csv('CloseWeights4.csv') Date Symbol ClosingPrice Weight 3/1/2010 OGDC 116.51 0.1820219 3/2/2010 OGDC 117.32 0.1820219 3/3/2010 OGDC 116.4 0.1820219 3/4/2010 OGDC 116.58 0.1820219 3/5/2010 OGDC 117.61 0.1820219 3/1/2010 WTI 78.7 0.5348142 3/2/2010 WTI 79.68 0.5348142 3/3/2010 WTI 80.87 0.5348142 3/4/2010 WTI 80.21 0.5348142 3/5/2010 WTI 81.5 0.5348142 3/1/2010 FX 85.07 0.1312427 3/2/2010 FX 85.1077 0.1312427 3/3/2010 FX 85.049 0.1312427 3/4/2010 FX 84.9339 0.1312427 3/5/2010 FX 84.8 0.1312427 3/1/2010 PIB 98.1596499 0.1519211 3/2/2010 PIB 98.1596499 0.1519211 3/3/2010 PIB 98.1764222 0.1519211 3/4/2010 PIB 98.1770656 0.1519211 3/5/2010 PIB 98.1609364 0.1519211 </code></pre> <p>From Which I generate a dataframe df2</p> <pre><code>df2=df.iloc[:,0:3].pivot('Date', 'Symbol', 'ClosingPrice') df2 Out[10]: Symbol FX OGDC PIB WTI Date 2010-03-01 85.0700 116.51 98.159650 78.70 2010-03-02 85.1077 117.32 98.159650 79.68 2010-03-03 85.0490 116.40 98.176422 80.87 2010-03-04 84.9339 116.58 98.177066 80.21 2010-03-05 84.8000 117.61 98.160936 81.50 </code></pre> <p>from this I calculate returns using:</p> <pre><code>ret=np.log(df2/df2.shift(1)) In [12] ret Out[12]: Symbol FX OGDC PIB WTI Date 2010-03-01 NaN NaN NaN NaN 2010-03-02 0.000443 0.006928 0.000000 0.012375 2010-03-03 -0.000690 -0.007873 0.000171 0.014824 2010-03-04 -0.001354 0.001545 0.000007 -0.008195 2010-03-05 -0.001578 0.008796 -0.000164 0.015955 </code></pre> <p>I have weights of each security from df </p> <pre><code>df3=df.iloc[:,[1,3]].drop_duplicates().reset_index(drop=True) df3 Out[14]: Weight Symbol OGDC 0.182022 WTI 0.534814 FX 0.131243 PIB 0.151921 </code></pre> <p>I am trying to get the following weighted return results for each day but don't know how to do the math in pandas:</p> <pre><code>Date Portfolio_weighted_returns 2010-03-02 0.008174751 2010-03-03 0.006061657 2010-03-04 -0.005002414 2010-03-05 0.009058151 where the Portfolio_weighted_returns of 2010-03-02 is calculated as follows: 0.006928*0.182022+.012375*0.534814+0.000443*0.131243+0*0.151921 = 0.007937512315 </code></pre> <p>I then need to have these results multiplied by a decay factor where the decay factor is defineD as decFac =decay^(t). Using a decay = 0.5 gives decFac values of:</p> <pre><code>Date decFac 2010-03-02 0.0625 2010-03-03 0.125 2010-03-04 0.25 2010-03-05 0.5 </code></pre> <p>I then need to take the SQRT of the sum of the squared Portfolio_weighted_returns for each day multiplied by the respective decFac as such:</p> <pre><code>SQRT(Sum(0.008174751^2*.0625+0.006061657^2*.125+(-0.005002414^2)*.25+.009058151^2*.5)) = 0.007487 </code></pre>
1
2016-09-04T14:26:31Z
39,320,059
<p>IIUC you can do it this way:</p> <pre><code>In [267]: port_ret = ret.dot(df3) In [268]: port_ret Out[268]: Weight Date 2010-03-01 NaN 2010-03-02 0.007938 2010-03-03 0.006431 2010-03-04 -0.004278 2010-03-05 0.009902 In [269]: decay = 0.5 In [270]: decay_df = pd.DataFrame({'decFac':decay**np.arange(len(ret), 0, -1)}, index=ret.index) In [271]: decay_df Out[271]: decFac Date 2010-03-01 0.03125 2010-03-02 0.06250 2010-03-03 0.12500 2010-03-04 0.25000 2010-03-05 0.50000 In [272]: (port_ret.Weight**2 * decay_df.decFac).sum() ** 0.5 Out[272]: 0.007918790111274962 </code></pre> <p><code>port_ret.Weight**2 * decay_df.decFac</code></p> <pre><code>In [277]: port_ret.Weight**2 * decay_df.decFac Out[277]: Date 2010-03-01 NaN 2010-03-02 0.000004 2010-03-03 0.000005 2010-03-04 0.000005 2010-03-05 0.000049 dtype: float64 </code></pre>
1
2016-09-04T18:15:39Z
[ "python", "pandas", "dataframe" ]
Problems installing python module pybfd
39,318,053
<p>I've been trying to install the <code>pybfd</code> module but nothing works so far.</p> <p>Tried the following:</p> <p><code>pip install pybfd</code> returns <code>error: option --single-version-externally-managed not recognized</code>. After a quick search I found the <code>--egg</code> option for <code>pip</code> which seems to work, says successfully installed but when I try to run my code <code>ImportError: No module named pybfd.bfd</code></p> <p><code>easy_install pybfd</code> returns an error as well: <code>Writing /tmp/easy_install-oZUgBf/pybfd-0.1.1/setup.cfg Running pybfd-0.1.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-oZUgBf/pybfd-0.1.1/egg-dist-tmp-gWwhoT [-] Error : unable to determine correct include path for bfd.h / dis-asm.h No eggs found in /tmp/easy_install-oZUgBf/pybfd-0.1.1/egg-dist-tmp-gWwhoT (setup script problem?)</code></p> <p>For the last attempt I downloaded the <code>pybfd</code> repo from GitHub and ran the setup script: <code>[-] Error : unable to determine correct include path for bfd.h / dis-asm.h </code></p> <p>Does anyone have any idea what could be causing all this and how to actually install the module ? </p>
0
2016-09-04T14:36:59Z
39,318,468
<p>After some trial and error I discovered that <code>binutils-dev</code> and <code>python-dev</code> packages were missing and causing the header path errors. After installing those the setup script worked.</p>
0
2016-09-04T15:21:09Z
[ "python", "pip", "easy-install" ]
Loading variable from txt
39,318,065
<p>I'm having problems with the following code:</p> <pre><code>f=open('config.txt') lines=f.readlines() print(lines[1]) print(lines[3]) print(lines[5]) print(lines[7]) print(lines[9]) print(lines[11]) #Import and define import serial import time time.sleep(5) #Settings Port = lines[1] TargetMaxVoltage = float(lines[3]) TargetStartVoltage = float(lines[5]) TargetIntervalVoltage = float(lines[7]) DelayTime = float(lines[9]) LogInterval = float(lines[11]) CV = True ser = serial.Serial(Port, 9600) TargetStartVoltageLock = TargetStartVoltage #Starting Settings ser.write(b'&gt;Start\r\n') ser.write(b'&gt;VoSet 0.5\r\n') time.sleep(1) ser.write(b'&gt;expMode 1\r\n') ser.write(b'&gt;runTime 1000000000\r\n') ser.write(b'&gt;stDly 1000000000\r\n') ser.write(b'&gt;IoSet 1\r\n') ser.write(b'&gt;Imax 50\r\n') ser.write(b'&gt;Imin 1\r\n') ser.write(b'&gt;FarEfc 1\r\n') ser.write(b'&gt;MolMax 9999\r\n') LogTimeInterval = "&gt;logIntv "+str(format(LogInterval, '.4f'))+"\r\n" ser.write(LogTimeInterval.encode('utf-8')) time.sleep(5) #Running Method None CV Screening while (TargetStartVoltage != TargetMaxVoltage and CV == False): DataSend = "&gt;VoSet "+str(format(TargetStartVoltage, '.2f'))+"\r\n" print (DataSend) ser.write(DataSend.encode('utf-8')) TargetStartVoltage += TargetIntervalVoltage time.sleep(DelayTime) #Running Method CV Screening CVComplete = False while (TargetStartVoltage &lt;= TargetMaxVoltage and CV == True and CVComplete != True): DataSend = "&gt;VoSet "+str(format(TargetStartVoltage, '.2f'))+"\r\n" print (DataSend) ser.write(DataSend.encode('utf-8')) TargetStartVoltage += TargetIntervalVoltage time.sleep(DelayTime) else: TargetStartVoltage -= 2*TargetIntervalVoltage while(TargetStartVoltageLock &lt;= TargetStartVoltage and CV == True and CVComplete != True): DataSend = "&gt;VoSet "+str(format(TargetStartVoltage, '.2f'))+"\r\n" print (DataSend) ser.write(DataSend.encode('utf-8')) TargetStartVoltage -= TargetIntervalVoltage time.sleep(DelayTime) else: CVComplete = True ser.close() </code></pre> <p>And I get the following error message:</p> <blockquote> <p>Traceback (most recent call last): File "C:\Users\Mikkel\Desktop\Python Scripts\CV_and_Screeningv100.py", line 24, in ser = serial.Serial(Port, 9600) File "C:\Users\Mikkel\AppData\Local\Programs\Python\Python35\lib\site-packages\serial\serialwin32.py", line 31, in <strong>init</strong> super(Serial, self).<strong>init</strong>(*args, **kwargs) File "C:\Users\Mikkel\AppData\Local\Programs\Python\Python35\lib\site-packages\serial\serialutil.py", line 182, in <strong>init</strong> self.open() File "C:\Users\Mikkel\AppData\Local\Programs\Python\Python35\lib\site-packages\serial\serialwin32.py", line 62, in open raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError())) serial.serialutil.SerialException: could not open port 'COM11\n':<br> FileNotFoundError(2, 'The system cannot find the file specified.', None, 2)</p> </blockquote> <p>I'm loading the data from a txt file called 'config.txt', and it seems that it is the </p> <p><code>Port = lines[1]</code> </p> <p>or </p> <pre><code>ser = serial.Serial(Port,9600) </code></pre> <p>that are the problem. Am I using the wrong format? I tried to introduce a 'str', 'init' and 'float', but nothing works. The data on lines[1] is COM11, which is the current port.</p>
2
2016-09-04T14:38:32Z
39,319,317
<p>Checkout the Error log there is written can't open <code>COM11\n</code> so you have to remove the newline (<code>\n</code>).</p> <p>Example: <code>Port.strip()</code></p>
0
2016-09-04T16:53:19Z
[ "python", "database", "error-handling", "serial-port" ]
Why can generator expressions be iterated over only once?
39,318,106
<p>This program:</p> <pre><code>def pp(seq): print(''.join(str(x) for x in seq)) print(''.join(str(x) for x in seq)) print('---') pp([0,1,2,3]) pp(range(4)) # range in Python3, xrange in Python2 pp(x for x in [0,1,2,3]) </code></pre> <p>prints this:</p> <pre><code>0123 0123 --- 0123 0123 --- 0123 --- </code></pre> <p>It is a result of the difference between <code>container.__iter__</code> and <code>iterator.__iter__</code>. Both are documented here: <a href="https://docs.python.org/3/library/stdtypes.html#typeiter" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#typeiter</a>. If the <code>__iter__</code> returns a new iterator each time, we see two repeating lines. And if it returns the same iterator each time, we see just one line, beacuse the iterator is exhausted after that.</p> <p>My question is <strong>why it was decided to implement generator expressions not similar to other objects that seem to be equivalent or at least very similar?</strong></p> <p>Here is another example that generator expressions are different than other similar types which may lead to unexpected outcome.</p> <pre><code>def pp(seq): # accept only non-empty sequences if seq: print("data ok") else: print("required data missing") pp([]) pp(range(0)) pp(x for x in []) </code></pre> <p>output:</p> <pre><code>required data missing required data missing data ok </code></pre>
0
2016-09-04T14:43:58Z
39,318,144
<blockquote> <p>My question is why it was decided to implement generator expressions not similar to other objects that seem to be equivalent or at least very similar?</p> </blockquote> <p>Because that's exactly what a generator is, if you make it similar to other iterables you have to preserve all the items in memory and then what you have is not a generator any more.</p> <p>The main benefit of using generators is that they doesn't consume the memory and just generate the items on demand, and this makes them to be one shot iterables, because otherwise if you want to be able to iterate over them multiple times you have to preserve them in memory. </p>
1
2016-09-04T14:47:38Z
[ "python" ]
Why can generator expressions be iterated over only once?
39,318,106
<p>This program:</p> <pre><code>def pp(seq): print(''.join(str(x) for x in seq)) print(''.join(str(x) for x in seq)) print('---') pp([0,1,2,3]) pp(range(4)) # range in Python3, xrange in Python2 pp(x for x in [0,1,2,3]) </code></pre> <p>prints this:</p> <pre><code>0123 0123 --- 0123 0123 --- 0123 --- </code></pre> <p>It is a result of the difference between <code>container.__iter__</code> and <code>iterator.__iter__</code>. Both are documented here: <a href="https://docs.python.org/3/library/stdtypes.html#typeiter" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#typeiter</a>. If the <code>__iter__</code> returns a new iterator each time, we see two repeating lines. And if it returns the same iterator each time, we see just one line, beacuse the iterator is exhausted after that.</p> <p>My question is <strong>why it was decided to implement generator expressions not similar to other objects that seem to be equivalent or at least very similar?</strong></p> <p>Here is another example that generator expressions are different than other similar types which may lead to unexpected outcome.</p> <pre><code>def pp(seq): # accept only non-empty sequences if seq: print("data ok") else: print("required data missing") pp([]) pp(range(0)) pp(x for x in []) </code></pre> <p>output:</p> <pre><code>required data missing required data missing data ok </code></pre>
0
2016-09-04T14:43:58Z
39,318,171
<p>A generator <em>runs arbitrary code</em>, and returns a lazy sequence with the items yielded by that code.</p> <ul> <li>That code could be providing an infinite sequence.</li> <li>That code could be reading contents off a network connection.</li> <li>That code could be modifying external variables every time it iterates.</li> </ul> <p>Thus, you can't cache the results safely in the general case: If it's an infinite sequence, you'd run out of memory.</p> <p>You also can't simply rerun the code when it's read from again: If it's reading off a network connection, then the connection may <em>no longer be there</em> again in the future (or may be in a different state). Similarly, if the code is modifying variables outside the genexp's scope, then that state would be changed in hard-to-predict ways based on the readers' behavior -- an undesirable propery for a language that values predictability and readability.</p> <hr> <p>Some other languages (notably Clojure) <em>do</em> implement generators (there, generalized as "lazy sequences") that cache results if and only if a reference to the beginning of the sequence is retained. This gives the programmer control, but at a cost of complexity: You need to know exactly what is and is not referenced for the garbage collector.</p> <p>The decision not to do this for Python is entirely reasonable and in keeping with the language's design goals.</p>
3
2016-09-04T14:51:03Z
[ "python" ]
np.cast in numpy results in incorrect result
39,318,232
<p>This use of np.cast: </p> <pre><code>np.cast['f'](np.pi) </code></pre> <p>results in an incorrect value for pi:</p> <pre><code>array(3.1415927410125732, dtype=float32) </code></pre> <p>why did this happen?</p>
0
2016-09-04T14:57:12Z
39,318,332
<p>Real pi value up to a few digits more than <code>float32</code> precision (from <a href="http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html" rel="nofollow">here</a>)</p> <pre><code>`3.14159265358979323846264338327950288...` </code></pre> <p><code>float32</code> precision has an accuracy from 6 to 9 decimal places (from <a href="https://en.wikipedia.org/wiki/Single-precision_floating-point_format" rel="nofollow">here</a>)</p> <pre><code> 3.1 4 1 5 9 2 7 4 1 0125732 # your value 3.1 4 1 5 9 2 6 5 3 5897 # actual value --1 2 3 4 5 6 7 8 9 # (index of decimal place) </code></pre> <p>As you can see the deviation from the real value happens after the 7th decimal place. So that's the reason why it is not right after that</p>
3
2016-09-04T15:07:41Z
[ "python", "numpy" ]
Serialize two nested schema with marshmallow
39,318,251
<p>I am fairly new to python. I have two SQLAlchemy models as follows:</p> <pre><code>class listing(db.Model): id = db.Integer(primary_key=True) title = db.String() location_id = db.Column(db.Integer, db.ForeignKey('location.id')) location = db.relationship('Location', lazy='joined') class location(db.Model): id = db.Integer(primary_key=True) title = db.String() </code></pre> <p>I have two Marshmallow schema classes for them:</p> <pre><code>class ListingSchema(Schema): id = fields.Int() title = fields.Str() location_id = fields.Int() class LocationSchema(Schema): id = fields.Int() title = fields.Str() </code></pre> <p>I have created a nested schema class like:</p> <pre><code>class NestedSchema(Schema): listing = fields.Nested(ListingSchema) location fields.Nested(LocationSchema) </code></pre> <p>I am doing the join query like :</p> <pre><code>listing,location = db.session.query(Listing,Location)\ .join(Location, and_(Listing.location_id == Location.id))\ .filter(Listing.id == listing_id).first() </code></pre> <p>data gets load in the objects i have checked. How can parse this schema? I have tried</p> <pre><code>result,errors = nested_listing_Schema(listing,location) </code></pre> <p>This gives error: "Listing object is not iteratable."</p>
1
2016-09-04T14:59:27Z
39,758,980
<p>The right is to use the class that you created NestedSchema and not nested_schema, do this:</p> <pre><code>result,errors = NestedSchema().dump({'listing':listing,'location':location}) </code></pre> <p>And the result wiil be:</p> <pre><code>dict: { u'listing': {u'id': 8, u'title': u'foo'}, u'location': {u'id': 30, u'title': u'bar'} } </code></pre> <p>But i do not understand why you wanted to make a "NestedSchema", i think you can do it another way.</p> <p>First, forget the class "NestedSchema".</p> <p>After, change your "ListingSchema", like this:</p> <pre><code>class ListingSchema(Schema): id = fields.Int() title = fields.Str() location_id = fields.Int() location = fields.Nested("LocationSchema") #The diff is here </code></pre> <p>And now you can do:</p> <pre><code>listing = db.session.query(Listing).get(listing_id) # Suppose listing_id = 8 result,errors = ListingSchema().dump(listing) print result </code></pre> <p>The result will be:</p> <pre><code>dict: { u'id': 8, u'title': u'foo', u'location_id': 30, u'location': {u'id': 30, u'title': u'bar'} } </code></pre> <p>Note that now, "location" is a property of "listing".</p> <p>And you can still make a <a href="http://marshmallow.readthedocs.io/en/latest/nesting.html#two-way-nesting" rel="nofollow">Two-Way Nesting</a>, just add a backref in Listing (model) and add ListingSchema as nested in LocationSchema</p> <pre><code>class Listing(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(45), nullable=False) location_id = db.Column(db.Integer, db.ForeignKey('location.id')) location = db.relationship('Location', lazy='joined', backref="listings") #the diff is here class LocationSchema(Schema): id = fields.Int() title = fields.Str() listings = fields.Nested("ListingSchema", many=True, exclude=("location",)) #The property name is the same as in bakcref </code></pre> <p>The <code>many=True</code> is because we have a relationship One-to-Many. The <code>exclude=("location")</code> is to avoid recursion exception.</p> <p>Now we can search by location too.</p> <pre><code>location = db.session.query(Location).get(location_id) # Suppose location_id = 30 result,errors = LocationSchema().dump(location) print result dict: {u'id': 30, u'title': u'bar', u'listings': [ {u'location_id': 30, u'id': 8, u'title': u'foo'}, {u'location_id': 30, u'id': 9, u'title': u'foo bar baz'}, ... ] } </code></pre> <p>You can see the docs about it <a href="http://marshmallow.readthedocs.io/en/latest/nesting.html" rel="nofollow">here</a></p>
2
2016-09-28T23:08:01Z
[ "python", "flask-sqlalchemy", "marshmallow" ]
lua cjson cannot decode specific unicode char?
39,318,257
<p>I'm getting the following error from lua cjson when trying to decode a specific unicode char,</p> <pre><code>root@9dc8433e6d83:~/torch-rnn# th train.lua -input_h5 data/aud.h5 -input_json data/aud.json -batch_size 50 -seq_length 100 -rnn_size 256 -max_epochs 50 Running with CUDA on GPU 0 /root/torch/install/bin/luajit: train.lua:77: Expected value but found invalid unicode escape code at character 350873 stack traceback: [C]: in function 'read_json' train.lua:77: in main chunk [C]: in function 'dofile' /root/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:145: in main chunk [C]: at 0x00406670 </code></pre> <p>by following the source, I can see that train.lua read_json is using cjson under the covers.</p> <p>The unicode escape code in question is \uda85</p> <p>If I go to <a href="https://www.branah.com/unicode-converter" rel="nofollow">https://www.branah.com/unicode-converter</a> it tells me the character the escape should decode to.</p> <p>The unicode escape was generated using python unichr(55941) and written to a file with PYTHONIOENCODING=UTF-8 via redirection of the python script output.</p> <p>The following demonstrates how the character was generated;</p> <pre><code>echo "print unichr(55941)" &gt; test.py python test.py Traceback (most recent call last): File "test.py", line 1, in &lt;module&gt; print unichr(55941) UnicodeEncodeError: 'ascii' codec can't encode character u'\uda85' in position 0: ordinal not in range(128) # export PYTHONIOENCODING=UTF-8 # python test.py ��� # python test.py &gt; tfile # cat tfile ��� # python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; f=open("tfile",'r') &gt;&gt;&gt; s=f.readline() &gt;&gt;&gt; s '\xed\xaa\x85\n' &gt;&gt;&gt; print s ��� &gt;&gt;&gt; s.decode('utf-8') u'\uda85\n' </code></pre> <p>What I am trying to do overall is take a set of integers in the range 0-65535 and using python map them to UTF-8 chars and write them out to a file. Then I would like to use torch-rnn that uses LUA to train an RNN on the sequence of chars. I'm getting the error when attempting to run th train.lua on the files generated by the torch-rnn python scripts/preprocess.py</p>
1
2016-09-04T15:00:03Z
39,320,587
<p>It seems the problem was unicode surrogates, understanding that means I can filter/switch them for different values. In this use case, thats not such a big problem.</p>
0
2016-09-04T19:17:01Z
[ "python", "unicode", "utf-8", "lua", "torch" ]
Find index of first occurrence in sorted list
39,318,277
<p>I have a sorted list that looks like this:</p> <pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3'] </code></pre> <p>I also have a count variable:</p> <pre><code>count = '1' </code></pre> <p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code></p> <p>What I want to do is to find the first occurrence of the count in the list and print the index. If the value is greater than the max value in the list, then assign a string. Here is what I have tried:</p> <pre><code>maxvalue = max(sortedlist) for i in sortedlist: if int(count) &lt; int(sortedlist[int(i)]): indexval = i break OutputFile.write(''+str(indexval)+'\n') if int(count) &gt; int(maxvalue): indexval = "over" OutputFile.write(''+str(indexval)+'\n') </code></pre> <p>I thought the break would end the for loop, but I'm only getting results from the last if statement. Am I doing something incorrectly?</p>
0
2016-09-04T15:01:37Z
39,318,395
<p>As your list is already sorted, so the maximum value will be the last element of your list i.e <code>maxval = sortedlist[-1]</code> . secondly there is an error in your for loop. <code>for i in sortedlist:</code> This gives you each element in the list . To get index do a for loop on range <code>len(sortedlist)</code> Here i is the element in the list. You should break after writing to the file. Below is the fixed code:</p> <pre><code>maxvalue = sortedlist[-1] if int(count) &gt; int(maxvalue): indexval = "over" OutputFile.write(''+str(indexval)+'\n') else: for i in xrange(len(sortedlist)): if int(count) &lt;= int(sortedlist[int(i)]): indexval = i OutputFile.write(''+str(indexval)+'\n') break </code></pre>
0
2016-09-04T15:13:58Z
[ "python", "list", "for-loop" ]
Find index of first occurrence in sorted list
39,318,277
<p>I have a sorted list that looks like this:</p> <pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3'] </code></pre> <p>I also have a count variable:</p> <pre><code>count = '1' </code></pre> <p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code></p> <p>What I want to do is to find the first occurrence of the count in the list and print the index. If the value is greater than the max value in the list, then assign a string. Here is what I have tried:</p> <pre><code>maxvalue = max(sortedlist) for i in sortedlist: if int(count) &lt; int(sortedlist[int(i)]): indexval = i break OutputFile.write(''+str(indexval)+'\n') if int(count) &gt; int(maxvalue): indexval = "over" OutputFile.write(''+str(indexval)+'\n') </code></pre> <p>I thought the break would end the for loop, but I'm only getting results from the last if statement. Am I doing something incorrectly?</p>
0
2016-09-04T15:01:37Z
39,318,397
<p>You could use a function (using <a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow">EAFP</a> principle) to find the first occurrence that is equal to or greater than the count:</p> <pre><code>In [239]: l = ['0','0','0','1','1','1','2','2','3'] In [240]: def get_index(count, sorted_list): ...: try: ...: return next(x[0] for x in enumerate(l) if int(x[1]) &gt;= int(count)) ...: except StopIteration: ...: return "over" ...: In [241]: get_index('3', l) Out[241]: 8 In [242]: get_index('7', l) Out[242]: 'over' </code></pre>
1
2016-09-04T15:14:04Z
[ "python", "list", "for-loop" ]
Find index of first occurrence in sorted list
39,318,277
<p>I have a sorted list that looks like this:</p> <pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3'] </code></pre> <p>I also have a count variable:</p> <pre><code>count = '1' </code></pre> <p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code></p> <p>What I want to do is to find the first occurrence of the count in the list and print the index. If the value is greater than the max value in the list, then assign a string. Here is what I have tried:</p> <pre><code>maxvalue = max(sortedlist) for i in sortedlist: if int(count) &lt; int(sortedlist[int(i)]): indexval = i break OutputFile.write(''+str(indexval)+'\n') if int(count) &gt; int(maxvalue): indexval = "over" OutputFile.write(''+str(indexval)+'\n') </code></pre> <p>I thought the break would end the for loop, but I'm only getting results from the last if statement. Am I doing something incorrectly?</p>
0
2016-09-04T15:01:37Z
39,318,462
<p>Your logic is wrong, you have a so called <em>sorted list</em> of strings which unless you compared as integer would not be sorted correctly, you should use <em>integers</em> from the get-go and <a href="https://docs.python.org/2/library/bisect.html#bisect.bisect_left" rel="nofollow">bisect_left</a> to find index:</p> <pre><code>from bisect import bisect_left sortedlist = sorted(map(int, ['0', '0', '0', '1', '1', '1', '2', '2', '3'])) count = 0 def get_val(lst, cn): if lst[-1] &lt; cn: return "whatever" return bisect_left(lst, cn, hi=len(lst) - 1) </code></pre> <p>If the value falls between two as per your requirement, you will get the first index of the higher value, if you get an exact match you will get that index:</p> <pre><code>In [13]: lst = [0,0,2,2] In [14]: get_val(lst, 1) Out[14]: 2 In [15]: lst = [0,0,1,1,2,2,2,3] In [16]: get_val(lst, 2) Out[16]: 4 In [17]: get_val(lst, 9) Out[17]: 'whatever' </code></pre>
2
2016-09-04T15:20:45Z
[ "python", "list", "for-loop" ]
Find index of first occurrence in sorted list
39,318,277
<p>I have a sorted list that looks like this:</p> <pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3'] </code></pre> <p>I also have a count variable:</p> <pre><code>count = '1' </code></pre> <p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code></p> <p>What I want to do is to find the first occurrence of the count in the list and print the index. If the value is greater than the max value in the list, then assign a string. Here is what I have tried:</p> <pre><code>maxvalue = max(sortedlist) for i in sortedlist: if int(count) &lt; int(sortedlist[int(i)]): indexval = i break OutputFile.write(''+str(indexval)+'\n') if int(count) &gt; int(maxvalue): indexval = "over" OutputFile.write(''+str(indexval)+'\n') </code></pre> <p>I thought the break would end the for loop, but I'm only getting results from the last if statement. Am I doing something incorrectly?</p>
0
2016-09-04T15:01:37Z
39,318,522
<p>Using <code>itertools.dropwhile()</code>:</p> <pre class="lang-py prettyprint-override"><code>from itertools import dropwhile sortedlist = [0, 0, 0, 1, 1, 1, 2, 2, 3] def getindex(count): index = len(sortedlist) - len(list(dropwhile(lambda x: x &lt; count, sortedlist))) return "some_string" if index &gt;= len(sortedlist) else index </code></pre> <p>The test:</p> <pre><code>print(getindex(5)) &gt; some_string </code></pre> <p>and:</p> <pre><code>print(getindex(3)) &gt; 8 </code></pre> <h3>Explanation</h3> <p><code>dropwhile()</code> drops the list until the first occurrence, when <code>item &lt; count</code> returns <code>False</code>. By subrtracting the (number of) items <em>after</em> that from the length of the original list, we have the index.</p> <p><em>"<a href="https://docs.python.org/3.1/library/itertools.html#itertools.dropwhile" rel="nofollow">an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element</a>."</em> </p>
0
2016-09-04T15:27:18Z
[ "python", "list", "for-loop" ]
Find index of first occurrence in sorted list
39,318,277
<p>I have a sorted list that looks like this:</p> <pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3'] </code></pre> <p>I also have a count variable:</p> <pre><code>count = '1' </code></pre> <p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code></p> <p>What I want to do is to find the first occurrence of the count in the list and print the index. If the value is greater than the max value in the list, then assign a string. Here is what I have tried:</p> <pre><code>maxvalue = max(sortedlist) for i in sortedlist: if int(count) &lt; int(sortedlist[int(i)]): indexval = i break OutputFile.write(''+str(indexval)+'\n') if int(count) &gt; int(maxvalue): indexval = "over" OutputFile.write(''+str(indexval)+'\n') </code></pre> <p>I thought the break would end the for loop, but I'm only getting results from the last if statement. Am I doing something incorrectly?</p>
0
2016-09-04T15:01:37Z
39,318,704
<p>As there are some over-complicated solutions here it's worth posting how straightforwardly this can be done:</p> <pre><code>def get_index(a, L): for i, b in enumerate(L): if b &gt;= a: return i return "over" get_index('1', ['0','0','2','2','3']) &gt;&gt;&gt; 2 get_index('1', ['0','0','0','1','2','3']) &gt;&gt;&gt; 3 get_index('4', ['0','0','0','1','2','3']) &gt;&gt;&gt; 'over' </code></pre> <p>But, use <code>bisect</code>.</p>
2
2016-09-04T15:46:30Z
[ "python", "list", "for-loop" ]
Find index of first occurrence in sorted list
39,318,277
<p>I have a sorted list that looks like this:</p> <pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3'] </code></pre> <p>I also have a count variable:</p> <pre><code>count = '1' </code></pre> <p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code></p> <p>What I want to do is to find the first occurrence of the count in the list and print the index. If the value is greater than the max value in the list, then assign a string. Here is what I have tried:</p> <pre><code>maxvalue = max(sortedlist) for i in sortedlist: if int(count) &lt; int(sortedlist[int(i)]): indexval = i break OutputFile.write(''+str(indexval)+'\n') if int(count) &gt; int(maxvalue): indexval = "over" OutputFile.write(''+str(indexval)+'\n') </code></pre> <p>I thought the break would end the for loop, but I'm only getting results from the last if statement. Am I doing something incorrectly?</p>
0
2016-09-04T15:01:37Z
39,319,025
<p>First of all:</p> <pre><code>for i in range(1, 100): if i &gt;= 3: break destroyTheInterwebz() print i </code></pre> <p>Will <em>never</em> execute that last function. It will onmy peint <code>1</code> and <code>2</code>. Because <code>break</code> <em>immediately</em> leaves the loop; it does <em>not</em> wait for the current iteration to finish.</p> <p>In my opinion, the code would be nicer if you used a function <code>indexOf</code> and <code>return</code> instead of <code>break</code>.</p> <p>Last but not least: the data structures here are pretty expensive. You may want to use integers instead of strings, and numpy arrays. You could then use the very fast <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>numpy.searchsorted</code></a> function.</p>
0
2016-09-04T16:22:35Z
[ "python", "list", "for-loop" ]
Django archive via crontab in production
39,318,363
<p>I'm having trouble getting crontab to execute a site backup, using django-archive.</p> <p>crontab file:</p> <pre><code>0 5 * * * python ~/SBGBook/gbsite/manage.py archive </code></pre> <p>Error:</p> <pre><code> Traceback (most recent call last): File "/home/jgates/SBGBook/gbsite/manage.py", line 17, in &lt;module&gt; "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available $ </code></pre> <p>The <code>python manage.py archive</code> command works great if I'm in the <code>gbsite/</code> directory, but there's some sort of path issue here, I'm guessing. This is all running in a venv on a production server. </p>
0
2016-09-04T15:10:27Z
39,318,639
<p>Try to use the python interpreter from your virtualenv :</p> <pre><code>0 5 * * * /path/to/virtualenv/bin/python ~/SBGBook/gbsite/manage.py archive </code></pre>
1
2016-09-04T15:39:14Z
[ "python", "django", "crontab", "dev-to-production" ]
converting a flat list to a nested dictionary based on items from the list
39,318,366
<p>For example, I have a flat list like this:</p> <pre><code>[' a', ' aa1', ' aaa1', ' aaa2', ' aaa3', ' aaa4', ' aaa5', ' aa2', ' aaa6', ' aaa7', ' aaa8', ' aaa9', ' aaa10', ' b', ' bb1', ' bbb1', ' bbb2', ' bbb3', ' bb2', ' bbb4', ' bbb5', ' bbb6', ' bb3', ' bbb7', ' bbb8', ' bbb9', ' bbb10'] </code></pre> <p>I need to convert to a nested dictionary like this:</p> <pre><code>{'a': {'aa1': ['aaa1', 'aaa2', 'aaa3', 'aaa4', 'aaa5'], 'aa2': ['aaa6', 'aaa7', 'aaa8', 'aaa9', 'aaa10']}, 'b': {'bb1': ['bbb1', 'bbb2', 'bbb3'], 'bb2': ['bbb4', 'bbb5', 'bbb6'], 'bb3': ['bbb7', 'bbb8', 'bbb9', 'bbb10']}} </code></pre> <p>each item from the list concludes spaces, the item with only one space is assigned as the top key to the nested dictionary, the one with two spaces is assigned as the second level key to the previous item, and then with three spaces items are all the values for the previous key.</p>
2
2016-09-04T15:10:41Z
39,318,871
<p>I think the spaces only make the list awkward, you don't necessarily need them to achieve what you want.</p> <p>First, <code>strip</code> all the spaces from the list items, then build the dictionary starting off from <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a>. The logic that does what you intended to do with the spaces is <code>re.sub</code>. Applied to clear out all the numbers, the length of the string after substitution can now be used to determine its position in the dictionary:</p> <pre><code>import re from pprint import pprint from collections import defaultdict # remove all spaces from list items lst = map(str.strip, lst) d = defaultdict(lambda: defaultdict(list)) for i in lst: j = re.sub('\d+', '', i) if len(j) == 1: k1 = i elif len(j) == 2: k2 = i else: d[k1][k2].append(i) pprint(d) #{'a': {'aa1': ['aaa1', 'aaa2', 'aaa3', 'aaa4', 'aaa5'], # 'aa2': ['aaa6', 'aaa7', 'aaa8', 'aaa9', 'aaa10']}, # 'b': {'bb1': ['bbb1', 'bbb2', 'bbb3'], # 'bb2': ['bbb4', 'bbb5', 'bbb6'], # 'bb3': ['bbb7', 'bbb8', 'bbb9', 'bbb10']}} </code></pre>
2
2016-09-04T16:04:19Z
[ "python", "list", "dictionary" ]