title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
UnboundLocalError from If statement
38,549,500
<p>I keep receiving the error:</p> <pre><code>UnboundLocalError: local variable 'var' referenced before assignment </code></pre> <p>When i try running</p> <pre><code>def func1(): var = True def func2(): if something_random and var == True: do stuff </code></pre>
0
2016-07-24T06:51:29Z
38,549,698
<p>This is because <code>var</code> is defined within the scope of <code>func1</code>, and not in the scope of <code>func2</code>. <a href="http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html" rel="nofollow">See this</a> for an explaination of variable scoping in python.</p>
0
2016-07-24T07:24:43Z
[ "python" ]
UnboundLocalError from If statement
38,549,500
<p>I keep receiving the error:</p> <pre><code>UnboundLocalError: local variable 'var' referenced before assignment </code></pre> <p>When i try running</p> <pre><code>def func1(): var = True def func2(): if something_random and var == True: do stuff </code></pre>
0
2016-07-24T06:51:29Z
38,549,842
<p>When you assign to a variable in a python function, that variable is local to the function by default. You <em>could</em> make it global:</p> <pre><code>var = False # What if func2 was called before func1? def func1(): global var var = True def func2(): global var # Not strictly required, but documentary something_random = True if something_random and var == True: print("stuff") func1() func2() </code></pre> <p>But global variables are to be avoided where possible. Why? Because it can be difficult to follow where they are set, and it means that the functions cannot be reused elsewhere.</p> <p>So a better solution would be to <em>encapsulate</em>:</p> <pre><code>def func1(): var = True return var # func1 could be shortened to: return True def func2(var): something_random = True if something_random and var == True: print("stuff") result = func1() func2(result) # Some people prefer: func2(func1()) </code></pre>
0
2016-07-24T07:46:19Z
[ "python" ]
Python not responding in loop
38,549,507
<p>Here is my code:</p> <pre><code>from random import randint doorNum = randint(1, 3) doorInp = input("Please Enter A Door Number Between 1 and 3: ") x = 1 while (x == 1) : if(doorNum == doorInp) : print("You opened the wrong door and died.") exit() </code></pre> <p>now, that works fine, if I happen to get the unlucky number.</p> <pre><code>else : print("You entered a room.") doorNum = randint(1, 3) </code></pre> <p>This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.</p> <p>I am new to programming in Python, I spent most of my time as a web developer.</p> <p><strong>UPDATE:</strong></p> <p>Thanks @rawing, I can not yet upvote (newbie), so will put it here.</p>
0
2016-07-24T06:51:54Z
38,549,585
<p>In python3, the <code>input</code> function returns a <em>string</em>. You're comparing this <em>string</em> value to a random <em>int</em> value. This will always evaluate to <code>False</code>. Since you only ask for user input <strong>once</strong>, before the loop, the user never gets a chance to choose a new number and the loop keeps comparing a random number to a string forever.</p> <hr> <p>I'm not sure what exactly your code is supposed to do, but you probably wanted to do something like this:</p> <pre><code>from random import randint while True: doorNum = randint(1, 3) doorInp = int(input("Please Enter A Door Number Between 1 and 3: ")) if(doorNum == doorInp) : print("You opened the wrong door and died.") break print("You entered a room.") </code></pre> <p>See also: <a href="http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response">Asking the user for input until they give a valid response</a></p>
-1
2016-07-24T07:07:17Z
[ "python", "shell" ]
Python not responding in loop
38,549,507
<p>Here is my code:</p> <pre><code>from random import randint doorNum = randint(1, 3) doorInp = input("Please Enter A Door Number Between 1 and 3: ") x = 1 while (x == 1) : if(doorNum == doorInp) : print("You opened the wrong door and died.") exit() </code></pre> <p>now, that works fine, if I happen to get the unlucky number.</p> <pre><code>else : print("You entered a room.") doorNum = randint(1, 3) </code></pre> <p>This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.</p> <p>I am new to programming in Python, I spent most of my time as a web developer.</p> <p><strong>UPDATE:</strong></p> <p>Thanks @rawing, I can not yet upvote (newbie), so will put it here.</p>
0
2016-07-24T06:51:54Z
38,549,615
<p>If you are using python3, then <code>input</code> returns a string and comparing a string to an int is always false, thus your <code>exit()</code> function can never run.</p>
0
2016-07-24T07:11:53Z
[ "python", "shell" ]
Python not responding in loop
38,549,507
<p>Here is my code:</p> <pre><code>from random import randint doorNum = randint(1, 3) doorInp = input("Please Enter A Door Number Between 1 and 3: ") x = 1 while (x == 1) : if(doorNum == doorInp) : print("You opened the wrong door and died.") exit() </code></pre> <p>now, that works fine, if I happen to get the unlucky number.</p> <pre><code>else : print("You entered a room.") doorNum = randint(1, 3) </code></pre> <p>This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.</p> <p>I am new to programming in Python, I spent most of my time as a web developer.</p> <p><strong>UPDATE:</strong></p> <p>Thanks @rawing, I can not yet upvote (newbie), so will put it here.</p>
0
2016-07-24T06:51:54Z
38,549,721
<p>Your doorInp variable is a string type, which is causing the issue because you are comparing it to an integer in the if statement. You can easily check by adding something like <code>print(type(doorInp))</code> after your input line. To fix it, just enclose the input statement inside int() like:<code>doorInp = int(input("...."))</code></p>
0
2016-07-24T07:28:40Z
[ "python", "shell" ]
UnicodeEncodeError: Script runs on Spyder and IDLE, yet not on cmd prompt
38,549,695
<p>I have a working script at hand, while it runs on the Spyder IDE and python shell, when I just run it by double clicking, it closes right away. To understand the problem, I ran it through the cmd prompt and encountered the following:</p> <pre><code>Traceback (most recent call last): File "C:\Users\Cheese\Desktop\demografik-proje\demo-form-v-0-1-3.py", line 314, in &lt;module&gt; mainMenu(q_list, xtr_q_list) File "C:\Users\Cheese\Desktop\demografik-proje\demo-form-v-0-1-3.py", line 152, in mainMenu patient_admin = input("Testi uygulayan ki\u015fi: ") #the person who administrated the test File "C:\Program Files\Python35\lib\encodings\cp850.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character '\u015f' in position 18: character maps to &lt;undefined&gt; </code></pre> <p>This question has been asked many times before, but why I'm asking is, this script works fine in some computers, just by double-clicking, yet doesn't work on mine, for instance. From what I gathered, could it be related to the fact that my computer is in English, yet the computers that were able to run were in Turkish? </p> <p>Also since program has many Turkish strings, I'd rather not fiddle with every individual string and rather put a thing on the top or something. I'm even up for setting up a batch file to run the script in UTF8. Or if I could freeze it in such a way that it recognizes UTF8(this would be preferred)? Also, I just checked, and the program works fine if all the turkish chars are removed. As expected.</p> <p>If it's any help, Spyder still runs Python 3.5.1, I have 3.5.2 installed and when I just type "python" on command prompt, Python 3.5.2 runs just fine.</p> <p>Following is the code, if it's any assistance:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Block o' Code """ patient_admin = input("Testi uygulayan kişi: ") #the person who administrated the test #gets input for all the data program needs print("=======================================") """ More block o' code """ </code></pre>
1
2016-07-24T07:24:29Z
38,550,107
<p>Okay, found the solution, wonder how I missed this one (considering I tried to figure this one out for 2-3 hours).</p> <p>To run the program with a non ASCII strings, you can change the code page for the command prompt. To do that: Open Windows Control Panel Select Region and Language Click on the Administrative tab Under Language for non-Unicode programs, click on Change System Locale Choose the locale (Turkish for my case) Click OK</p> <p>It's going to restart your computer, after that, your program should work fine.</p> <p>Source: <a href="http://knowledgebase.progress.com/articles/Article/4677" rel="nofollow">http://knowledgebase.progress.com/articles/Article/4677</a></p>
0
2016-07-24T08:27:34Z
[ "python", "unicode" ]
UnicodeEncodeError: Script runs on Spyder and IDLE, yet not on cmd prompt
38,549,695
<p>I have a working script at hand, while it runs on the Spyder IDE and python shell, when I just run it by double clicking, it closes right away. To understand the problem, I ran it through the cmd prompt and encountered the following:</p> <pre><code>Traceback (most recent call last): File "C:\Users\Cheese\Desktop\demografik-proje\demo-form-v-0-1-3.py", line 314, in &lt;module&gt; mainMenu(q_list, xtr_q_list) File "C:\Users\Cheese\Desktop\demografik-proje\demo-form-v-0-1-3.py", line 152, in mainMenu patient_admin = input("Testi uygulayan ki\u015fi: ") #the person who administrated the test File "C:\Program Files\Python35\lib\encodings\cp850.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character '\u015f' in position 18: character maps to &lt;undefined&gt; </code></pre> <p>This question has been asked many times before, but why I'm asking is, this script works fine in some computers, just by double-clicking, yet doesn't work on mine, for instance. From what I gathered, could it be related to the fact that my computer is in English, yet the computers that were able to run were in Turkish? </p> <p>Also since program has many Turkish strings, I'd rather not fiddle with every individual string and rather put a thing on the top or something. I'm even up for setting up a batch file to run the script in UTF8. Or if I could freeze it in such a way that it recognizes UTF8(this would be preferred)? Also, I just checked, and the program works fine if all the turkish chars are removed. As expected.</p> <p>If it's any help, Spyder still runs Python 3.5.1, I have 3.5.2 installed and when I just type "python" on command prompt, Python 3.5.2 runs just fine.</p> <p>Following is the code, if it's any assistance:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Block o' Code """ patient_admin = input("Testi uygulayan kişi: ") #the person who administrated the test #gets input for all the data program needs print("=======================================") """ More block o' code """ </code></pre>
1
2016-07-24T07:24:29Z
38,550,595
<p><code>input</code> with a string argument does a <code>print</code>, and, notoriously, <a href="https://wiki.python.org/moin/PrintFails" rel="nofollow">PrintFails</a>.</p> <p>The Windows command prompt is hopelessly broken at Unicode. You can change the code page it uses to one that includes the characters you want to print, for example using the command <code>chcp 1254</code> for the legacy Turkish encoding <a href="https://en.wikipedia.org/wiki/Windows-1254" rel="nofollow">code page 1254</a>, before running the Python script. By setting the ‘Language for non-Unicode programs’ you are setting this code page as the default for all command prompts.</p> <p>However this will still fail if you need to use characters that don't exist in 1254. In theory as @PM2Ring suggests you could use code page 65001 (which is nearly UTF-8), but in practice the long-standing bugs in Windows's implementation of this code page usually make it unusable.</p> <p>You could also try installing the <a href="https://pypi.python.org/pypi/win_unicode_console" rel="nofollow">win-unicode-console</a> module, which attempts to work around the problems of the Windows command prompt.</p>
0
2016-07-24T09:34:27Z
[ "python", "unicode" ]
How can I do ordinal regression using the mord module in python?
38,549,756
<p>I am trying to predict a label based on some features and I have some training data. </p> <p>Searching for ordinal regression in python, I found <a href="http://pythonhosted.org/mord/" rel="nofollow">http://pythonhosted.org/mord/</a> but I could not figure out how to use it. </p> <p>It would be great if someone has an example code to demonstrate how to use this module. Here are the classes in the mord module:</p> <pre><code>&gt;&gt;&gt;import mord &gt;&gt;&gt;dir(mord) ['LAD', 'LogisticAT', 'LogisticIT', 'LogisticSE', 'OrdinalRidge', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', 'base', 'check_X_y', 'grad_margin', 'linear_model', 'log_loss', 'metrics', 'np', 'obj_margin', 'optimize', 'propodds_loss', 'regression_based', 'sigmoid', 'svm', 'threshold_based', 'threshold_fit', 'threshold_predict', 'utils'] </code></pre>
0
2016-07-24T07:34:24Z
38,549,926
<p>I believe it follows the API of Scikit-learn. So here is an example:</p> <pre><code>import numpy as np import mord as m c = m.LogisticIT() #Default parameters: alpha=1.0, verbose=0, maxiter=10000 c.fit(np.array([[0,0,0,1],[0,1,0,0],[1,0,0,0]]), np.array([1,2,3])) c.predict(np.array([0,0,0,1])) c.predict(np.array([0,1,0,0])) c.predict(np.array([1,0,0,0])) </code></pre> <p>The output will be as follows:</p> <p><code>array([1])</code></p> <p><code>array([2])</code></p> <p><code>array([3])</code></p> <p>Hope it was helpful</p>
1
2016-07-24T07:59:13Z
[ "python", "machine-learning", "regression", "logistic-regression", "non-linear-regression" ]
How to know file size after reading it as an object in python?
38,549,793
<p>I have a functionality for testing out the file size in python server. But after converting file it into Request object (i.e file converted to python object) size mismatched. File size is somewhat smaller than python object. Files are attached from a form in post request.</p> <p>Is there a way to know correct file size from object in python?</p> <p>I am using tornado server at backend.</p> <p>Thanks</p>
0
2016-07-24T07:40:08Z
38,551,259
<p>Already answered <a href="http://stackoverflow.com/a/19079887/6631262">here</a></p> <pre><code># f is a file-like object. old_file_position = f.tell() f.seek(0, os.SEEK_END) size = f.tell() f.seek(old_file_position, os.SEEK_SET) </code></pre>
1
2016-07-24T10:54:18Z
[ "python", "file", "object", "size", "tornado" ]
Using seek() to create a mean pixel value comparing software in .tiff format?
38,549,807
<p>How does PIL handle seek() function to operate within multiframe .tiff files? I'm trying to extract a piece of information (greyscale pixel values) of various frames in the file, but no matter what I set the seek for, EOFE error is raised. Example code:</p> <pre><code>from PIL import Image im = Image.open('example_recording.tif').convert('LA') width,height = im.size image_lookup = 0 total=0 for i in range(0,width): for j in range(0,height): total += im.getpixel((i,j))[0] total2=0 im.seek(1) for i in range(0,width): for j in range(0,height): total += im.getpixel((i,j))[0] print total print total2 </code></pre> <p>The error log looks like this:</p> <p>File "C:\Users\ltopuser\Anaconda2\lib\site-packages\PIL\Image.py", line 1712, in seek raise EOFError</p> <p>EOFError</p> <p>Cheers, JJ</p>
0
2016-07-24T07:42:10Z
38,608,994
<p>Was caused by PIL getting to end of the file: can be fixed like this;</p> <pre><code>class ImageSequence: def __init__(self, im): self.im = im def __getitem__(self, ix): try: if ix: self.im.seek(ix) return self.im except EOFError: raise IndexError # this is the end of sequence for frame in ImageSequence(im): for i in range(0,width): for j in range(0,height): total += im.getpixel((i,j))[0] </code></pre>
1
2016-07-27T09:29:05Z
[ "python", "image", "tiff", "seek" ]
Python sqlite loop thought all tables in database
38,549,815
<p>I have 700 tables in a <code>test.db</code> file, and was wondering how do I loop through all these tables and return the table name if <code>columnA</code> value is <code>-</code>?</p> <pre><code>connection.execute('SELECT * FROM "all_tables" WHERE "columnA" = "-"') </code></pre> <p>How do I put all 700 tables in <code>all_tables</code>?</p>
0
2016-07-24T07:43:25Z
38,549,944
<p>You could query the <a href="http://www.sqlite.org/faq.html#q7" rel="nofollow">sqlite_master</a> to get all the table names within your database: <code>SELECT name FROM sqlite_master WHERE type = 'table'</code></p> <p><code>sqlite_master</code> can be thought of as a table that contains information about <em>your</em> databases (metadata).</p> <p>A quick but most likely inefficient way (because it will be running 700 queries with 700 separate resultsets) to get the list of table names, loop through those tables and return data where <code>columnA = "-"</code>:</p> <pre><code>for row in connection.execute('SELECT name FROM sqlite_master WHERE type = "table" ORDER BY name').fetchall() for result in connection.execute('SELECT * FROM ' + row[1] + ' WHERE "columnA" = "-"').fetchall() # do something with results </code></pre> <p>Note: Above code is untested but gives you an idea on how to approach this.</p>
1
2016-07-24T08:01:28Z
[ "python", "sqlite", "sqlalchemy" ]
Python sqlite loop thought all tables in database
38,549,815
<p>I have 700 tables in a <code>test.db</code> file, and was wondering how do I loop through all these tables and return the table name if <code>columnA</code> value is <code>-</code>?</p> <pre><code>connection.execute('SELECT * FROM "all_tables" WHERE "columnA" = "-"') </code></pre> <p>How do I put all 700 tables in <code>all_tables</code>?</p>
0
2016-07-24T07:43:25Z
38,550,029
<p>SQLite</p> <p>get all tables name:</p> <pre><code>SELECT name FROM sqlite_master WHERE type='table' ORDER BY name; </code></pre> <p>Cycle</p> <pre><code>for table in tables: ... connection.execute('SELECT * FROM "table1" WHERE "columnA" = "-"') </code></pre> <p>or one SQL request UNION</p> <pre><code>sql = [] for table in tables sql.append('(SELECT * FROM "' + table + '" WHERE "columnA" = "-";)') ' UNION '.join(sql) </code></pre>
1
2016-07-24T08:14:11Z
[ "python", "sqlite", "sqlalchemy" ]
Python sqlite loop thought all tables in database
38,549,815
<p>I have 700 tables in a <code>test.db</code> file, and was wondering how do I loop through all these tables and return the table name if <code>columnA</code> value is <code>-</code>?</p> <pre><code>connection.execute('SELECT * FROM "all_tables" WHERE "columnA" = "-"') </code></pre> <p>How do I put all 700 tables in <code>all_tables</code>?</p>
0
2016-07-24T07:43:25Z
38,550,222
<p>To continue on a theme:</p> <pre><code>import sqlite3 try: conn = sqlite3.connect('/home/rolf/my.db') except sqlite3.Error as e: print('Db Not found', str(e)) db_list = [] mycursor = conn.cursor() for db_name in mycursor.execute("SELECT name FROM sqlite_master WHERE type = 'table'"): db_list.append(db_name) for x in db_list: print "Searching",x[0] try: mycursor.execute('SELECT * FROM '+x[0]+' WHERE columnA" = "-"') stats = mycursor.fetchall() for stat in stats: print stat, "found in ", x except sqlite3.Error as e: continue conn.close() </code></pre>
0
2016-07-24T08:45:30Z
[ "python", "sqlite", "sqlalchemy" ]
code passes all the tests but fails in other tests.. please follow the link
38,549,822
<p>Return the sum of the numbers in the array, ignoring sections of numbers between 6 and 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.</p> <pre><code>sum67([1, 2, 2]) → 5 sum67([1, 2, 2, 6, 99, 99, 7]) → 5 sum67([1, 1, 6, 7, 2]) → 4 </code></pre> <p>my code: </p> <pre><code>def sum67(nums): total = 0 n = 0 while(n &lt; len(nums)): if nums[n] == 6: while(nums[n] != 7 and n &lt; len(nums)): n += 1 n += 1 if n &gt; len(nums)-1: break total += nums[n] n += 1 return total </code></pre> <p><a href="http://codingbat.com/prob/p108886" rel="nofollow">click here to test </a></p>
0
2016-07-24T07:43:56Z
38,549,906
<p>The problem arises if there's a <code>6</code> directly after a <code>7</code>.</p> <p>Your code detects the first <code>6</code> and skips forward past the next <code>7</code>. But if the next number is another <code>6</code>, it won't be skipped.</p> <p>It'll work if you change <code>if nums[n]==6:</code> to <code>while n&lt;len(nums) and nums[n] == 6:</code>.</p>
0
2016-07-24T07:55:52Z
[ "python" ]
code passes all the tests but fails in other tests.. please follow the link
38,549,822
<p>Return the sum of the numbers in the array, ignoring sections of numbers between 6 and 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.</p> <pre><code>sum67([1, 2, 2]) → 5 sum67([1, 2, 2, 6, 99, 99, 7]) → 5 sum67([1, 1, 6, 7, 2]) → 4 </code></pre> <p>my code: </p> <pre><code>def sum67(nums): total = 0 n = 0 while(n &lt; len(nums)): if nums[n] == 6: while(nums[n] != 7 and n &lt; len(nums)): n += 1 n += 1 if n &gt; len(nums)-1: break total += nums[n] n += 1 return total </code></pre> <p><a href="http://codingbat.com/prob/p108886" rel="nofollow">click here to test </a></p>
0
2016-07-24T07:43:56Z
38,549,939
<p>@Rawing got this debugged properly. Here's another simple fix if you prefer:</p> <pre><code>def sum67(nums): total = 0 n = 0 while n &lt; len(nums): if nums[n] == 6: # Skip forward until we find a 7 (or the end of the list). while n &lt; len(nums) and nums[n] != 7: n += 1 else: total += nums[n] # We're either looking at a number we just added to the total, # or we're looking at the 7 we just found. Either way, we need # to move forward to the next number. n += 1 return total </code></pre>
0
2016-07-24T08:00:41Z
[ "python" ]
code passes all the tests but fails in other tests.. please follow the link
38,549,822
<p>Return the sum of the numbers in the array, ignoring sections of numbers between 6 and 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.</p> <pre><code>sum67([1, 2, 2]) → 5 sum67([1, 2, 2, 6, 99, 99, 7]) → 5 sum67([1, 1, 6, 7, 2]) → 4 </code></pre> <p>my code: </p> <pre><code>def sum67(nums): total = 0 n = 0 while(n &lt; len(nums)): if nums[n] == 6: while(nums[n] != 7 and n &lt; len(nums)): n += 1 n += 1 if n &gt; len(nums)-1: break total += nums[n] n += 1 return total </code></pre> <p><a href="http://codingbat.com/prob/p108886" rel="nofollow">click here to test </a></p>
0
2016-07-24T07:43:56Z
38,549,959
<p>As @Rawing pointed out your code doesn't cover the scenario where <code>6</code> follows immediately after <code>7</code>. Instead of having multiple loops and updating loop counter yourself you could just iterate over the numbers on the list and have extra variable telling if you need to skip them or not:</p> <pre><code>def sum67(nums): skip = False total = 0 for x in nums: if skip: if x == 7: skip = False elif x == 6: skip = True else: total += x return total </code></pre>
0
2016-07-24T08:03:49Z
[ "python" ]
Merging data frame columns of strings into one single column in Pandas
38,549,915
<p>I have columns in a dataframe (imported from a CSV) containing text like this.</p> <pre><code>"New york", "Atlanta", "Mumbai" "Beijing", "Paris", "Budapest" "Brussels", "Oslo", "Singapore" </code></pre> <p>I want to collapse/merge all the columns into one single column, like this</p> <pre><code>New york Atlanta Beijing Paris Budapest Brussels Oslo Singapore </code></pre> <p>How to do it in pandas?</p>
4
2016-07-24T07:57:26Z
38,550,047
<p>Suppose you have a <code>DataFrame</code> like so:</p> <pre><code>&gt;&gt;&gt; df 0 1 2 0 New york Atlanta Mumbai 1 Beijing Paris Budapest 2 Brussels Oslo Singapore </code></pre> <p>Then, a simple use of the <code>pd.DataFrame.apply</code> method will work nicely:</p> <pre><code>&gt;&gt;&gt; df.apply(" ".join, axis=1) 0 New york Atlanta Mumbai 1 Beijing Paris Budapest 2 Brussels Oslo Singapore dtype: object </code></pre> <p>Note, I have to pass <code>axis=1</code> so that it is applied across the columns, rather than down the rows. I.e:</p> <pre><code>&gt;&gt;&gt; df.apply(" ".join, axis=0) 0 New york Beijing Brussels 1 Atlanta Paris Oslo 2 Mumbai Budapest Singapore dtype: object </code></pre>
4
2016-07-24T08:17:11Z
[ "python", "pandas" ]
Merging data frame columns of strings into one single column in Pandas
38,549,915
<p>I have columns in a dataframe (imported from a CSV) containing text like this.</p> <pre><code>"New york", "Atlanta", "Mumbai" "Beijing", "Paris", "Budapest" "Brussels", "Oslo", "Singapore" </code></pre> <p>I want to collapse/merge all the columns into one single column, like this</p> <pre><code>New york Atlanta Beijing Paris Budapest Brussels Oslo Singapore </code></pre> <p>How to do it in pandas?</p>
4
2016-07-24T07:57:26Z
38,550,190
<p>A faster (but uglier) version is with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.cat.html" rel="nofollow"><code>.cat</code></a>:</p> <pre><code>df[0].str.cat(df.ix[:, 1:].T.values, sep=' ') 0 New york Atlanta Mumbai 1 Beijing Paris Budapest 2 Brussels Oslo Singapore Name: 0, dtype: object </code></pre> <p>On a larger (10kx5) DataFrame:</p> <pre><code>%timeit df.apply(" ".join, axis=1) 10 loops, best of 3: 112 ms per loop %timeit df[0].str.cat(df.ix[:, 1:].T.values, sep=' ') 100 loops, best of 3: 4.48 ms per loop </code></pre>
4
2016-07-24T08:39:45Z
[ "python", "pandas" ]
Merging data frame columns of strings into one single column in Pandas
38,549,915
<p>I have columns in a dataframe (imported from a CSV) containing text like this.</p> <pre><code>"New york", "Atlanta", "Mumbai" "Beijing", "Paris", "Budapest" "Brussels", "Oslo", "Singapore" </code></pre> <p>I want to collapse/merge all the columns into one single column, like this</p> <pre><code>New york Atlanta Beijing Paris Budapest Brussels Oslo Singapore </code></pre> <p>How to do it in pandas?</p>
4
2016-07-24T07:57:26Z
38,550,724
<p>Here are a couple more ways:</p> <pre><code>def pir(df): df = df.copy() df.insert(2, 's', ' ', 1) df.insert(1, 's', ' ', 1) return df.sum(1) def pir2(df): df = df.copy() return pd.MultiIndex.from_arrays(df.values.T).to_series().str.join(' ').reset_index(drop=True) def pir3(df): a = df.values[:, 0].copy() for j in range(1, df.shape[1]): a += ' ' + df.values[:, j] return pd.Series(a) </code></pre> <hr> <h3>Timing</h3> <p><strong>pir3</strong> seems fastest over small <code>df</code></p> <p><a href="http://i.stack.imgur.com/9djGS.png" rel="nofollow"><img src="http://i.stack.imgur.com/9djGS.png" alt="enter image description here"></a></p> <p><strong>pir3</strong> still fastest over larger <code>df</code> 30,000 rows</p> <p><a href="http://i.stack.imgur.com/iaM8y.png" rel="nofollow"><img src="http://i.stack.imgur.com/iaM8y.png" alt="enter image description here"></a></p>
5
2016-07-24T09:48:49Z
[ "python", "pandas" ]
Merging data frame columns of strings into one single column in Pandas
38,549,915
<p>I have columns in a dataframe (imported from a CSV) containing text like this.</p> <pre><code>"New york", "Atlanta", "Mumbai" "Beijing", "Paris", "Budapest" "Brussels", "Oslo", "Singapore" </code></pre> <p>I want to collapse/merge all the columns into one single column, like this</p> <pre><code>New york Atlanta Beijing Paris Budapest Brussels Oslo Singapore </code></pre> <p>How to do it in pandas?</p>
4
2016-07-24T07:57:26Z
38,551,192
<p>for the sake of completeness:</p> <pre><code>In [160]: df1.add([' '] * (df1.columns.size - 1) + ['']).sum(axis=1) Out[160]: 0 New york Atlanta Mumbai 1 Beijing Paris Budapest 2 Brussels Oslo Singapore dtype: object </code></pre> <p>Explanation:</p> <pre><code>In [162]: [' '] * (df.columns.size - 1) + [''] Out[162]: [' ', ' ', ''] </code></pre> <p><strong>Timing against 300K rows DF:</strong></p> <pre><code>In [68]: df = pd.concat([df] * 10**5, ignore_index=True) In [69]: df.shape Out[69]: (300000, 3) In [76]: %timeit df.apply(" ".join, axis=1) 1 loop, best of 3: 5.8 s per loop In [77]: %timeit df[0].str.cat(df.ix[:, 1:].T.values, sep=' ') 10 loops, best of 3: 138 ms per loop In [79]: %timeit pir(df) 1 loop, best of 3: 499 ms per loop In [80]: %timeit pir2(df) 10 loops, best of 3: 174 ms per loop In [81]: %timeit pir3(df) 10 loops, best of 3: 115 ms per loop In [159]: %timeit df.add([' '] * (df.columns.size - 1) + ['']).sum(axis=1) 1 loop, best of 3: 478 ms per loop </code></pre> <p><strong>Conclusion:</strong> current winner is <a href="http://stackoverflow.com/a/38550724/5741205">@piRSquared's pir3()</a></p>
1
2016-07-24T10:46:38Z
[ "python", "pandas" ]
Merging data frame columns of strings into one single column in Pandas
38,549,915
<p>I have columns in a dataframe (imported from a CSV) containing text like this.</p> <pre><code>"New york", "Atlanta", "Mumbai" "Beijing", "Paris", "Budapest" "Brussels", "Oslo", "Singapore" </code></pre> <p>I want to collapse/merge all the columns into one single column, like this</p> <pre><code>New york Atlanta Beijing Paris Budapest Brussels Oslo Singapore </code></pre> <p>How to do it in pandas?</p>
4
2016-07-24T07:57:26Z
38,551,387
<p>If you prefer something more explicit...</p> <p>Starting with a dataframe df that looks like this:</p> <pre><code>&gt;&gt;&gt; df A B C 0 New york Beijing Brussels 1 Atlanta Paris Oslo 2 Mumbai Budapest Singapore </code></pre> <p>You can create a new column like this:</p> <pre><code>df['result'] = df['A'] + ' ' + df['B'] + ' ' + df['C'] </code></pre> <p>In this case the result is stored in the 'result' column of the original DataFrame:</p> <pre><code> A B C result 0 New york Beijing Brussels New york Beijing Brussels 1 Atlanta Paris Oslo Atlanta Paris Oslo 2 Mumbai Budapest Singapore Mumbai Budapest Singapore </code></pre>
1
2016-07-24T11:10:46Z
[ "python", "pandas" ]
Shifting grid with matplotlib
38,550,017
<p>I'm plotting data which is formatted between 0 and 360 degrees. I'm trying to plot this on cyl or merc projection, but it is only showing data from 0 onwards (I want to plot the data with the GMT in the center, so need the data on a lon grid of -180 to 180). If I shift the grid (lon = lon -180) then all data shows, but the data is in the wrong place by -180 degrees.</p> <p>Issue:</p> <p><a href="http://i.stack.imgur.com/HEdsl.png" rel="nofollow"><img src="http://i.stack.imgur.com/HEdsl.png" alt="enter image description here"></a></p> <p>Works fine in ortho projection though. Relevant code below.</p> <pre><code>lat = np.linspace(90,-90,721) lon = np.linspace(0,360,1440) m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=0,urcrnrlon=360,resolution='c',) X, Y = np.meshgrid(lon, lat) X, Y = m(X, Y) cs = m.contourf(X,Y,Plot,scale, cmap=cmap) </code></pre>
2
2016-07-24T08:12:56Z
38,551,520
<p>I have a solution (albeit an ugly one). By reordering the data.</p> <pre><code>temp = np.zeros((721,1440)) temp[:,0:720] = Plot[:,720:1440] temp[:,720:1440] = Plot[:,0:720] Plot[:]=temp[:] </code></pre>
1
2016-07-24T11:26:29Z
[ "python", "matplotlib", "matplotlib-basemap" ]
Shifting grid with matplotlib
38,550,017
<p>I'm plotting data which is formatted between 0 and 360 degrees. I'm trying to plot this on cyl or merc projection, but it is only showing data from 0 onwards (I want to plot the data with the GMT in the center, so need the data on a lon grid of -180 to 180). If I shift the grid (lon = lon -180) then all data shows, but the data is in the wrong place by -180 degrees.</p> <p>Issue:</p> <p><a href="http://i.stack.imgur.com/HEdsl.png" rel="nofollow"><img src="http://i.stack.imgur.com/HEdsl.png" alt="enter image description here"></a></p> <p>Works fine in ortho projection though. Relevant code below.</p> <pre><code>lat = np.linspace(90,-90,721) lon = np.linspace(0,360,1440) m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=0,urcrnrlon=360,resolution='c',) X, Y = np.meshgrid(lon, lat) X, Y = m(X, Y) cs = m.contourf(X,Y,Plot,scale, cmap=cmap) </code></pre>
2
2016-07-24T08:12:56Z
39,277,671
<p>Please Try:</p> <pre><code>import numpy as np from mpl_toolkits.basemap import shiftgrid from mpl_toolkits.basemap import Basemap lat = np.linspace(-90, 90, 721) lon = np.linspace(0, 360, 1440) Plot, lon = shiftgrid(180., Plot, lon, start=False) # shiftgrid m = Basemap(projection='cyl', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='c',) X, Y = np.meshgrid(lon, lat) X, Y = m(X, Y) cs = m.contourf(X, Y, Plot, scale, cmap=cmap) </code></pre> <p>shiftgrid: shifts global lat/lon grids east or west.</p>
0
2016-09-01T17:33:16Z
[ "python", "matplotlib", "matplotlib-basemap" ]
No Resolution to Pygame Error
38,550,055
<p>I am using anaconda [python 2.7] on ubuntu machine [15.04].</p> <p>I need opencv, pygame, python 2.7 for my code to run.</p> <p>I get the error on running my code:</p> <pre><code>Traceback (most recent call last): File "deep_q_network.py", line 8, in &lt;module&gt; import wrapped_flappy_bird as game File "game/wrapped_flappy_bird.py", line 19, in &lt;module&gt; IMAGES, SOUNDS, HITMASKS = flappy_bird_utils.load() File "game/flappy_bird_utils.py", line 21, in load pygame.image.load('assets/sprites/0.png').convert_alpha(), pygame.error: File is not a Windows BMP file </code></pre> <p>Hours spent on this making the fix. TRied SO solutions. PLease help. Thanks.</p>
1
2016-07-24T08:18:26Z
38,550,068
<p>Read the error: <code>File is not a Windows BMP file</code>. The image you're trying to load seems to be a .png: <code>assets/sprites/0.png</code>. To fix, save the image as a .bmp. Your pygame is missing support for other formats. <a href="http://www.pygame.org/docs/ref/image.html" rel="nofollow">Documentation quote</a>:</p> <blockquote> <p>The image module is a required dependency of Pygame, but it only optionally supports any extended file formats. By default it can only load uncompressed BMP images. When built with full image support, the pygame.image.load() function can support the following formats.</p> </blockquote> <p>To fix it, you need to install python imaging libraries.</p>
0
2016-07-24T08:20:35Z
[ "python", "python-2.7", "opencv" ]
Parsing text file (Python)
38,550,071
<p>I have a text file with a bunch of lines which contains:</p> <pre><code>"blah0","blah1","blah2","blah3","blah4" "blah5","blah6","blah7","blah8","blah9" "blah10","blah11","blah12","blah13","blah14" </code></pre> <p>I have around 50 of these little guys, and I want the script to get rid of the stuff I don't need, all I would need is</p> <pre><code>blah2:blah3 blah7:blah8 blah12:blah13 </code></pre> <p>and so on and so on. How would I achieve this?</p>
-5
2016-07-24T08:21:07Z
38,550,420
<p>I cant tell how what information you really need, but using a spreadsheet editor is probably best. All you would need to do is remove the Quote marks, then your file is in csv format and can be opened in excel or most spreadsheet editors (rename to .csv).</p> <p>To remove the quotes there are many options, like Find &amp; Replace with any text editor (just enter nothing in replace).</p> <p>You really dont need to program anything if you only have one of these files.</p>
-1
2016-07-24T09:12:01Z
[ "python", "parsing" ]
boost python C++ function calling another function error
38,550,098
<p>I have written a function in C++ and built successfully.</p> <p>However, if I just calling it from another function in C++, then the built failed.</p> <pre><code>double getlistvalue(boost::python::list l, int index) { if (index = -1) return 0; else return boost::python::extract&lt;double&gt;(l[index]); } double xx(boost::python::list l, int index) { return getlistvalue(l, index); } </code></pre> <p>the above code, without the second function, it builds.</p> <p>here is the error info: <a href="http://i.stack.imgur.com/cMWTp.png" rel="nofollow">error info</a></p> <p>Please share ideas of how to solve it. thanks a lot.</p>
0
2016-07-24T08:26:15Z
38,550,192
<p>You are passing the lists by value, which requires a copy constructor. The error message is telling you that no copy constructor has been provided for list. The solution therefore is to pass the list by reference:</p> <pre><code>double getlistvalue(const boost::python::list &amp;l, int index) </code></pre> <p>(and the same for the other function).</p> <p>In general, passing complex objects like a list by value is a bad idea, since even if a copy constructor has been provided, actually making the copy can be quite expensive.</p>
1
2016-07-24T08:40:11Z
[ "python", "c++", "boost" ]
Sum for Multiple Ranges on GroupBy Aggregations in Elasticsearch
38,550,149
<p>The following mapping is aggregated on multiple levels on a field grouping documents using another field.</p> <p>Mapping:</p> <pre><code> { 'predictions': { 'properties': { 'Company':{'type':'string'}, 'TxnsId':{'type':'string'}, 'Emp':{'type':'string'}, 'Amount':{'type':'float'}, 'Cash/online':{'type':'string'}, 'items':{'type':'float'}, 'timestamp':{'type':'date'} } } } </code></pre> <p>My requirement is bit complex, I need to </p> <ol> <li>For each Emp (Getting the distinct employees)</li> <li>Check whether it is online or cashed transaction </li> <li>Group by items with the ranges like 0-10,11-20,21-30.... </li> <li>Sum the Amount</li> </ol> <p>Final Output is like:</p> <pre><code>&gt;Emp-online-range-Amount &gt;a-online-(0-10)-1240$ &gt;a-online-(21-30)-3543$ &gt;b-online-(0-10)-2345$ &gt;b-online-(11-20)-3456$ </code></pre>
0
2016-07-24T08:32:45Z
38,560,944
<p>Something like this should do the job:</p> <pre><code>{ "size": 0, "aggs": { "by_emp": { "terms": { "field": "Emp" }, "aggs": { "cash_online": { "filters": { "filters": { "cashed": { "term": { "Cash/online": "cached" } }, "online": { "term": { "Cash/online": "online" } } } }, "aggs": { "ranges": { "range": { "field": "items", "ranges": [ { "from": 0, "to": 11 }, { "from": 11, "to": 21 }, { "from": 21, "to": 31 } ] }, "aggs": { "total": { "sum": { "field": "Amount" } } } } } } } } } } </code></pre>
0
2016-07-25T06:24:22Z
[ "python", "elasticsearch", "dsl", "elasticsearch-query" ]
Matrix terminology
38,550,207
<p>I've found three useful operations when dealing with lists of lists.</p> <pre><code>mat=[list('abc'),list('pqr'),list('xyz')] </code></pre> <p>1.<code>mat=[x for sl in mat for x in sl]</code> ("flatten")</p> <ol start="2"> <li><p><code>mat=list(zip(*mat))</code> (transposing)</p></li> <li><p><code>mat=mat[::-1]</code> ("flip"; first becomes latter and vice versa)</p></li> </ol> <p>What is the <em>specific terminology</em> for these operations, and which key operations am I overlooking?</p>
0
2016-07-24T08:42:16Z
38,552,849
<ol> <li>In my corner of the world, this is often called “rasterizing” a matrix (though we might be appropriating the term from image processing). Numpy calls it <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html" rel="nofollow"><code>ravel()</code></a>. Matlab calls it “vectorize” and uses the <a href="http://www.mathworks.com/help/matlab/ref/colon.html" rel="nofollow">colon operator</a> (search for <code>A(:)</code>).</li> <li>Transpose is the standard mathematical and numerical name.</li> <li>Numpy and Matlab both call this <code>fliplr</code> (left–right) and <code>flipud</code> (up–down).</li> </ol> <p>There are a ton of other matrix operations, some more common, some less. A look thru Numpy/Matlab/Julia/etc. documentation will blow your mind.</p>
0
2016-07-24T14:02:00Z
[ "python", "arrays", "list", "matrix", "linear-algebra" ]
(flask) python - mysql - using where clause in a select query with variable from URL
38,550,263
<pre><code>@app.route('/select/&lt;username&gt;') def select(username): db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" ) cursor = db.cursor() cursor.execute("SELECT * FROM p_shahr") data = cursor.fetchall() db.close() return render_template('select.html', data=data) </code></pre> <p>I want to edit the select query in this script in order to have </p> <pre><code>SELECT * FROm p_shahr WHERE os = username </code></pre> <p>How should I edit the query to include the <em>where clause</em> above to set <code>os</code> to <code>username</code> that is coming from URL?</p>
0
2016-07-24T08:50:30Z
38,550,328
<p>Use string formatting to prepare the query.</p> <pre><code>@app.route('/select/&lt;username&gt;') def select(username): db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" ) cursor = db.cursor() query_string = "SELECT * FROM p_shahr WHERE os = '{username}'".format(username=username) cursor.execute(query_string) data = cursor.fetchall() db.close() return render_template('select.html', data=data) </code></pre>
0
2016-07-24T08:57:40Z
[ "python", "mysql", "select", "flask" ]
pandas.apply() returns NaN from difference between two columns
38,550,304
<p>I want to calculate the absolute differences of two pandas columns <code>I</code> and <code>Imean</code> with the following code</p> <pre><code> def diff(row): """ calculate absolute difference of this row """ return np.abs(row['I'] - row['Imean']) spectrum['diff'] = spectrum.apply(diff, axis=1) </code></pre> <p>Whenever <code>spectrum['I']</code> is all zeros, <code>spectrum['diff']</code> contains all <code>nan</code>. What do I miss? (I can circumvent the error if I check <code>spectrum['I']</code> for the all-zeros case and then <code>spectrum['diff'] = spectrum['Imean']</code>. But still ...)</p> <p>Info added:</p> <p>Ok, I investigated further and tracked down my problem. I normalize my data by the area below the curve and try to avoid division by zero as I know that there might be all-zero data present.</p> <pre><code> s = spectrum['I'].sum() try: spectrum['I'] /= s except ValueError: spectrum['I'] = 0.0 </code></pre> <p>I get no runtime warning from my script but if I run my code in an Ipython console I get <code>RuntimeWarning: invalid value encountered in true_divide</code> and <code>spectrum['I']</code> gets replaced by <code>NaN</code>s. The same if I use <code>ZeroDivisionError</code>. So how do I properly avoid division by zero here?</p>
2
2016-07-24T08:55:03Z
38,550,487
<p>IIUC you can do it this way:</p> <pre><code>In [6]: df = pd.DataFrame(np.random.randint(0, 20, (10,2)), columns=['I', 'Imean']) In [7]: df['diff'] = (df['I'] - df['Imean']).abs() In [8]: df Out[8]: I Imean diff 0 2 9 7 1 9 1 8 2 18 11 7 3 6 19 13 4 5 12 7 5 4 8 4 6 13 3 10 7 1 19 18 8 6 5 1 9 7 0 7 </code></pre> <p>all zeros:</p> <pre><code>In [9]: df.I=0 In [10]: df Out[10]: I Imean diff 0 0 9 7 1 0 1 8 2 0 11 7 3 0 19 13 4 0 12 7 5 0 8 4 6 0 3 10 7 0 19 18 8 0 5 1 9 0 0 7 In [11]: df['diff'] = (df['I'] - df['Imean']).abs() In [12]: df Out[12]: I Imean diff 0 0 9 9 1 0 1 1 2 0 11 11 3 0 19 19 4 0 12 12 5 0 8 8 6 0 3 3 7 0 19 19 8 0 5 5 9 0 0 0 </code></pre> <p>PS as <a href="http://stackoverflow.com/questions/38550304/pandas-apply-returns-nan-from-difference-between-two-columns#comment64491751_38550304">@piRSquared</a> has already mentioned please always provide reproducible sample and desired data sets, when asking pandas questions</p>
1
2016-07-24T09:20:34Z
[ "python", "numpy", "pandas" ]
How to TCP server serves forever?
38,550,322
<p><br></p> <p>Hello everyone!</p> <p>I'm new to python networking programming.</p> <p>My development environments are as below.</p> <ul> <li>Windows 7</li> <li>Python 3.4</li> </ul> <p>I am studying with "Python Network Programming Cookbook". In this book, there's an example of <strong>ThreadingMixIn</strong> socket server application.</p> <p>This book's code is written in Python 2.7. So I've modified for python 3.4. The code is...</p> <pre><code># coding: utf-8 import socket import threading import socketserver SERVER_HOST = 'localhost' SERVER_PORT = 0 # tells the kernel to pick up a port dynamically BUF_SIZE = 1024 def client(ip, port, message): """ A client to test threading mixin server""" # Connect to the server sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, port)) try: message = bytes(message, encoding="utf-8") sock.sendall(message) response = sock.recv(BUF_SIZE) print("Client received: {0}".format(response)) finally: sock.close() class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): """ An example of threaded TCP request handler """ def handle(self): data = self.request.recv(1024) current_thread = threading.current_thread() response = "{0}: {0}".format(current_thread.name, data) response = bytes(response, encoding="utf-8") self.request.sendall(response) class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): """Nothing to add here, inherited everything necessary from parents""" pass if __name__ == "__main__": # Run server server = ThreadedTCPServer((SERVER_HOST, SERVER_PORT), ThreadedTCPRequestHandler) ip, port = server.server_address # retrieve ip address # Start a thread with the server -- one thread per request server_thread = threading.Thread(target=server.serve_forever) # Exit the server thread when the main thread exits server_thread.daemon = True server_thread.start() print("Server loop running on thread: {0}".format(server_thread)) # Run clients client(ip, port, "Hello from client 1") client(ip, port, "Hello from client 2") client(ip, port, "Hello from client 3") </code></pre> <p>This code works perfect. Every client's request processed by new thread. And when the client's request is over, program ends.</p> <p><strong>I want to make server serves forever.</strong> So when the additional client's request has come, server send its response to that client.</p> <p>What should I do?</p> <p>Thank you for reading my question.</p> <p>P.S: Oh, one more. I always write say hello in top of my post of stack overflow. In preview it shows normally. But when the post has saved, first line always gone. Please anyone help me XD</p>
-1
2016-07-24T08:57:19Z
38,550,380
<p>You will have to run on an infinite loop and on each loop wait for some data to come from client. This way the connection will be kept alive.</p> <p>Same infinite loop for the server to accept more clients.</p> <p>However, you will have to somehow detect when a client closes the connection with the server because in most times the server won't be notified.</p>
0
2016-07-24T09:06:09Z
[ "python", "network-programming" ]
How to TCP server serves forever?
38,550,322
<p><br></p> <p>Hello everyone!</p> <p>I'm new to python networking programming.</p> <p>My development environments are as below.</p> <ul> <li>Windows 7</li> <li>Python 3.4</li> </ul> <p>I am studying with "Python Network Programming Cookbook". In this book, there's an example of <strong>ThreadingMixIn</strong> socket server application.</p> <p>This book's code is written in Python 2.7. So I've modified for python 3.4. The code is...</p> <pre><code># coding: utf-8 import socket import threading import socketserver SERVER_HOST = 'localhost' SERVER_PORT = 0 # tells the kernel to pick up a port dynamically BUF_SIZE = 1024 def client(ip, port, message): """ A client to test threading mixin server""" # Connect to the server sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, port)) try: message = bytes(message, encoding="utf-8") sock.sendall(message) response = sock.recv(BUF_SIZE) print("Client received: {0}".format(response)) finally: sock.close() class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): """ An example of threaded TCP request handler """ def handle(self): data = self.request.recv(1024) current_thread = threading.current_thread() response = "{0}: {0}".format(current_thread.name, data) response = bytes(response, encoding="utf-8") self.request.sendall(response) class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): """Nothing to add here, inherited everything necessary from parents""" pass if __name__ == "__main__": # Run server server = ThreadedTCPServer((SERVER_HOST, SERVER_PORT), ThreadedTCPRequestHandler) ip, port = server.server_address # retrieve ip address # Start a thread with the server -- one thread per request server_thread = threading.Thread(target=server.serve_forever) # Exit the server thread when the main thread exits server_thread.daemon = True server_thread.start() print("Server loop running on thread: {0}".format(server_thread)) # Run clients client(ip, port, "Hello from client 1") client(ip, port, "Hello from client 2") client(ip, port, "Hello from client 3") </code></pre> <p>This code works perfect. Every client's request processed by new thread. And when the client's request is over, program ends.</p> <p><strong>I want to make server serves forever.</strong> So when the additional client's request has come, server send its response to that client.</p> <p>What should I do?</p> <p>Thank you for reading my question.</p> <p>P.S: Oh, one more. I always write say hello in top of my post of stack overflow. In preview it shows normally. But when the post has saved, first line always gone. Please anyone help me XD</p>
-1
2016-07-24T08:57:19Z
38,550,548
<p>Your program exits because your server thread is a daemon:</p> <pre><code># Exit the server thread when the main thread exits server_thread.daemon = True </code></pre> <p>You can either remove that line or add <code>server_thread.join()</code> at the bottom of the code to prevent the main thread from exiting early.</p>
1
2016-07-24T09:28:54Z
[ "python", "network-programming" ]
Random number generation with seeds
38,550,345
<p>So in games where you can create "random" worlds there is an option for seeds. The thing i don't understand is: how can you get the same outcome if you fill in the same seed? I would say you have to store every outcome but thats very hard to achieve. I've read something about PRNG(Pseudo random number generator). Every outcome is determined in a PRNG. But i have no idea how to achieve this in python</p>
-3
2016-07-24T09:01:09Z
38,550,384
<p>Just use <code>random.seed</code>:</p> <pre><code>import random random.seed(42) random.random() # 0.6394267984578837 </code></pre> <p>This program will always return that value as the first generated random number, because the seed is always the same.</p>
1
2016-07-24T09:06:38Z
[ "python" ]
Random number generation with seeds
38,550,345
<p>So in games where you can create "random" worlds there is an option for seeds. The thing i don't understand is: how can you get the same outcome if you fill in the same seed? I would say you have to store every outcome but thats very hard to achieve. I've read something about PRNG(Pseudo random number generator). Every outcome is determined in a PRNG. But i have no idea how to achieve this in python</p>
-3
2016-07-24T09:01:09Z
38,550,390
<p>It's quite easy actually, firstly you have to import random library and then you juste have to set the seed manually using your game's seed value :</p> <pre><code>import random your_seed = 1234 random.seed(seed) random.randint(1, 10) </code></pre>
0
2016-07-24T09:07:41Z
[ "python" ]
Random number generation with seeds
38,550,345
<p>So in games where you can create "random" worlds there is an option for seeds. The thing i don't understand is: how can you get the same outcome if you fill in the same seed? I would say you have to store every outcome but thats very hard to achieve. I've read something about PRNG(Pseudo random number generator). Every outcome is determined in a PRNG. But i have no idea how to achieve this in python</p>
-3
2016-07-24T09:01:09Z
38,550,408
<p>A PRNG does not create "random" number but always produces the same numbers when the same seed is used. Thus if you do something in dependence on these numbers you will always do the same when you enter the same seed.</p> <p>In python the <code>random</code> module will take a seed, see <a href="https://docs.python.org/3/library/random.html#random.seed" rel="nofollow">the documentation</a>. If you provide no seed the current system time is chosen and thus it seems random and is often random enough.</p> <p>An example may help you how this relates to level creation.</p> <pre><code>import random elements = ["Enemy1", "Enemy2", "Powerup", "Hazard", "empty", "empty", "empty"] level_length = 100 seed = 100 random.seed(100) level = [] for i in range(level_length): level.append(random.choice(elements)) print(level) </code></pre> <p>This will generate a random level - besides that it is not random but dependent on the seed. If you choose a different seed, you will get a different level. But if you choose the same seed, you will get the same level.</p> <p>Ofcourse this is only a one dimensional level, but it is the same for two or three dimensional level.</p>
0
2016-07-24T09:10:28Z
[ "python" ]
Random number generation with seeds
38,550,345
<p>So in games where you can create "random" worlds there is an option for seeds. The thing i don't understand is: how can you get the same outcome if you fill in the same seed? I would say you have to store every outcome but thats very hard to achieve. I've read something about PRNG(Pseudo random number generator). Every outcome is determined in a PRNG. But i have no idea how to achieve this in python</p>
-3
2016-07-24T09:01:09Z
38,550,480
<h2>How does a RNG end up generating the same sequence given the same seed?</h2> <p>Let's take a trivial RNG implementation:</p> <pre><code>class SillyRand: """Don't try this at home!""" def __init__(self, seed): self.current = self.calc(seed) def get(self): current_ = self.current self.current = self.calc(current_) return current_ def calc(self, prev): return ((prev * 7) + 17) % 100 </code></pre> <p>This implementation contains many flaws, but it should be enough to demonstrate the concept. <strong>It uses the <code>seed</code> as the predecessor of the first random number in the sequence.</strong></p> <p>If we run this:</p> <pre><code>print("Seed is 123") r = SillyRand(123) for i in range(10): print(r.get()) </code></pre> <p>The output will be:</p> <pre><code>Seed is 123 78 63 58 23 78 63 58 23 78 63 </code></pre> <p>And with a different seed...</p> <pre><code>print("Seed is 42") r = SillyRand(42) for i in range(10): print(r.get()) </code></pre> <p>we get a different sequence:</p> <pre><code>Seed is 42 11 94 75 42 11 94 75 42 11 94 </code></pre> <p>But the same seed will give the same sequence every run.</p>
1
2016-07-24T09:19:33Z
[ "python" ]
Python - on windows, how to make all the files as zip?
38,550,392
<p>I have a folder <code>(C:\\Python27\\security_camera_snapshot\\)</code> where <code>image1.png 2.png 3.png .... 100.png</code> is stored. I need to make them in one.zip file and upload it to a NAS server.</p> <p>But how can i do the compression of all those files in zip?</p>
-2
2016-07-24T09:08:05Z
38,550,416
<p>Just use the zipfile library as in this example adapted for your usage : </p> <pre><code>#!/usr/bin/env python import os import zipfile def zipdir(path, ziph): # ziph is zipfile handle for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file)) if __name__ == '__main__': zipf = zipfile.ZipFile('One.zip', 'w', zipfile.ZIP_DEFLATED) zipdir('C:\\Python27\\security_camera_snapshot\\', zipf) zipf.close() </code></pre>
1
2016-07-24T09:11:38Z
[ "python", "windows" ]
web.py multiple parameters query not working
38,550,400
<p>I have created a web.py service.</p> <p>Here is thet code:</p> <pre><code>urls = ('/', 'index') class index: def GET(self): user_data = web.input(url=[]) print (user_data) </code></pre> <p>This is the url that i try to open:</p> <pre><code>http://webpy_server/?url=http://www.phonebook.com.pk/dynamic/search.aspx?searchtype=cat&amp;class_id=4520&amp;page=1 </code></pre> <p>But the problem is that web.py service only detects searchtype=cat as a parameter but other parameters are not being sent with url. I confirmed it using print (user_data) and got this outout in console:</p> <pre><code>&lt;Storage {'url': [u'http://www.phonebook.com.pk/dynamic/search.aspx?searchtype=cat'], 'class_id': u'4520', 'page': u'2'}&gt; </code></pre> <p>class_id and page are detected as other user_data variables. I hope that my explanation is easy to understand. :)</p> <p>This question is not related to <a href="http://stackoverflow.com/questions/29203256/python-web-py-web-service-multiple-parameters-query-not-working">this</a>.</p>
0
2016-07-24T09:09:11Z
38,550,436
<p>You need to escape the URL properly. It should be </p> <pre><code>http://webpy_server/?url=http%3A//www.phonebook.com.pk/dynamic/search.aspx%3Fsearchtype%3Dcat%26class_id%3D4520%26page%3D1 </code></pre> <p>The multiple question-marks are messing things up.</p> <p>(Assuming that cat and the others are meant as parameters to the phonebook, not to your own app.)</p>
1
2016-07-24T09:13:59Z
[ "python", "web.py" ]
python selenium: element not visible in [weird] dropdown to be clicked
38,550,477
<p>There are two dropdown element code: one is standard option-select and the other is made of div, ul, li elements.</p> <p>And somehow both are used to select a dropdown element via javascript...</p> <p>Problem is selenium is not able to click the element and throws not visible exception.....</p> <p>See the dropdown box here: [Its below "Top 5" tab] <a href="http://www.oddsbox.com/baseball/mlb/record/section.odd" rel="nofollow">http://www.oddsbox.com/baseball/mlb/record/section.odd</a></p> <p>Following solutions don't help either: <a href="http://stackoverflow.com/questions/12579061/python-selenium-find-object-attributes-using-xpath">Python Selenium: Find object attributes using xpath</a> <a href="http://stackoverflow.com/questions/27244589/selecting-element-in-python-selenium">selecting element in python selenium</a> <a href="http://stackoverflow.com/questions/18394479/selenium-nested-li-div-menu-select-or-click-python">Selenium nested li div menu select() or click() python</a> <a href="http://stackoverflow.com/questions/22228418/how-to-select-custom-dropdown-list-element-from-selenium">how to select custom dropdown list element from selenium</a></p>
0
2016-07-24T09:19:23Z
38,550,773
<p>It would be nice if you'd post your code, so we can see a bit clearer what's happening. Also admitted, I did not check all of your links to see everything that doesn't work. However my guess is this:</p> <p><em>If you get an <code>ElementNotVisible</code> exception, then you should probably make your element visible before selecting it.</em></p> <p>In this case I'd forget about the selecting commands and all and just : - click on the element to open and reveal the menu and then - click on the desired element inside that list.</p> <p>Looks something like :</p> <pre><code>driver.find_element_by_xpath(".//*[@id='ctmSelectBox4_wrap']/button").click() driver.find_element_by_xpath(".//*[@id='ctmSelectBox4_wrap']/div/ol/li[6]/label/span").click() </code></pre> <p>I personally detest these ugly xpaths (especially for maintainability), and probably would change that somehow, but that's not the scope of this question.</p> <p>Hope that helps!</p>
0
2016-07-24T09:56:00Z
[ "python", "selenium" ]
How to bounce turtle off the canvas
38,550,483
<p>I am currently, learning Charles Dierbach's book, Introduction to Computer Science using Python.</p> <p>I am trying to make my turtle bounce off the canvas but it does not work. I have tried different variations but have not being able to fix it</p> <p>Here is my code:</p> <pre><code> #Drunkard walk PYTHON from turtle import * from random import * #draw a house def house(t): pu() goto(270,100) pd() pensize(5) for i in range(4): fd(100) right(90) setheading(120) fd(100) setheading(240) fd(100) pu() goto(200,0) pd() setheading(90) fd(70) setheading(0) fd(40) setheading(270) fd(70) pu() #make roads def road(t): pu() goto(80, 280) pd() begin_fill() color('black') setheading(270) fd(250) setheading(180) fd(100) setheading(90) fd(250) setheading(0) fd(100) end_fill() pu() goto(80,25) pd() begin_fill() color('white') setheading(270) for i in range(4): fd(70) right(90) fd(100) right(90) end_fill() pu() goto(80, -45) pd() begin_fill() color('black') setheading(270) fd(240) setheading(180) fd(100) setheading(90) fd(240) setheading(0) fd(100) end_fill() #this is my code to keep turtle on canvas def isInScreen(window, t): xmin=-299 xmax=299 ymin=-299 ymax=299 xTcor = t.xcor() yTcor = t.ycor() if xTcor&lt;xmin or xTcor&gt;xmax: new_heading = (180 - t.heading()) return new_heading if yTcor&lt;ymin or yTcor&gt;ymax: new_heading = (360 - t.heading()) return new_heading #house coord if (170&lt;=xTcor&lt;=200 or 200&lt;=xTcor&lt;=270)and yTcor==0: new_heading = (360 - t.heading()) return new_heading if xTcor==170 and 0&lt;=yTcor&lt;=100: new_heading = (180 - t.heading()) return new_heading if (170&lt;=xTcor&lt;=200 or 200&lt;=xTcor&lt;=270) and yTcor==100: new_heading = (360 - t.heading()) return new_heading if xTcor==270 and 0&lt;=yTcor&lt;=100: new_heading = (180 - t.heading()) return new_heading if 170&lt;=xTcor&lt;=271 and 100&lt;=yTcor&lt;=150: new_heading = (360 - t.heading()) return new_heading if 200&lt;=xTcor&lt;=240 and yTcor ==0: new_heading = 0 return new_heading return 100 #################MAIN#################### setup(600,600) window=Screen() window.title("Drunkard walk") window.bgcolor("grey") #get the turtle and change the shape t=getturtle() t.shape('turtle') shapesize(2,1.2,1.2) pu() #change coords and make the ouer roads goto(290,290) pd() setheading(270) pensize(10) for i in range(4): fd(580) right(90) shape('circle') house(t) goto(80,0) road(t) penup() goto(-250,-260) shapesize(1,1,1) walking = True while walking: pendown() fd(10) color = choice(["black", "red", "yellow", "blue", "white", "green"]) fillcolor(color) ch = randrange(2) if ch == 0: left(90) else: right(90) setheading(isInScreen(window, t)) mainloop() exitonclick() </code></pre>
0
2016-07-24T09:20:07Z
38,558,123
<p>I've extracted a minimum example from your code and got it bouncing about the screen. The key changes are:</p> <p>1) your routine that decides if the turtle should bounce off a wall shouldn't do anything if the turtle hasn't actually reached a wall -- but you return a new heading regardless</p> <p>2) you shouldn't create an infinite loop when using turtle graphics, this prevents the event handlers from running (e.g. <code>exitonclick()</code> doesn't work in your code as it's never reached.) Intead use the timer features provided to run your turtle within the event framework: </p> <pre><code>import turtle CANVAS_WIDTH, CANVAS_HEIGHT = 600, 600 def headIntoCanvas(t): """ keep turtle on canvas """ xmin, xmax = -CANVAS_WIDTH // 2, CANVAS_WIDTH // 2 ymin, ymax = -CANVAS_HEIGHT // 2, CANVAS_HEIGHT // 2 xTcor, yTcor = t.position() old_heading = t.heading() if not xmin &lt; xTcor &lt; xmax: new_heading = (180 - old_heading) return new_heading # bounce off wall if not ymin &lt; yTcor &lt; ymax: new_heading = (360 - old_heading) return new_heading # bounce off floor/ceiling return old_heading # stay the course def motion(): """ make the turtle march around """ t.forward(5) t.setheading(headIntoCanvas(t)) turtle.ontimer(motion, 25) # again! turtle.setup(CANVAS_WIDTH, CANVAS_HEIGHT) # get the turtle and change the shape t = turtle.Turtle() t.shape('circle') t.shapesize(1, 1, 1) t.speed("fastest") t.penup() t.goto(- CANVAS_WIDTH // 3, - CANVAS_HEIGHT // 3) t.pendown() t.setheading(120) motion() turtle.exitonclick() </code></pre> <p><a href="http://i.stack.imgur.com/sM70w.png" rel="nofollow"><img src="http://i.stack.imgur.com/sM70w.png" alt="enter image description here"></a></p>
0
2016-07-25T00:15:03Z
[ "python", "function", "graphics", "turtle-graphics", "bounce" ]
CRC16-CCITT for binary file using python
38,550,489
<p>What is the maximum size of file that CRC16-CCITT calculates?</p> <p>If I split the binary file on blocks of 256*1024, can I add the crc result of each block to determine the CRC of the whole file?</p> <p>what is the criterias to choose CRC-16CCITT and CRC-32CCITT?</p>
-1
2016-07-24T09:20:40Z
38,551,761
<p>CRC imposes no limit on file size. However your library should support feeding data in chunks to calculate crc. Simply adding CRC values of chunks won't work - you have to use CRC of preceding chunk as the starting value for next chunk CRC calculation and that needs to be support by your library.</p> <p>E.g. <a href="https://github.com/gtrafimenkov/pycrc16" rel="nofollow">pycrc16</a> gives this example of doing just that:</p> <pre><code>import crc16 crc = crc16.crc16xmodem(b'1234') crc = crc16.crc16xmodem(b'56789', crc) </code></pre> <p>On the 16 vs 32 bit part. In general, the more bits are there the lower is probability of collisions and so are better chances of detecting errors. But that is also strongly dependent on the polynomial as well as other parameters for the CRC. So choosing a right/best CRC is a good pretext for a holly war :o).</p> <p>I'm worried about "CRC-32CCITT" though. CRC names are somewhat arbitrary and often same name refer to different algorithms and many algorithms have multiple names. But as far as I know, "CCITT" always refer to a CRC-16 algorithm. So, as a word of caution - simple extension from 16 bits to 32 bits isn't a good idea as good 16-bit polynomials usually aren't very good as 32 bit polynomials. If you prefer to use 32-bit CRC, I'd suggest choosing a proper 32-bit CRC. See <a href="http://reveng.sourceforge.net/crc-catalogue/" rel="nofollow">here</a> a good list of "known good" parameter sets.</p>
2
2016-07-24T11:59:48Z
[ "python", "crc" ]
Command completions are invisible in ipython 5.0
38,550,608
<p>In ipython 5.0, the autocompletion function seems to be replaced by a new one.</p> <p>Now "os.[tab]" does not display a list of possible commands, but seems to cycle through the module members. But while it does, it seems to display below the current line a list of possible members, but all but the currently selected one are black on black on a standard terminal (urxvt), which worked with ipython 4.0 before just fine.</p> <p>How can i adjust the colors (of the inactive items) or get back to the old completion mode?</p> <p>The ipython is a fresh installation in a python2 <code>virtualenv</code> on Debian linux.</p> <p>Screenshot: <a href="http://i.stack.imgur.com/G6nzu.png" rel="nofollow"><img src="http://i.stack.imgur.com/G6nzu.png" alt="enter image description here"></a></p> <p>When i press tab again, <code>os.abort</code> is hidden and <code>os.access</code> below becomes bright white. Hitting tab a few more times it goes further down and then jumps to the next column with <code>os.chdir</code>. Looks like intended behaviour for this (different) kind of tab completion, but the colors of the inactive entries are wrong.</p> <p>In KDE "konsole" it behaves differently: <a href="http://i.stack.imgur.com/DVUvX.png" rel="nofollow"><img src="http://i.stack.imgur.com/DVUvX.png" alt="enter image description here"></a></p> <p>in an xterm (with default white background) the font colors are the same, so this does not depend on the terminals color scheme.</p> <p>I reset my urxvt settings and got with a default white terminal:</p> <p><a href="http://i.stack.imgur.com/jgWXT.png" rel="nofollow"><img src="http://i.stack.imgur.com/jgWXT.png" alt=""></a></p> <p>So the black / white foreground colors seem to work, but both gray tones are not displayed. I wonder if its an urxvt or ipython bug, maybe with non-standard color names or something similiar.</p>
4
2016-07-24T09:35:48Z
38,554,161
<p>On my terminal (Ubuntu linux) the completion list appears as black text on a gray background. Up/down keys scroll through this, with the current selection appearing on the <code>IN</code> line as well as highlighted with white text on dark gray. </p> <p>Repeated tab also steps through the list (column by column). Lists that are too long to show on the window has <code>&lt;&gt;</code> edge markings. I can see that <code>&gt;</code> on your screen shot.</p> <p>I not fully adjusted, but for long lists (e.g. whole <code>os</code>) it is better than the previous <code>less</code> style of paging.</p> <p>It looks like your terminal color scheme does not handle this gray and dark gray back grounds. I use a default Ubuntu (Mate) terminal with a black on white, but this tab highlighting works the same if I switch to a <code>white on black</code> profile.</p> <p>My ipython profile includes</p> <pre><code>c.TerminalInteractiveShell.color_info = True (default) c.TerminalInteractiveShell.colors = 'LightBG' </code></pre> <p>I've played with <code>%colors</code> and profile settings, and can't get rid of the gray background.</p> <p>So the problem could be in your terminal profile, or in the <code>ipython</code> config settings. I don't know if there's a way of reverting the tab completion back to the previous style.</p>
1
2016-07-24T16:20:27Z
[ "python", "terminal", "ipython" ]
Command completions are invisible in ipython 5.0
38,550,608
<p>In ipython 5.0, the autocompletion function seems to be replaced by a new one.</p> <p>Now "os.[tab]" does not display a list of possible commands, but seems to cycle through the module members. But while it does, it seems to display below the current line a list of possible members, but all but the currently selected one are black on black on a standard terminal (urxvt), which worked with ipython 4.0 before just fine.</p> <p>How can i adjust the colors (of the inactive items) or get back to the old completion mode?</p> <p>The ipython is a fresh installation in a python2 <code>virtualenv</code> on Debian linux.</p> <p>Screenshot: <a href="http://i.stack.imgur.com/G6nzu.png" rel="nofollow"><img src="http://i.stack.imgur.com/G6nzu.png" alt="enter image description here"></a></p> <p>When i press tab again, <code>os.abort</code> is hidden and <code>os.access</code> below becomes bright white. Hitting tab a few more times it goes further down and then jumps to the next column with <code>os.chdir</code>. Looks like intended behaviour for this (different) kind of tab completion, but the colors of the inactive entries are wrong.</p> <p>In KDE "konsole" it behaves differently: <a href="http://i.stack.imgur.com/DVUvX.png" rel="nofollow"><img src="http://i.stack.imgur.com/DVUvX.png" alt="enter image description here"></a></p> <p>in an xterm (with default white background) the font colors are the same, so this does not depend on the terminals color scheme.</p> <p>I reset my urxvt settings and got with a default white terminal:</p> <p><a href="http://i.stack.imgur.com/jgWXT.png" rel="nofollow"><img src="http://i.stack.imgur.com/jgWXT.png" alt=""></a></p> <p>So the black / white foreground colors seem to work, but both gray tones are not displayed. I wonder if its an urxvt or ipython bug, maybe with non-standard color names or something similiar.</p>
4
2016-07-24T09:35:48Z
38,575,512
<p>Debian has a separate package <code>rxvt-unicode-256color</code> for the version with full color support. Using this version, the ipython colors are correct.</p>
1
2016-07-25T18:58:13Z
[ "python", "terminal", "ipython" ]
Calling a function within a class instead of function using multiprocessing in Python
38,550,733
<p>In the Python <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">documentation on multiprocessing</a> there are numerous examples of parallelizing the work of a function. I assumed it would also be possible to do this of a function contained in a class. However the following example does not work. It spawns for processes that calculate the multiplication of 2 of the current process number. Reporting the calculated value inside the object works, however when I try to get the calculated value after the jobs are finished it just reports back the value set in the constructor.</p> <p>Class definition</p> <pre><code>import multiprocessing class MyClass(): def __init__(self,runname): self.runname = runname self.output = 0 def calculate(self,input): self.output = input*2 print "Reporting from runname %s, calculation yielded %s" % (self.runname,self.output) def getOutput(self): return self.output </code></pre> <p>Code to call the object:</p> <pre><code>objectList = [] #Store objects jobList = [] #Store multiprocessing objects #Run the workers in 4 parallel processes for i in range(4): thisRunname = 'Worker:%s' % i thisInstance = MyClass(thisRunname) p = multiprocessing.Process(target=thisInstance.calculate, args=(i,)) jobList.append(p) p.start() objectList.append(thisInstance) for thisJob in jobList: #Wait till all jobs are done thisJob.join() print "Jobs finished" for thisInstance in objectList: print "Worker %s calculated %s " % (thisInstance.runname,thisInstance.getOutput() ) </code></pre> <p><strong>This outputs:</strong></p> <pre><code>Reporting from runname Worker:0, calculation yielded 0 Reporting from runname Worker:1, calculation yielded 2 Reporting from runname Worker:2, calculation yielded 4 Reporting from runname Worker:3, calculation yielded 6 Jobs finished Worker Worker:0 calculated 0 Worker Worker:1 calculated 0 Worker Worker:2 calculated 0 Worker Worker:3 calculated 0 </code></pre> <p>So the calculate function can be spawned without problem, when trying to retrieve the calculated value it just gives back 0, the value it was set to in the constructor.</p> <p>Is there a key concept I'm missing, how is it possible to obtain the self.output value?</p>
0
2016-07-24T09:50:05Z
38,550,887
<p>The serialization provided by the <code>Process</code> class is only one-way. It will serialize the <code>target</code> and <code>args</code> you give it, but it doesn't bring anything back automatically.</p> <p>So when you create your <code>Process</code>es, the <code>multiprocessing</code> module pickles the <code>MyClass</code> instances you've created (since the <code>target</code>s are bound methods of the instances) and each one gets unpickled it in one of the child processes. This is why each of the children does the calculation as you expect.</p> <p>However, the changes to the child process's version of the instance don't ever get copied back to the main process. There's simply no mechanism to do it. In the end the instances get thrown away when the child process ends. The parent process's instances of <code>MyClass</code> are not updated, which is why you see the <code>calculated 0</code> messages.</p>
1
2016-07-24T10:10:12Z
[ "python", "multiprocessing" ]
unable to stop thread from a module
38,550,828
<p>I need to be able to call a stop funtion of a running thread. I tried several ways to achieve this but so far no luck. I think I need a thread id but have no idea how this is done.</p> <p>relevant code: model:</p> <pre><code>import MODULE class do_it(): def __init__(self): self.on_pushButton_start_clicked() return def on_pushButton_start_clicked(self): self.Contr = MODULE.Controller() self.Contr.start() def on_pushButton_stop_clicked(self): if self.Contr: self.Contr.stop() self.Contr = None return </code></pre> <p>module:</p> <pre><code>import thread class Controller(): def __init__(self): self.runme = False def start(self): """Using this to start the controllers eventloop.""" thread.start_new_thread(self._run, ()) def stop(self): """Using this to stop the eventloop.""" self.runme = False def _run(self): """The actual eventloop""" self.runme = True </code></pre> <p>I think my issue lies here...<br> my controller:</p> <pre><code> """I want to use this to control my model, that in turn controls the module""" def start_module(): start=do_it().on_pushButton_start_clicked() return 'Ran start function' def stop_module(): stop=do_it().on_pushButton_stop_clicked() return 'Ran stop function' </code></pre>
0
2016-07-24T10:02:35Z
38,551,293
<p>Regarding the <code>thread</code> module, this is what the docs say:</p> <blockquote> <p>This module provides low-level primitives for working with multiple threads […] The <code>threading</code> module provides an easier to use and higher-level threading API built on top of this module.</p> </blockquote> <p>Furthermore, there is no way to stop or kill a thread once it's started. <a href="http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python">This</a> SO question goes further into detail and shows how to use a <code>threading.Event</code> to implement a stoppable thread.</p> <p>The only difference is a <a href="https://docs.python.org/2.7/library/multiprocessing.html#multiprocessing.Process.daemon" rel="nofollow">daemon thread</a>, which will be killed automatically when your main program exists.</p>
0
2016-07-24T10:58:14Z
[ "python", "multithreading", "class", "web2py", "python-module" ]
Python pip2 fails - ImportError: No module named moves
38,550,925
<p>I can't run pip2, which is installed from its Arch Linux package:</p> <pre><code>$ pip2 Traceback (most recent call last): File "/usr/bin/pip2", line 5, in &lt;module&gt; from pkg_resources import load_entry_point File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 47, in &lt;module&gt; from pkg_resources.extern.six.moves import urllib, map, filter ImportError: No module named moves </code></pre> <p>I reinstalled python2-pip2 and python2-setuptools with no results. This has been a problem for months.</p>
0
2016-07-24T10:15:32Z
38,550,926
<p>While I don't understand the issue, it is possible to reset it by removing locally (<code>--user</code>) installed packages:</p> <p>Move all packages installed as the user:</p> <pre><code>mv ~/.local/lib/python2.7/site-packages ~/site-packages-bak </code></pre> <p>or try to pinpoint the problematic files. In my case, for some reason I had a python file and its <code>pyc</code> file lying around the <code>site-packages</code> directory and just moving them solved my issue:</p> <pre><code>mv ~/.local/lib/python2.7/site-packages/six.py ~/six.py-bak mv ~/.local/lib/python2.7/site-packages/six.pyc ~/six.pyc-bak </code></pre>
0
2016-07-24T10:15:32Z
[ "python", "pip" ]
Dynamically generated field in SqlAlchemy model with Postgres
38,550,984
<p>I want to create a table with a column for each hour of the day of Float type. How do I get rid of this verbose syntax:</p> <pre><code>from app import db class HourlySchedule(db.Model): id = db.Column( db.Integer, primary_key=True ) h0 = db.Column(db.Float, nullable=True) h1 = db.Column(db.Float, nullable=True) h2 = db.Column(db.Float, nullable=True) h3 = db.Column(db.Float, nullable=True) h4 = db.Column(db.Float, nullable=True) h5 = db.Column(db.Float, nullable=True) h6 = db.Column(db.Float, nullable=True) h7 = db.Column(db.Float, nullable=True) h8 = db.Column(db.Float, nullable=True) h9 = db.Column(db.Float, nullable=True) h10 = db.Column(db.Float, nullable=True) h11 = db.Column(db.Float, nullable=True) h12 = db.Column(db.Float, nullable=True) h13 = db.Column(db.Float, nullable=True) h14 = db.Column(db.Float, nullable=True) h15 = db.Column(db.Float, nullable=True) h16 = db.Column(db.Float, nullable=True) h17 = db.Column(db.Float, nullable=True) h18 = db.Column(db.Float, nullable=True) h19 = db.Column(db.Float, nullable=True) h20 = db.Column(db.Float, nullable=True) h21 = db.Column(db.Float, nullable=True) h22 = db.Column(db.Float, nullable=True) h23 = db.Column(db.Float, nullable=True) </code></pre> <p>Another question is how do I enforce checks on the values (e.g. 0 &lt;= value &lt;=1)? </p> <p>As validation? Then how do i set validation neatly for 24 fields? </p> <p>Can I instead add a check constraint with SqlAlchemy?</p>
0
2016-07-24T10:22:21Z
38,553,323
<p>You may need to play around with the order of calling <code>super().__init__(*args, **kwargs)</code>, but this should theoretically work.</p> <p>As for validation, the good thing about the <code>validates</code> decorator is that it takes multiple column names, so we can achieve dynamic field creation and validation like so:</p> <pre><code>from app import db from sqlalchemy.orm import validates class HourlySchedule(db.Model): id = db.Column( db.Integer, primary_key=True ) def __init__(self, *args, **kwargs): self.colstrings = [] for hour in range(0, 24): colstring = "h{}".format(hour) setattr(self, colstring, db.Column(db.Float, nullable=True)) self.colstrings.append(colstring) super().__init__(*args, **kwargs) @validates(*self.colstrings) def validate_hours(self, key, hour): assert 0 &lt; hour &lt; 1 return hour </code></pre> <p>One thing I'd like to note, however, is that this is actually greatly increases the complexity of a rather simple concept. Instead of hiding model details, which are meant to be verbose so devs can easily understand model > table mappings, it might make more sense to either list out every column, or to rethink how you're structuring your data.</p>
-1
2016-07-24T14:49:16Z
[ "python", "flask", "sqlalchemy", "data-modeling" ]
Dynamically generated field in SqlAlchemy model with Postgres
38,550,984
<p>I want to create a table with a column for each hour of the day of Float type. How do I get rid of this verbose syntax:</p> <pre><code>from app import db class HourlySchedule(db.Model): id = db.Column( db.Integer, primary_key=True ) h0 = db.Column(db.Float, nullable=True) h1 = db.Column(db.Float, nullable=True) h2 = db.Column(db.Float, nullable=True) h3 = db.Column(db.Float, nullable=True) h4 = db.Column(db.Float, nullable=True) h5 = db.Column(db.Float, nullable=True) h6 = db.Column(db.Float, nullable=True) h7 = db.Column(db.Float, nullable=True) h8 = db.Column(db.Float, nullable=True) h9 = db.Column(db.Float, nullable=True) h10 = db.Column(db.Float, nullable=True) h11 = db.Column(db.Float, nullable=True) h12 = db.Column(db.Float, nullable=True) h13 = db.Column(db.Float, nullable=True) h14 = db.Column(db.Float, nullable=True) h15 = db.Column(db.Float, nullable=True) h16 = db.Column(db.Float, nullable=True) h17 = db.Column(db.Float, nullable=True) h18 = db.Column(db.Float, nullable=True) h19 = db.Column(db.Float, nullable=True) h20 = db.Column(db.Float, nullable=True) h21 = db.Column(db.Float, nullable=True) h22 = db.Column(db.Float, nullable=True) h23 = db.Column(db.Float, nullable=True) </code></pre> <p>Another question is how do I enforce checks on the values (e.g. 0 &lt;= value &lt;=1)? </p> <p>As validation? Then how do i set validation neatly for 24 fields? </p> <p>Can I instead add a check constraint with SqlAlchemy?</p>
0
2016-07-24T10:22:21Z
38,575,915
<p>The key here is to realize that a <code>class</code> block is just a block of code, so you can put loops in there:</p> <pre><code>class HourlySchedule(db.Model): id = db.Column(db.Integer, primary_key=True) for i in range(24): locals()["h{}".format(i)] = db.Column(db.Float) @validates(*("h{}".format(i) for i in range(24))) def _validate(self, k, h): assert 0 &lt;= h &lt;= 1 return h </code></pre>
0
2016-07-25T19:26:02Z
[ "python", "flask", "sqlalchemy", "data-modeling" ]
Strange behaviour: Same code, different errors
38,551,016
<p>I have to use packages tensorflow and pygame.</p> <p>In my machine [Ubuntu 15.04][Anaconda, Python=2.7] I installed pygame and tensorflow in the same environment.</p> <p>Now, when I import tensorflow in the Python interpreter:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; import tensorflow </code></pre> <p>it works fine. If I go into the interpreter via <code>/usr/bin/python</code></p> <p>and do <code>&gt;&gt;&gt; import tensorflow</code> I get: </p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named tensorflow </code></pre> <p>On top of this, every time in the <code>/usr/bin/python</code>,</p> <p>Upon running a program I get:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; execfile("deep_q_network.py") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "deep_q_network.py", line 4, in &lt;module&gt; import tensorflow as tf ImportError: No module named tensorflow </code></pre> <p>and In running the same program in <code>python</code> interpreter, I get:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; execfile("deep_q_network.py") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "deep_q_network.py", line 8, in &lt;module&gt; import wrapped_flappy_bird as game File "game/wrapped_flappy_bird.py", line 19, in &lt;module&gt; IMAGES, SOUNDS, HITMASKS = flappy_bird_utils.load() File "game/flappy_bird_utils.py", line 21, in load pygame.image.load('assets/sprites/0.png').convert_alpha(), pygame.error: File is not a Windows BMP file </code></pre> <p>It seems in anyway my code is failing despite hours spent on installing and fixing those installs.</p> <p>Please help if this could be resolved.</p> <hr> <p><code>pip show tensorflow</code> gives:</p> <pre class="lang-none prettyprint-override"><code>--- Metadata-Version: 2.0 Name: tensorflow Version: 0.9.0 Summary: TensorFlow helps the tensors flow Home-page: http://tensorflow.org/ Author: Google Inc. Author-email: opensource@google.com Installer: pip License: Apache 2.0 Location: /home/v/anaconda2/envs/tensorflow/lib/python2.7/site-packages Requires: numpy, six, protobuf, wheel Classifiers: Development Status :: 4 - Beta Intended Audience :: Developers Intended Audience :: Education Intended Audience :: Science/Research License :: OSI Approved :: Apache Software License Programming Language :: Python :: 2.7 Topic :: Scientific/Engineering :: Mathematics Topic :: Software Development :: Libraries :: Python Modules Topic :: Software Development :: Libraries Entry-points: [console_scripts] tensorboard = tensorflow.tensorboard.tensorboard:main </code></pre>
0
2016-07-24T10:25:30Z
38,551,099
<p>Have you installed Anaconda in the correct way?</p> <pre><code>$ conda install virtualenv $ conda create --name=tensorflow_env python=2.7 $ source activate tensorflow_env $ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl </code></pre> <p>Maybe, you also have installed it in the wrong directory. Try to run: <code>pip show tensorflow</code> and make sure it's in the right path.</p>
0
2016-07-24T10:36:45Z
[ "python", "python-2.7", "pygame", "tensorflow", "development-environment" ]
Strange behaviour: Same code, different errors
38,551,016
<p>I have to use packages tensorflow and pygame.</p> <p>In my machine [Ubuntu 15.04][Anaconda, Python=2.7] I installed pygame and tensorflow in the same environment.</p> <p>Now, when I import tensorflow in the Python interpreter:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; import tensorflow </code></pre> <p>it works fine. If I go into the interpreter via <code>/usr/bin/python</code></p> <p>and do <code>&gt;&gt;&gt; import tensorflow</code> I get: </p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named tensorflow </code></pre> <p>On top of this, every time in the <code>/usr/bin/python</code>,</p> <p>Upon running a program I get:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; execfile("deep_q_network.py") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "deep_q_network.py", line 4, in &lt;module&gt; import tensorflow as tf ImportError: No module named tensorflow </code></pre> <p>and In running the same program in <code>python</code> interpreter, I get:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; execfile("deep_q_network.py") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "deep_q_network.py", line 8, in &lt;module&gt; import wrapped_flappy_bird as game File "game/wrapped_flappy_bird.py", line 19, in &lt;module&gt; IMAGES, SOUNDS, HITMASKS = flappy_bird_utils.load() File "game/flappy_bird_utils.py", line 21, in load pygame.image.load('assets/sprites/0.png').convert_alpha(), pygame.error: File is not a Windows BMP file </code></pre> <p>It seems in anyway my code is failing despite hours spent on installing and fixing those installs.</p> <p>Please help if this could be resolved.</p> <hr> <p><code>pip show tensorflow</code> gives:</p> <pre class="lang-none prettyprint-override"><code>--- Metadata-Version: 2.0 Name: tensorflow Version: 0.9.0 Summary: TensorFlow helps the tensors flow Home-page: http://tensorflow.org/ Author: Google Inc. Author-email: opensource@google.com Installer: pip License: Apache 2.0 Location: /home/v/anaconda2/envs/tensorflow/lib/python2.7/site-packages Requires: numpy, six, protobuf, wheel Classifiers: Development Status :: 4 - Beta Intended Audience :: Developers Intended Audience :: Education Intended Audience :: Science/Research License :: OSI Approved :: Apache Software License Programming Language :: Python :: 2.7 Topic :: Scientific/Engineering :: Mathematics Topic :: Software Development :: Libraries :: Python Modules Topic :: Software Development :: Libraries Entry-points: [console_scripts] tensorboard = tensorflow.tensorboard.tensorboard:main </code></pre>
0
2016-07-24T10:25:30Z
38,634,839
<p>try <code>$ sudo pip install tensorflow</code></p>
0
2016-07-28T11:18:36Z
[ "python", "python-2.7", "pygame", "tensorflow", "development-environment" ]
Radio Button in Pygame?
38,551,168
<p>I want to know if there's a radio button in pygame or a module of it. I'm making a questions game which requires radio buttons.</p>
-1
2016-07-24T10:43:04Z
38,625,795
<p>I know how you feel man, I needed some radio buttons to. I have, however, been working on a checkbox in pygame. I'll post the code below if you want to use it:</p> <pre><code>import pygame as pg pg.init() class Checkbox: def __init__(self, surface, x, y, color=(230, 230, 230), caption="", outline_color=(0, 0, 0), check_color=(0, 0, 0), font_size=22, font_color=(0, 0, 0), text_offset=(28, 1)): self.surface = surface self.x = x self.y = y self.color = color self.caption = caption self.oc = outline_color self.cc = check_color self.fs = font_size self.fc = font_color self.to = text_offset # checkbox object self.checkbox_obj = pg.Rect(self.x, self.y, 12, 12) self.checkbox_outline = self.checkbox_obj.copy() # variables to test the different states of the checkbox self.checked = False self.active = False self.unchecked = True self.click = False def _draw_button_text(self): self.font = pg.font.Font(None, self.fs) self.font_surf = self.font.render(self.caption, True, self.fc) w, h = self.font.size(self.caption) self.font_pos = (self.x + 12 / 2 - w / 2 + self.to[0], self.y + 12 / 2 - h / 2 + self.to[1]) self.surface.blit(self.font_surf, self.font_pos) def render_checkbox(self): if self.checked: pg.draw.rect(self.surface, self.color, self.checkbox_obj) pg.draw.rect(self.surface, self.oc, self.checkbox_outline, 1) pg.draw.circle(self.surface, self.cc, (self.x + 6, self.y + 6), 4) elif self.unchecked: pg.draw.rect(self.surface, self.color, self.checkbox_obj) pg.draw.rect(self.surface, self.oc, self.checkbox_outline, 1) self._draw_button_text() def _update(self, event_object): x, y = event_object.pos # self.x, self.y, 12, 12 px, py, w, h = self.checkbox_obj # getting check box dimensions if px &lt; x &lt; px + w and px &lt; x &lt; px + w: self.active = True else: self.active = False def _mouse_up(self): if self.active and not self.checked and self.click: self.checked = True elif self.checked: self.checked = False self.unchecked = True if self.click is True and self.active is False: if self.checked: self.checked = True if self.unchecked: self.unchecked = True self.active = False def update_checkbox(self, event_object): if event_object.type == pg.MOUSEBUTTONDOWN: self.click = True # self._mouse_down() if event_object.type == pg.MOUSEBUTTONUP: self._mouse_up() if event_object.type == pg.MOUSEMOTION: self._update(event_object) def is_checked(self): if self.checked is True: return True else: return False def is_unchecked(self): if self.checked is False: return True else: return False </code></pre> <p>A few <strong>caveats</strong> though. There are still some bugs to be worked out in the code, one of which is that you can un-check the checkbox without hovering over it. And at the moment they don't function like radio buttons. And one more thing. I coded all of this in python 3.5. sorry</p> <p>That being said, You're very much welcome to use the code to began to build your own radio buttons. Just make sure you show me what you come up with ;).</p> <p>Here is an example of how to use the module:</p> <pre><code>import checkbox import pygame as pg def main(): WIDTH = 800 HEIGHT = 600 display = pg.display.set_mode((WIDTH, HEIGHT)) chkbox = checkbox.Checkbox(display, 400, 400) running = True while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False pg.quit() quit() chkbox.update_checkbox(event) display.fill((200, 200, 200)) chkbox.render_checkbox() pg.display.flip() if __name__ == '__main__': main() </code></pre> <p>~Mr.Python</p>
0
2016-07-28T01:38:06Z
[ "python", "python-2.7", "pygame" ]
Django Signal on relation update
38,551,253
<p>I have similar models:</p> <pre><code>class Basket(model.Models): pass class Item(models.Model): basket = models.ForeignKey(Basket, related_name='items') </code></pre> <p>I want to catch <code>Basket.items</code> update with Django Signal, but from Basket side, due to call signal once when multiple items added. </p> <p>How can I catch <code>basket.items</code> relation update with a signal? </p> <p>THX</p>
0
2016-07-24T10:53:51Z
38,552,001
<p>You can easily get the item object in your basket using <code>post_signal</code></p> <pre><code>class Basket(model.Models): pass @classmethod def item_added(self, **kargs): print karts['instance'] class Item(models.Model): basket = models.ForeignKey(Basket, related_name='items') post_save.connect(Basket.item_added, sender=Item) </code></pre>
0
2016-07-24T12:25:39Z
[ "python", "django", "django-signals" ]
import my local module in python3 so it can i installed in the system via pip
38,551,276
<p>I have a directory structure as:</p> <pre><code> tree . ├── bin │   └── mkbib.py ├── LICENSE ├── mkbib │   ├── __init__.py #empty file │   ├── menubar.ui #a xml file. where should I place it? │   ├── menu.py │   ├── pybib.py │   └── view.py ├── mkbib.desktop.in #should be copied to /usr/local/applications ├── README └── setup.py </code></pre> <p>with <code>bin/mkbib.py</code> is the main file, which imports the files in <code>mkbib/</code>. And in <code>bin/mkbib.py</code>, I use:</p> <pre><code>import mkbib.menu as menu import mkbib.view as view # import view # import pybib </code></pre> <p>If all files are in same directory, last two lines are enough. I separated them as per the accepted answer <a href="http://stackoverflow.com/questions/16742203/create-a-python-executable-using-setuptools">here</a>.</p> <p>But, now, when I am trying to run the code, I am getting error:</p> <pre><code> File "mkbib.py", line 26, in __init__ self.TreeView = view.treeview() NameError: name 'view' is not defined </code></pre> <p>My ultimate goal is to install the <code>mkbib</code> app in the <code>/bin/</code>, same as the question I have linked, but I don't have any success.</p> <p>My <code>setup.py</code> is :</p> <pre><code>from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README'), encoding='utf-8') as f: long_description = f.read() setup( name='mkbib', version='0.1', description='BibTeX Creator', url='https://github.com/rudrab/mkbib', author='Rudra Banerjee', author_email='bnrj.rudra@gmail.com', license='GPLv3', packages=['mkbib'], package_dir={'mkbib': 'mkbib'}, scripts=['bin/mkbib.py'] ) </code></pre> <p>When I run <code>setup.py</code>, I get;</p> <pre><code> sudo python3 setup.py develop running develop running egg_info writing top-level names to mkbib.egg-info/top_level.txt writing mkbib.egg-info/PKG-INFO writing dependency_links to mkbib.egg-info/dependency_links.txt reading manifest file 'mkbib.egg-info/SOURCES.txt' writing manifest file 'mkbib.egg-info/SOURCES.txt' running build_ext Creating /usr/lib/python3.5/site-packages/mkbib.egg-link (link to .) mkbib 0.1 is already the active version in easy-install.pth Installing mkbib.py script to /usr/bin Installed /home/rudra/Devel/mkbib/Mkbib Processing dependencies for mkbib==0.1 Finished processing dependencies for mkbib==0.1 </code></pre> <p>I have also tried exporting pythonpath to the <code>mkbib</code>:</p> <pre><code>echo $PYTHONPATH ~/Devel/mkbib/Mkbib/mkbib </code></pre> <p>As I said, if all the files are in same directory, its working flawless.</p> <p><strong>The <code>mkbib.py</code>'s structure is(as asked by GeckStar)</strong>:</p> <pre><code>#!/usr/bin/python3 import gi import sys # import mkbib import mkbib.menu as menu import mkbib.view as view # import view # import pybib import urllib.parse as lurl import webbrowser import os from gi.repository import Gtk, Gio # , GLib, Gdk gi.require_version("Gtk", "3.0") class Window(Gtk.ApplicationWindow): def __init__(self, application, giofile=None): Gtk.ApplicationWindow.__init__(self, application=application, default_width=1000, default_height=200, title="mkbib") self.TreeView = view.treeview() self.MenuElem = menu.MenuManager() self.Parser = pybib.parser() self.name = "" ......... class mkbib(Gtk.Application): def __init__(self): Gtk.Application.__init__(self) self.connect("startup", self.startup) self.connect("activate", self.activate) .......... def install_excepthook(): """ Make sure we exit when an unhandled exception occurs. """ old_hook = sys.excepthook def new_hook(etype, evalue, etb): old_hook(etype, evalue, etb) while Gtk.main_level(): Gtk.main_quit() sys.exit() sys.excepthook = new_hook if __name__ == "__main__": app = mkbib() r = app.run(sys.argv) sys.exit(r) </code></pre> <p>Kindly help.</p>
0
2016-07-24T10:56:30Z
38,551,927
<p>This is one of Python's quirks: setting up paths to modules and packages. In your case, after you install the <code>mkbib</code> package <code>bin/mkbib.py</code> should simply have:</p> <pre><code>import mkbib </code></pre> <p>without any changes to <code>PYTHONPATH</code>. This is because <code>bin/mkbib.py</code> is designed to be used as a binary and assumes that <code>mkbib</code> package is already on the default <code>PYTHONPATH</code>. You can test whether <code>mkbib</code> is on the unmodified <code>PYTHONPATH</code> by running:</p> <pre><code>$ python -c 'import mkbib' </code></pre> <p>which should do nothing.</p> <p>Python takes as reference the current directory <code>.</code> in resolving relative paths, which is why your setup works when all files are in one folder.</p>
0
2016-07-24T12:17:11Z
[ "python", "python-3.x", "setuptools", "setup.py" ]
Returning value from thread in python without blocking main thread
38,551,298
<p>I have got an XMLRPC server and client runs some functions on server and gets returned value. If the function executes quickly then everything is fine but I have got a function that reads from file and returns some value to user. Reading takes about minute(there is some complicated stuff) and when one client runs this function on the server then server is not able to respond for other users until the function is done.</p> <p>I would like to create new thread that will read this file and return value for user. Is it possible somehow?</p> <p>Are there any good solutions/patters to do not block server when one client run some long function?</p>
0
2016-07-24T10:58:55Z
38,553,796
<p>Yes, using the <code>threading</code> module you can spawn new threads. See the <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">documentation</a>. An example would be this:</p> <pre><code>import threading import time def main(): print("main: 1") thread = threading.Thread(target=threaded_function) thread.start() time.sleep(1) print("main: 3") time.sleep(6) print("main: 5") def threaded_function(): print("thread: 2") time.sleep(4) print("thread: 4") main() </code></pre> <p>This code uses <code>time.sleep</code> to simulate that an action takes a certain amount of time. The output should look like this:</p> <pre><code>main: 1 thread: 2 main: 3 thread: 4 main: 5 </code></pre>
-1
2016-07-24T15:40:18Z
[ "python", "multithreading", "server", "xml-rpc" ]
Running Python code from an IDLE editor window
38,551,393
<p>I've programmed a bit in Python for the last few days and everything has worked fine up until yesterday. Whenever I try to run a script now the shell only responds with the message RESTART and a path to where my script is stored. Here's an image:</p> <p><a href="http://i.stack.imgur.com/H4t9U.png" rel="nofollow"><img src="http://i.stack.imgur.com/H4t9U.png" alt="image"></a></p> <p>I don't know how to fix this and can't find any solutions to it. When I'm writing the code directly into the shell everything works fine but this error only appears when I try to run a script from another file. </p> <p>Thanks in advance</p>
1
2016-07-24T11:11:19Z
38,551,658
<p>That's because your <code>testprog.py</code> doesn't actually output anything. Try changing it to <code>print(5 + 5)</code> or something similar, currently it only computes <code>5+5</code> and then it exits.</p>
-1
2016-07-24T11:47:07Z
[ "python", "python-idle" ]
Running Python code from an IDLE editor window
38,551,393
<p>I've programmed a bit in Python for the last few days and everything has worked fine up until yesterday. Whenever I try to run a script now the shell only responds with the message RESTART and a path to where my script is stored. Here's an image:</p> <p><a href="http://i.stack.imgur.com/H4t9U.png" rel="nofollow"><img src="http://i.stack.imgur.com/H4t9U.png" alt="image"></a></p> <p>I don't know how to fix this and can't find any solutions to it. When I'm writing the code directly into the shell everything works fine but this error only appears when I try to run a script from another file. </p> <p>Thanks in advance</p>
1
2016-07-24T11:11:19Z
38,555,821
<p>Except for the RESTART line, the behavior you see has nothing to do with IDLE. Run any program (without IDLE) that does not print anything with the '-i' option and you will see the same thing -- a '>>> ' prompt.</p> <pre><code>C:\Users\Terry&gt;type testprog.py 5+5 C:\Users\Terry&gt;python -i testprog.py &gt;&gt;&gt; quit() C:\Users\Terry&gt; </code></pre> <p>IDLE runs a editor window code the same as if it were run in a console (Command Prompt on Windows) with 'python -i'.</p>
0
2016-07-24T19:17:59Z
[ "python", "python-idle" ]
Selenium Python Script throws no element error exception even though the x path is right?
38,551,400
<pre><code>from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys driver=webdriver.Chrome() driver.get("https://paytm.com/") driver.maximize_window() driver.find_element_by_class_name("login").click() driver.implicitly_wait(10) driver.find_element_by_xpath("//md-input-container[@class='md-default-theme md-input-invalid']/input[@id='input_0']").send_keys("99991221212") </code></pre> <p>In the above code, I have verified the xpath using fire bug its highlighting the correct element. But when the script run its failing? Can you help me folks?</p>
2
2016-07-24T11:12:07Z
38,551,604
<p>You should try using <code>WebDriverWait</code> to wait until <code>input</code> element visible on the page as below :-</p> <pre><code>from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("https://paytm.com/") driver.maximize_window() wait = WebDriverWait(driver, 10) wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "login"))).click() #now switch to iframe first wait.until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe"))) input = wait.until(EC.visibility_of_element_located((By.ID, "input_0"))) input.send_keys("99991221212") </code></pre> <p>Hope it helps...:)</p>
0
2016-07-24T11:39:12Z
[ "python", "python-2.7", "selenium", "selenium-webdriver", "selenium-chromedriver" ]
Selenium Python Script throws no element error exception even though the x path is right?
38,551,400
<pre><code>from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys driver=webdriver.Chrome() driver.get("https://paytm.com/") driver.maximize_window() driver.find_element_by_class_name("login").click() driver.implicitly_wait(10) driver.find_element_by_xpath("//md-input-container[@class='md-default-theme md-input-invalid']/input[@id='input_0']").send_keys("99991221212") </code></pre> <p>In the above code, I have verified the xpath using fire bug its highlighting the correct element. But when the script run its failing? Can you help me folks?</p>
2
2016-07-24T11:12:07Z
38,551,909
<p>In selenium each frame is treated individually. Since the login is in a separate <code>iframe</code> element, you need to switch to it first using:</p> <pre><code>iframe = driver.find_elements_by_tag_name('iframe')[0] driver.switch_to_frame(iframe) </code></pre> <p><strong>Before</strong> trying to interact with it's elements.</p> <p>Or in this case, you would wait for the frame to exist, and it would be:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("https://paytm.com/") driver.maximize_window() wait = WebDriverWait(driver, 10) wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "login"))).click() wait.until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe"))) _input = wait.until(EC.visibility_of_element_located((By.ID,"input_0"))) _input.send_keys("99991221212") </code></pre>
3
2016-07-24T12:15:38Z
[ "python", "python-2.7", "selenium", "selenium-webdriver", "selenium-chromedriver" ]
Can a user access data from a context_dict?
38,551,432
<p>My <code>models.py</code>:</p> <pre><code>class Mymodel(models.Model): title = models.CharField(max_length=32) other_useful_field = models.CharField(max_length=32) ... secret_field = models.CharField(max_length=32) </code></pre> <p>My <code>views.py</code>:</p> <pre><code>def myview(request): context_dict=[] context=Mymodel.objects.get(id=1) context_dict=['reserved_data'] = context return render(request, 'mytemplate.html', context_dict) </code></pre> <p>My <code>mytemplate.html</code>:</p> <pre><code>{% extends 'base.html' %} {% load staticfiles %} {% block title %}{{ reserved_data.title }}{% endblock %} {% block content %}Hello world{% endblock %} </code></pre> <p>Is there a (simple*) method for a user to read all 'reserved_data'?</p> <p>Can a user have access to secret_field?</p> <p>I don't want that to happen.</p> <p>*simple, I mean a good hacker eventually can have access to all data anyway...</p>
0
2016-07-24T11:15:48Z
38,551,806
<p>The template is rendered on the server and output as HTML for the user to see. The user never sees the raw template. As long as your server is secure you have nothing to worry about.</p>
1
2016-07-24T12:04:58Z
[ "python", "django-templates" ]
i can not get the body element of html page in web scrapping by python
38,551,466
<p>I would like to parse a website with urllib python library. I wrote this:</p> <pre><code>from bs4 import BeautifulSoup from urllib.request import HTTPCookieProcessor, build_opener from http.cookiejar import FileCookieJar def makeSoup(url): jar = FileCookieJar("cookies") opener = build_opener(HTTPCookieProcessor(jar)) html = opener.open(url).read() return BeautifulSoup(html, "lxml") def articlePage(url): return makeSoup(url) Links = "http://collegeprozheh.ir/%d9%85%d9%82%d8%a7%d9%84%d9%87- %d9%85%d8%af%d9%84-%d8%b1%d9%82%d8%a7%d8%a8%d8%aa%db%8c-%d8%af%d8%b1-%d8%b5%d9%86%d8%b9%d8%aa-%d9%be%d9%86%d9%84-%d9%87%d8%a7%db%8c-%d8%ae%d9%88%d8%b1%d8%b4%db%8c%d8%af/" print(articlePage(Links)) </code></pre> <p>but the website does not return content of body tag. this is result of my program:</p> <pre><code>cURL = window.location.href; var p = new Date(); second = p.getTime(); GetVars = getUrlVars(); setCookie("Human" , "15421469358743" , 10); check_coockie = getCookie("Human"); if (check_coockie != "15421469358743") document.write("Could not Set cookie!"); else window.location.reload(true); &lt;/script&gt; &lt;/head&gt;&lt;body&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p>i think the cookie has caused this problem.</p>
0
2016-07-24T11:19:43Z
38,551,530
<p>The page is using JavaScript to check the cookie and to generate the content. However, <code>urllib</code> does not process JavaScript and thus the page shows nothing. </p> <p>You'll either need to use something like <a href="http://selenium-python.readthedocs.io" rel="nofollow">Selenium</a> that acts as a browser and executes JavaScript, or you'll need to set the cookie yourself before you request the page (from what I can see, that's all the JavaScript code does). You seem to be loading a file containing cookie definitions (using <code>FileCookieJar</code>), however you haven't included the content.</p>
0
2016-07-24T11:28:02Z
[ "python", "cookies", "web" ]
Error with pip install MySQLdb library
38,551,513
<p>In python 2.7.10, Windows OS. Could not find a version that satisfies the requirement mysqldb(from version) no matching distribution found for mysqldb</p> <p><strong>pip install MySQL-python also failed:</strong> Unable to find vcvarsall.bat and many other errors if I am patching solution for this one. </p>
1
2016-07-24T11:25:20Z
38,551,703
<p>Building Python libraries on Windows can be challenging.</p> <p>This message <a href="https://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat">indicates that the Visual C++ compiler cannot be found</a>:</p> <blockquote> <p>Unable to find vcvarsall.bat</p> </blockquote> <p>You could install <a href="https://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx" rel="nofollow">Visual Studio Express</a> and try again, or use another compiler as suggested in the referenced question. But you may find that this leads to further problems, e.g. now the MySQL headers can't be found.</p> <p>Manually installing MySQL from source will likely fix that issue, but that might reveal its own dependency problems.</p> <p>Instead of going through this rigmarole you might consider installing <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">precompiled versions from Christoph Gohlke</a>.</p>
1
2016-07-24T11:52:47Z
[ "python", "python-2.7", "mysql-python" ]
Seperate RSS feed link/s
38,551,570
<p>I am using the feedparser module to create a news feed in my program.</p> <p>The Yahoo! Finance API link element actually has two links: the Yahoo link, and the actual article link (external site/source). The two are separated by an asterisks, with the following being an example:</p> <p>'<a href="http://us.rd.yahoo.com/finance/external/investors/rss/SIG=12shc077a/" rel="nofollow">http://us.rd.yahoo.com/finance/external/investors/rss/SIG=12shc077a/</a>*<a href="http://www.investors.com/news/technology/click/pokemon-go-hurting-facebook-snapchat-usage/" rel="nofollow">http://www.investors.com/news/technology/click/pokemon-go-hurting-facebook-snapchat-usage/</a>'</p> <p>Note the asterisk between the two items.</p> <p>I was just wondering if there is a pythonic way to separate these two, and only read the second link to a file.</p> <p>Thank you for your time.</p> <p>Here is my relevant code:</p> <pre><code>def parse_feed(news_feed_message, rss_url): ''' This function parses the Yahoo! RSS API for data of the latest five articles, and writes it to the company news text file''' # Define the RSS feed to parse from, as the url passed in of the company the user chose feed = feedparser.parse(rss_url) # Define the file to write the news data to the company news text file outFile = open('C:\\Users\\nicks_000\\PycharmProjects\\untitled\\SAT\\GUI\\Text Files\\companyNews.txt', mode='w') # Create a list to store the news data parsed from the Yahoo! RSS news_data_write = [] # Initialise a count count = 0 # For the number of articles to append to the file, append the article's title, link, and published date to the news_elements list for count in range(10): news_data_write.append(feed['entries'][count].title) news_data_write.append(feed['entries'][count].published) news_data_write.append(feed['entries'][count].link) # Add one to the count, so that the next article is parsed count+=1 # For each item in the news_elements list, convert it to a string and write it to the company news text file for item in news_data_write: item = str(item) outFile.write(item+'\n') # For each article, write a new line to the company news text file, so that each article's data is on its own line outFile.write('\n') # Clear the news_elements list so that data is not written to the file more than once del(news_data_write[:]) outFile.close() read_news_file(news_feed_message) </code></pre>
0
2016-07-24T11:34:23Z
38,551,640
<p>You can split this the following way:</p> <pre><code>link = 'http://us.rd.yahoo.com/finance/external/investors/rss/SIG=12shc077a/*http://www.investors.com/news/technology/click/pokemon-go-hurting-facebook-snapchat-usage/' rss_link, article_link = link.split('*') </code></pre> <p>Keep in mind that this requires the link to always contain the asterisk, otherwise you'll get the following exception:</p> <pre><code>ValueError: not enough values to unpack (expected 2, got 1) </code></pre> <p>If you only need the second link, you could also write:</p> <pre><code>_, article_link = link.split('*') </code></pre> <p>This indicates that you want to discard the first return value. Another alternative is:</p> <pre><code>article_link = link.split('*')[1] </code></pre> <p>Regarding your code: if you have an exception anywhere after you've opened your output file, it won't be closed properly. Either use the <code>open</code> context manager (<a href="https://docs.python.org/3.5/library/functions.html#open" rel="nofollow">docs</a>) or a <code>try ... finally</code> block (<a href="https://docs.python.org/3.5/reference/compound_stmts.html#try" rel="nofollow">docs</a>) to make sure you close your file whatever happens.</p> <p>Context manager:</p> <pre><code>with open('youroutputfile', 'w') as f: # your code f.write(…) </code></pre> <p>Exception handler:</p> <pre><code>try: f = open('youroutputfile', 'w') f.write(…) finally: f.close() </code></pre>
0
2016-07-24T11:44:10Z
[ "python", "python-3.x", "rss", "feedparser" ]
How to avoid repeating "from . import class_name" when "." is actually referring to an invalid identifier?
38,551,694
<p>Say I have the very simple folder architecture below when working with a PyCharm project:</p> <pre class="lang-none prettyprint-override"><code>- 1 - Something - scripta.py - scriptb.py - dummyclass.py </code></pre> <p>Since <code>1 - Something</code> is an invalid identifier I have to use something like below in <code>scripta.py</code> and <code>scriptb.py</code> in order to be able to import DummyClass defined in <code>dummyclass.py</code>:</p> <pre><code>from .dummyclass import DummyClass </code></pre> <p>Is there any way to avoid that since both scripts and the class definition are within the same package without changing this invalid identifier?</p> <p>I thought creating an <code>__init__.py</code> and putting the <code>import</code> there would help but it actually does not...</p> <p>Any thoughts?</p>
0
2016-07-24T11:51:15Z
38,551,829
<p>I'm not sure why the directory can't be renamed - if it's someone else's codebase it's just as invalid for them as it is for you. But assuming you can't, one solution is to put that directory directly on the Python path; either from outside Python by adding it to the PYTHONPATH environment variable, or from inside by adding it to <code>sys.path</code>. After that you can just import the module directly.</p>
1
2016-07-24T12:07:43Z
[ "python", "python-3.x", "module", "package" ]
How to do time diff in each group on Pandas in Python
38,551,749
<p>Here's the phony data:</p> <pre><code>df = pd.DataFrame({'email': ['u1','u1','u1','u2','u2','u2'], 'timestamp': [3, 1, 5, 11, 15, 9]}) </code></pre> <p>What I intend to retrieve is the time diff in each group of email. Thus, after sorting by timestamp in each group, the data should be:</p> <pre><code>u1 5 u1 3 u1 1 u2 15 u2 11 u2 9 </code></pre> <p>the result should be:</p> <pre><code>u1 2 # 5-3 u1 2 # 3-1 u2 4 # 15-11 u2 2 # 11-9 </code></pre> <p>Could anyone tell me what I should do next? Great thanks.</p>
0
2016-07-24T11:58:28Z
38,551,811
<pre><code>df = pd.DataFrame({'email': ['u1','u1','u1','u2','u2','u2'], 'timestamp': [3, 1, 5, 11, 15, 9]}) (df.sort_values(['email', 'timestamp'], ascending=[True, False]) .groupby('email')['timestamp'] .diff(-1) .dropna()) Out: 2 2.0 0 2.0 4 4.0 3 2.0 Name: timestamp, dtype: float64 </code></pre> <p>To keep the email column:</p> <pre><code>df.sort_values(['email', 'timestamp'], ascending=[True, False], inplace=True) df.assign(diff=df.groupby('email')['timestamp'].diff(-1)).dropna() Out: email timestamp diff 2 u1 5 2.0 0 u1 3 2.0 4 u2 15 4.0 3 u2 11 2.0 </code></pre> <p>If you don't want the timestamp column you can add <code>.drop('timestamp', axis=1)</code> at the end.</p>
3
2016-07-24T12:05:21Z
[ "python", "pandas", "group-by" ]
How to access 1 cell in a DataFrame that has a Float64 as index? (Python3)
38,551,769
<p>Newbie here, I have csv file with rows that I want to index by a UNIQUE float</p> <pre><code>"GOOGL @ 759.28" "August 19 2016 Calls","","","","","","","","","","August 19 2016 Puts" ,"IV","Delta","Open Int","Vol","Change","Last","Bid","Ask","Strike","Bid","Ask","Last","Change","Vol","Open Int","Delta","IV" ,"85.67","0.971","1","0","0.00","233.45","257.30","261.60","500.00","0.00","3.60","0.05","0.00","0","2","-0.025","83.12" ,"83.91","0.971","0","0","0.00","0.00","252.20","256.60","505.00","0.00","0.50","0.00","0.00","0","0","-0.006","61.19" ,"82.16","0.970","0","0","0.00","0.00","247.30","251.60","510.00","0.00","4.00","0.81","0.00","0","1","-0.028","81.24" ,"46.25","0.999","0","0","0.00","0.00","242.30","246.70","515.00","0.00","0.55","0.00","0.00","0","0","-0.007","59.20" ,"44.85","0.999","0","0","0.00","0.00","237.40","241.60","520.00","0.05","0.60","0.13","0.00","0","11","-0.008","59.08" ,"43.47","0.999","0","0","0.00","0.00","232.40","236.60","525.00","0.00","0.60","0.00","0.00","0","0","-0.007","57.16" ,"42.08","0.999","0","0","0.00","0.00","227.40","231.60","530.00","0.00","0.65","0.10","0.00","0","18","-0.008","56.41" </code></pre> <p>My code:</p> <pre><code>#! /usr/local/bin/python import numpy as np import pandas as pd import locale locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) def read_csv_file(pathToFile="options.csv"): return pd.read_csv(pathToFile, header=2, dtype={"Strike":np.float}, index_col="Strike", usecols=["Strike","Bid","Ask","Bid.1","Ask.1"], thousands=',').reset_index() def list_record_with_strike(strike, df): for index, longCall in df.iterrows(): if strike == np.float(longCall['Strike']) : print("Ask Price of strike: ", longCall['Strike'], "is ",longCall['Ask']) def get_record_by_strike(strike, df ): print(df[strike]) def main(): # data frame df = read_csv_file() list_record_with_strike(510,df) get_record_by_strike(510,df) if __name__ == '__main__': main() </code></pre> <p>I get this output:</p> <pre><code>&gt; Ask Price of strike: 510.0 is 251.6 Traceback (most recent call &gt; last): File "spikes/OptionsReader.py", line 32, in &lt;module&gt; &gt; main() File "spikes/OptionsReader.py", line 29, in main &gt; get_record_by_strike(510,df) File "spikes/OptionsReader.py", line 23, in get_record_by_strike &gt; print(df[strike]) File "//anaconda/lib/python3.5/site-packages/pandas/core/frame.py", line &gt; 1969, in __getitem__ &gt; return self._getitem_column(key) File "//anaconda/lib/python3.5/site-packages/pandas/core/frame.py", line &gt; 1976, in _getitem_column &gt; return self._get_item_cache(key) File "//anaconda/lib/python3.5/site-packages/pandas/core/generic.py", line &gt; 1091, in _get_item_cache &gt; values = self._data.get(item) File "//anaconda/lib/python3.5/site-packages/pandas/core/internals.py", &gt; line 3211, in get &gt; loc = self.items.get_loc(item) File "//anaconda/lib/python3.5/site-packages/pandas/core/index.py", line &gt; 1759, in get_loc &gt; return self._engine.get_loc(key) File "pandas/index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas/index.c:3979) File &gt; "pandas/index.pyx", line 157, in pandas.index.IndexEngine.get_loc &gt; (pandas/index.c:3843) File "pandas/hashtable.pyx", line 668, in &gt; pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12265) &gt; File "pandas/hashtable.pyx", line 676, in &gt; pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12216) &gt; KeyError: 510 </code></pre> <p>Now, I know that I can get one series because of the list_record_with_strike correctly locates it. (but I goes through the full thing) but for some reason (I think trivial, but unknown to me) I cannot get the record directly by its index...</p>
0
2016-07-24T12:01:03Z
38,553,319
<p>Try this:</p> <pre><code>import numpy as np import pandas as pd def read_csv_file(pathToFile="options.csv"): return pd.read_csv(pathToFile, header=2, dtype={"Strike":np.float}, index_col="Strike", usecols=["Strike","Bid","Ask","Bid.1","Ask.1"], thousands=',').reset_index() def list_record_with_strike(strike, df): for i, (index, longCall) in enumerate(df.iterrows()): if strike == np.float(longCall['Strike']) : print("Ask Price of strike: ", longCall['Strike'], "is ",longCall['Ask']) return i def get_record_by_strike(strike, df ): print(df.loc[[strike]]) def main(): # data frame df = read_csv_file() i = list_record_with_strike(510, df) get_record_by_strike(i, df) if __name__ == '__main__': main() </code></pre>
0
2016-07-24T14:49:02Z
[ "python", "pandas", "dataframe" ]
How to access 1 cell in a DataFrame that has a Float64 as index? (Python3)
38,551,769
<p>Newbie here, I have csv file with rows that I want to index by a UNIQUE float</p> <pre><code>"GOOGL @ 759.28" "August 19 2016 Calls","","","","","","","","","","August 19 2016 Puts" ,"IV","Delta","Open Int","Vol","Change","Last","Bid","Ask","Strike","Bid","Ask","Last","Change","Vol","Open Int","Delta","IV" ,"85.67","0.971","1","0","0.00","233.45","257.30","261.60","500.00","0.00","3.60","0.05","0.00","0","2","-0.025","83.12" ,"83.91","0.971","0","0","0.00","0.00","252.20","256.60","505.00","0.00","0.50","0.00","0.00","0","0","-0.006","61.19" ,"82.16","0.970","0","0","0.00","0.00","247.30","251.60","510.00","0.00","4.00","0.81","0.00","0","1","-0.028","81.24" ,"46.25","0.999","0","0","0.00","0.00","242.30","246.70","515.00","0.00","0.55","0.00","0.00","0","0","-0.007","59.20" ,"44.85","0.999","0","0","0.00","0.00","237.40","241.60","520.00","0.05","0.60","0.13","0.00","0","11","-0.008","59.08" ,"43.47","0.999","0","0","0.00","0.00","232.40","236.60","525.00","0.00","0.60","0.00","0.00","0","0","-0.007","57.16" ,"42.08","0.999","0","0","0.00","0.00","227.40","231.60","530.00","0.00","0.65","0.10","0.00","0","18","-0.008","56.41" </code></pre> <p>My code:</p> <pre><code>#! /usr/local/bin/python import numpy as np import pandas as pd import locale locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) def read_csv_file(pathToFile="options.csv"): return pd.read_csv(pathToFile, header=2, dtype={"Strike":np.float}, index_col="Strike", usecols=["Strike","Bid","Ask","Bid.1","Ask.1"], thousands=',').reset_index() def list_record_with_strike(strike, df): for index, longCall in df.iterrows(): if strike == np.float(longCall['Strike']) : print("Ask Price of strike: ", longCall['Strike'], "is ",longCall['Ask']) def get_record_by_strike(strike, df ): print(df[strike]) def main(): # data frame df = read_csv_file() list_record_with_strike(510,df) get_record_by_strike(510,df) if __name__ == '__main__': main() </code></pre> <p>I get this output:</p> <pre><code>&gt; Ask Price of strike: 510.0 is 251.6 Traceback (most recent call &gt; last): File "spikes/OptionsReader.py", line 32, in &lt;module&gt; &gt; main() File "spikes/OptionsReader.py", line 29, in main &gt; get_record_by_strike(510,df) File "spikes/OptionsReader.py", line 23, in get_record_by_strike &gt; print(df[strike]) File "//anaconda/lib/python3.5/site-packages/pandas/core/frame.py", line &gt; 1969, in __getitem__ &gt; return self._getitem_column(key) File "//anaconda/lib/python3.5/site-packages/pandas/core/frame.py", line &gt; 1976, in _getitem_column &gt; return self._get_item_cache(key) File "//anaconda/lib/python3.5/site-packages/pandas/core/generic.py", line &gt; 1091, in _get_item_cache &gt; values = self._data.get(item) File "//anaconda/lib/python3.5/site-packages/pandas/core/internals.py", &gt; line 3211, in get &gt; loc = self.items.get_loc(item) File "//anaconda/lib/python3.5/site-packages/pandas/core/index.py", line &gt; 1759, in get_loc &gt; return self._engine.get_loc(key) File "pandas/index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas/index.c:3979) File &gt; "pandas/index.pyx", line 157, in pandas.index.IndexEngine.get_loc &gt; (pandas/index.c:3843) File "pandas/hashtable.pyx", line 668, in &gt; pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12265) &gt; File "pandas/hashtable.pyx", line 676, in &gt; pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12216) &gt; KeyError: 510 </code></pre> <p>Now, I know that I can get one series because of the list_record_with_strike correctly locates it. (but I goes through the full thing) but for some reason (I think trivial, but unknown to me) I cannot get the record directly by its index...</p>
0
2016-07-24T12:01:03Z
38,556,643
<p>Ok, I "RTFM" (<a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/10min.html</a>) and noticed that I had to explicitly say that I want to compare the value in the Column 'Strike' and that will give me the series.</p> <p>Here is my new code:</p> <pre><code>#! /usr/local/bin/python import numpy as np import pandas as pd import locale locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) def read_csv_file(pathToFile="options.csv"): return pd.read_csv(pathToFile, header=2, dtype={"Strike":np.float}, index_col="Strike", usecols=["Strike","Bid","Ask","Bid.1","Ask.1"], thousands=',').reset_index() def list_record_with_strike(strike, df): for index, longCall in df.iterrows(): if strike == np.float(longCall['Strike']) : print("Ask Price of strike: ", longCall['Strike'], "is ", longCall['Ask']) def get_record_by_strike(strike, df ): series = df[df.Strike == strike] print("Ask price for strike: ", series.iat[0,0], " is " , series.iat[0,2]) def main(): # data frame df = read_csv_file() get_record_by_strike(510.0,df) if __name__ == '__main__': main() </code></pre> <p>Observe that I get a Series by doing df[df.Strike == strike] which returns the full row with the data I want. Then, I use iat[x,y] with x always = 0, and get the values of the specific column.</p> <p>Please post if there is a more pythonic/pandonic way to do this.</p>
0
2016-07-24T20:50:07Z
[ "python", "pandas", "dataframe" ]
How do I put variable in a list slicing operation?
38,551,817
<p>I have a list in a function, and I want to sometimes use the whole thing, sometimes just a section depending on an offset variable. Sometimes I want to apply the offset to the start, sometimes the end.</p> <p>I know </p> <pre><code>my_list = my_list[:] </code></pre> <p>will give me just the same list, and </p> <pre><code>start= None end = None my_list[start:end] </code></pre> <p>seems to do the same thing.</p> <p>But the trouble is that sometimes I want to increment the parameter but I can't add 1 to None. (The start seems less of a problem as I can initialize it to 0.)</p> <p>I would like to have something like:</p> <pre><code> my_list[start: end + offset] </code></pre> <p>And sometimes I even want a constant stuck in there too, such as </p> <pre><code>my_list[start: end -1 + offset] </code></pre> <p>I am pretty tired as I write this so apologies if this is easy.</p> <p><strong><em>Edit - my final solution....</em></strong></p> <p>I followed the idea of using the length in the end parameter (as described in the solution) combined with the idea of changing my offset variable into two variables. Details are below...</p> <p>The whole idea was that I had a function that compares elements in two lists. The offset is zero by default and so the first element in one is compared with the first element of the other. Then I wanted to have an offset so the first element in one is compared with the second element of the other (or third, etc)</p> <p>Because I wanted the offset to be used differently in different places, I found I had to process the offset into two variables beforehand...</p> <pre><code>if offset &lt; 0: neg_offset = abs(offset) if offset &gt; 0: pos_offset = offset </code></pre> <p>And then I put the two lists in my function like this: When the lists are the same length...</p> <pre><code>get_list_comparison(my_first_list[pos_offset: len(my_first_list)-neg_offset], my_second_list[neg_offset: len(my_second_list)-pos_offset]) </code></pre> <p>When the second list is shorter than the first list:</p> <pre><code>get_list_comparison(my_first_list[pos_offset:len(my_first_list)-1-neg_offset], my_second_list[neg_offset: len(my_second_list)-pos_offset]) </code></pre> <p>When the lists are uneven, I suppose I could have worked out the difference computationally rather than hardcoding the -1 (or -2 etc) but this was good enough to work for me.</p>
3
2016-07-24T12:06:19Z
38,551,874
<p>Python supports negative offsets to specify distance from the end of the list (-1 is the last character), so if you have something like:</p> <pre><code>s = "Hello world!" print(s[:-6]) </code></pre> <p>It will print <code>Hello</code>.</p> <p>You can also do:</p> <pre><code>s = "Hello world!" print(s[-5:]) </code></pre> <p>And it will print <code>world</code>.</p>
0
2016-07-24T12:12:16Z
[ "python", "list", "slice" ]
How do I put variable in a list slicing operation?
38,551,817
<p>I have a list in a function, and I want to sometimes use the whole thing, sometimes just a section depending on an offset variable. Sometimes I want to apply the offset to the start, sometimes the end.</p> <p>I know </p> <pre><code>my_list = my_list[:] </code></pre> <p>will give me just the same list, and </p> <pre><code>start= None end = None my_list[start:end] </code></pre> <p>seems to do the same thing.</p> <p>But the trouble is that sometimes I want to increment the parameter but I can't add 1 to None. (The start seems less of a problem as I can initialize it to 0.)</p> <p>I would like to have something like:</p> <pre><code> my_list[start: end + offset] </code></pre> <p>And sometimes I even want a constant stuck in there too, such as </p> <pre><code>my_list[start: end -1 + offset] </code></pre> <p>I am pretty tired as I write this so apologies if this is easy.</p> <p><strong><em>Edit - my final solution....</em></strong></p> <p>I followed the idea of using the length in the end parameter (as described in the solution) combined with the idea of changing my offset variable into two variables. Details are below...</p> <p>The whole idea was that I had a function that compares elements in two lists. The offset is zero by default and so the first element in one is compared with the first element of the other. Then I wanted to have an offset so the first element in one is compared with the second element of the other (or third, etc)</p> <p>Because I wanted the offset to be used differently in different places, I found I had to process the offset into two variables beforehand...</p> <pre><code>if offset &lt; 0: neg_offset = abs(offset) if offset &gt; 0: pos_offset = offset </code></pre> <p>And then I put the two lists in my function like this: When the lists are the same length...</p> <pre><code>get_list_comparison(my_first_list[pos_offset: len(my_first_list)-neg_offset], my_second_list[neg_offset: len(my_second_list)-pos_offset]) </code></pre> <p>When the second list is shorter than the first list:</p> <pre><code>get_list_comparison(my_first_list[pos_offset:len(my_first_list)-1-neg_offset], my_second_list[neg_offset: len(my_second_list)-pos_offset]) </code></pre> <p>When the lists are uneven, I suppose I could have worked out the difference computationally rather than hardcoding the -1 (or -2 etc) but this was good enough to work for me.</p>
3
2016-07-24T12:06:19Z
38,551,884
<p>You can't sum None. However, you can sum to other numbers like 0 (start) and <code>len(my_list)</code> (End)</p> <pre><code>my_list = [1,2,3,4,5,7,8,9,10] print(my_list) my_list = my_list[:] print(my_list) start1 = None end1 = None my_list = my_list[start1:end1] print(my_list) ###################################### start2 = 0 end2 = len(my_list) my_list = my_list[start2:end2] print(my_list) my_list = my_list[start2 + 3:end2 - 3] print(my_list) </code></pre> <p><em>(First four outputs are just the same, to show the difference and how it works).</em></p> <p>That way you can change the parameters easily. Because <em>start</em> is just '0', and the same as 'None' but because of it's datatype you can increase and decrease it's value. and <em>end</em> is <code>len(my_list)</code> which returns an integer representing the length of your list, and thus, also the end. Because it's an integer, you can also increase/decrease that value.</p> <p>Another thing you can do is using negatives:</p> <pre><code>##################################### ###Using negatives start3 = -3 end3 = +3 my_list = my_list[start3:end3] print(my_list) </code></pre> <p>See? I kind of 'reversed' start end end, by making end positive, and start negative.</p> <p>Output of all code:</p> <pre><code>[1, 2, 3, 4, 5, 7, 8, 9, 10] [1, 2, 3, 4, 5, 7, 8, 9, 10] [1, 2, 3, 4, 5, 7, 8, 9, 10] [1, 2, 3, 4, 5, 7, 8, 9, 10] [4, 5, 7] [4, 5, 7] </code></pre>
1
2016-07-24T12:13:07Z
[ "python", "list", "slice" ]
Big data methods: Iterative (chunk-wise) computation of data moments
38,551,864
<p>I'm having data in the terabytes. Therefore, standard <code>pandas</code> and <code>numpy</code> procedures (<code>group-by</code>, <code>mean</code>, <code>histogram</code> etc.) will not work when I can't load in all the data at the same time. </p> <p>My data will come from <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.HDFStore.select.html" rel="nofollow"><code>pandas.HDFStore.select</code></a> which can return an iterator with chunks of variable chunk-size. </p> <p>Now all I need is methods on how to calculate moments of the data based on iterative approaches.</p> <p>The <strong>expected value</strong> is straight-forward:</p> <pre><code>n, mean = 0, 0 for chunk in iterator: nCurrent = len(chunk) meanCurrent = chunk['variable'].mean() mean = (n * mean + nCurrent * meanCurrent)/(n + nCurrent) n += nCurrent </code></pre> <p>However it's not clear what the general approach is. How would I do this for <strong>higher-order moments</strong>? </p> <p>Also, I am interested in plotting the distribution. Say I decide to go for a <strong>histogram</strong>. Without knowing the limits of the distribution at the beginning, it's hard to create the bins. Do I first need to iterate once through the whole distribution to get the min and max, and then create bins and start counting? Or is there a better approach?</p>
1
2016-07-24T12:11:10Z
38,551,929
<p>for the average (<code>mean</code>) it can be done like this:</p> <pre><code>i, cumsum = 0 for chunk in store.select('key', chunksize=N): cumsum += chunk['variable'].sum() i += len(chunk) my_mean = cumsum / i </code></pre> <p>As a <em>general</em> approach i would go for an Apache Spark on Hadoop Cluster if you have to work with terabytes of data</p>
0
2016-07-24T12:17:23Z
[ "python", "numpy", "pandas", "scipy", "hdf5" ]
Why is function not changing global variable even after specifying global
38,551,905
<p>I have recently started programming. Everything is working fine but this piece of code intriguing me from a long time. </p> <p>Here is my code.</p> <pre><code>addon = 20 startup = 50 + addon def click(): global addon, startup addon *= 2 print addon, startup click() click() click() click() click() click() click() click() click() click() </code></pre> <p>This is my output:-</p> <pre><code>40 70 80 70 160 70 320 70 640 70 1280 70 2560 70 5120 70 10240 70 20480 70 </code></pre> <p>This is what I expected:-</p> <pre><code>40 90 80 170 160 330 320 650 640 1290 1280 2570 2560 5130 5120 10250 10240 20490 20480 40970 </code></pre> <p>I am just not getting. if every call of <code>click</code> is updating global variable <code>addon</code> than it should also update <code>startup</code> variable. But don't know why it is not working. </p>
-2
2016-07-24T12:15:10Z
38,552,112
<p><code>startup</code> does not store an <em>expression</em>, it stores the <em>result</em> of an expression, <strong>once</strong>.</p> <p>In other words, the variable <code>startup</code> references the <em>result</em> of <code>50 + addon</code>, which at the time is the integer <code>70</code>.</p> <p>That <code>addon</code> later changes does not make a difference here, because <code>startup</code> does not reference <code>addon</code>.</p> <p>You'd have to make <code>startup</code> a <em>function</em> instead, and call that function each time if you wanted to re-calculate the expression:</p> <pre><code>startup = lambda: 50 + addon </code></pre> <p>I used a <a href="https://docs.python.org/2/reference/expressions.html#lambda" rel="nofollow"><code>lambda</code> expression</a> to create the function here; a <code>lambda</code> creates a function from a single expression.</p> <p>You then call <code>startup</code> each time you need to see the latest result:</p> <pre><code>def click(): global addon addon *= 2 print addon, startup() </code></pre>
1
2016-07-24T12:39:03Z
[ "python", "python-2.7", "global-variables" ]
Get country name from Country code in python?
38,551,958
<p>I have worked with 2 python libraries: <a href="https://pypi.python.org/pypi/phonenumbers" rel="nofollow">phonenumbers</a>, <a href="https://pypi.python.org/pypi/pycountry" rel="nofollow">pycountry</a>. I actually could not find a way to give just country code and get its corresponding country name.</p> <p>In <code>phonenumbers</code> you need to provide full numbers to <code>parse</code>. In <code>pycountry</code> it just get country ISO.</p> <p>Is there a solution or a method in any way to give the library country code and get country name?</p>
1
2016-07-24T12:20:39Z
38,552,310
<p>The <code>phonenumbers</code> library is rather under-documented; instead they advice you to look a the original Google project for unittests to learn about functionality.</p> <p>The <a href="https://github.com/googlei18n/libphonenumber/blob/master/java/libphonenumber/test/com/google/i18n/phonenumbers/PhoneNumberUtilTest.java" rel="nofollow"><code>PhoneNumberUtilTest</code> unittests</a> seems to cover your required functionality; mapping the country portion of a phone number to a given region, using the <a href="https://github.com/googlei18n/libphonenumber/blob/master/java/libphonenumber/test/com/google/i18n/phonenumbers/PhoneNumberUtilTest.java#L1226" rel="nofollow"><code>getRegionCodeForCountryCode()</code> function</a>. There is also a <a href="https://github.com/googlei18n/libphonenumber/blob/master/java/libphonenumber/test/com/google/i18n/phonenumbers/PhoneNumberUtilTest.java#L1234" rel="nofollow"><code>getRegionCodeForNumber()</code> function</a> that appears to extract the country code attribute of a parsed number first.</p> <p>And indeed, there are corresponding <a href="https://github.com/daviddrysdale/python-phonenumbers/blob/dev/python/phonenumbers/phonenumberutil.py#L1920" rel="nofollow"><code>phonenumbers.phonenumberutil.region_code_for_country_code()</code></a> and <a href="https://github.com/daviddrysdale/python-phonenumbers/blob/dev/python/phonenumbers/phonenumberutil.py#L1877" rel="nofollow"><code>phonenumbers.phonenumberutil.region_code_for_number()</code></a> functions to do the same in Python:</p> <pre><code>import phonenumbers from phonenumbers.phonenumberutil import ( region_code_for_country_code, region_code_for_number, ) pn = phonenumbers.parse('+442083661177') print(region_code_for_country_code(pn.country_code)) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; import phonenumbers &gt;&gt;&gt; from phonenumbers.phonenumberutil import region_code_for_country_code &gt;&gt;&gt; from phonenumbers.phonenumberutil import region_code_for_number &gt;&gt;&gt; pn = phonenumbers.parse('+442083661177') &gt;&gt;&gt; print(region_code_for_country_code(pn.country_code)) GB &gt;&gt;&gt; print(region_code_for_number(pn)) GB </code></pre> <p>The resulting region code is a 2-letter ISO code, so you can use that directly in <code>pycountry</code>:</p> <pre><code>&gt;&gt;&gt; import pycountry &gt;&gt;&gt; country = pycountry.countries.get(alpha2=region_code_for_number(pn)) &gt;&gt;&gt; print(country.name) United Kingdom </code></pre> <p>Note that the <code>.country_code</code> attribute is <em>just an integer</em>, so you can use <code>phonenumbers.phonenumberutil.region_code_for_country_code()</code> without a phone number, just a country code:</p> <pre><code>&gt;&gt;&gt; region_code_for_country_code(1) 'US' &gt;&gt;&gt; region_code_for_country_code(44) 'GB' </code></pre>
4
2016-07-24T12:59:08Z
[ "python", "phone-number" ]
Django - Registration form can't upload image
38,552,028
<p>I am a beginner with Django. I have a problem when I am filling the registration form. I can't upload any image. If the ImageField is set to required=true, it's never validated, impossible to submit. If required=false, it's possible to submit it but the image is never saved in destination folder (model). However, I can upload the image from the admin panel as a super user. </p> <pre><code>MODELS.PY from __future__ import unicode_literals from django.contrib.auth.models import AbstractUser, UserManager from django.db import models from django.utils import timezone class AccountUserManager(UserManager): def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields): now = timezone.now() if not email: raise ValueError('The given username must be set') email = self.normalize_email(email) user = self.model(username=email, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user class User(AbstractUser): """ Here goes a little code for stripe, but I removed it for making it shorter. """ team = models.CharField(max_length=20, default='') photo = models.ImageField('photo', upload_to='static/media/profiles/', null=True, blank=True) objects = AccountUserManager() </code></pre> <p>The views.py</p> <pre><code>VIEWS.PY from django.contrib import messages, auth from django.contrib.auth.decorators import login_required from accounts.forms import UserRegistrationForm, UserLoginForm from django.core.urlresolvers import reverse from django.shortcuts import render, redirect, get_object_or_404 from django.template.context_processors import csrf from django.conf import settings import datetime from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from models import User import stripe import arrow import json from django.http import Http404, HttpResponseRedirect from forms import UpdateProfileForm stripe.api_key = settings.STRIPE_SECRET def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): try: customer = stripe.Customer.create( email=form.cleaned_data['email'], card=form.cleaned_data['stripe_id'], plan='REG_MONTHLY', ) except stripe.error.CardError, e: messages.error(request, "Your card was declined!") if customer: user = form.save() user.stripe_id = customer.id user.subscription_end = arrow.now().replace(weeks=+4).datetime user.save() user = auth.authenticate(email=request.POST.get('email'), password=request.POST.get('password1')) if user: auth.login(request, user) messages.success(request, "You have successfully registered") return redirect(reverse('profile')) else: messages.error(request, "We were unable to log you in at this time") else: messages.error(request, "We were unable to take payment from the card provided") else: today = datetime.date.today() form = UserRegistrationForm(initial={'expiry_month': today.month, 'expiry_year': today.year}) args = {'form': form, 'publishable': settings.STRIPE_PUBLISHABLE} args.update(csrf(request)) return render(request, 'register.html', args) ... </code></pre> <p>And here comes forms.py:</p> <pre><code>FORMS.PY from django import forms from django.contrib.auth.forms import UserCreationForm from accounts.models import User from django.core.exceptions import ValidationError class UserRegistrationForm(UserCreationForm): """More fields for stripe""" photo = forms.ImageField(label='Photo', required=False) team = forms.CharField(label='team') password1 = forms.CharField( label='Password', widget=forms.PasswordInput ) password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput ) class Meta: model = User fields = ['email', 'password1', 'password2', 'team', 'photo'] exclude = ['username'] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: message = "Passwords do not match" raise forms.ValidationError(message) return password2 def clean_email(self): email = self.cleaned_data.get('email') if not email: message = "Please enter your email address" raise forms.ValidationError(message) return email def save(self, commit=True): instance = super(UserRegistrationForm, self).save(commit=False) # automatically set to email address to create a unique identifier instance.username = instance.email if commit: instance.save() return instance ... </code></pre> <p>Maybe the image it is not saved... I'm lost. I've been 3 days reading posts here, but I haven't found any solution. I saw a similar issue as mine, but with a different approach, but not resolved yet. <a href="http://stackoverflow.com/questions/28724822/django-upload-image-to-form">Django: upload image to form</a></p> <p>Thanks. </p>
0
2016-07-24T12:28:51Z
38,552,790
<p>You have to add request.FILES in form class</p> <pre><code>form = UserRegistrationForm(request.POST) </code></pre> <p>And also <code>form.post = request.FILES['photo']</code></p>
0
2016-07-24T13:55:36Z
[ "python", "django", "forms" ]
How to scan a panda dataframe for all values greater than something and returns row and column number corresponding to that value?
38,552,055
<p>I have a problem where I have huge data set like below (Correl Coeef matrix)</p> <pre><code> A B C D E A 1, 0.413454352,0.615350574,0.479720098,0.34261232 B 0.413454352,1, 0.568124328,0.316543449,0.361164436 C 0.615350574,0.568124328,1, 0.633182519,0.790921334 D 0.479720098,0.316543449,0.633182519,1, 0.450248008 E 0.34261232, 0.361164436,0.790921334,0.450248008,1 </code></pre> <p>I want to fetch all the values in this data frame where cell value is greater than 0.6 it should be along with row name and column name like below </p> <pre><code> row_name col_name value 1 A C 0.61 2 C A 0.61 3 C D 0.63 3 C E 0.79 4 D C 0.63 5 E C 0.79 </code></pre> <p>If we can also ignore either (A,C) or (C,A) ..it would be much better.</p> <p>I know I can do it using for loop but that method is not efficient for large data set.</p>
3
2016-07-24T12:31:18Z
38,552,230
<p><strong>UPDATE:</strong> using <a href="http://stackoverflow.com/a/38552281/5741205">@Divakar's solution</a> and <a href="http://stackoverflow.com/questions/38552055/how-to-scan-a-panda-dataframe-for-all-values-greater-than-something-and-returns/38552230?noredirect=1#comment64505165_38552230">his hints</a>:</p> <pre><code>In [186]: df = pd.DataFrame(np.triu(df, 1), columns=df.columns, index=df.index) In [187]: df Out[187]: A B C D E A 0.0 0.413454 0.615351 0.479720 0.342612 B 0.0 0.000000 0.568124 0.316543 0.361164 C 0.0 0.000000 0.000000 0.633183 0.790921 D 0.0 0.000000 0.000000 0.000000 0.450248 E 0.0 0.000000 0.000000 0.000000 0.000000 In [188]: df[df &gt; 0.6].stack().reset_index() Out[188]: level_0 level_1 0 0 A C 0.615351 1 C D 0.633183 2 C E 0.790921 </code></pre> <p><strong>OLD answer:</strong></p> <pre><code>In [96]: df[df &gt; 0.6] Out[96]: A B C D E A 1.000000 NaN 0.615351 NaN NaN B NaN 1.0 NaN NaN NaN C 0.615351 NaN 1.000000 0.633183 0.790921 D NaN NaN 0.633183 1.000000 NaN E NaN NaN 0.790921 NaN 1.000000 In [97]: df[df &gt; 0.6].stack() Out[97]: A A 1.000000 C 0.615351 B B 1.000000 C A 0.615351 C 1.000000 D 0.633183 E 0.790921 D C 0.633183 D 1.000000 E C 0.790921 E 1.000000 dtype: float64 </code></pre> <p>or:</p> <pre><code>In [99]: df[df &gt; 0.6].stack().reset_index() Out[99]: level_0 level_1 0 0 A A 1.000000 1 A C 0.615351 2 B B 1.000000 3 C A 0.615351 4 C C 1.000000 5 C D 0.633183 6 C E 0.790921 7 D C 0.633183 8 D D 1.000000 9 E C 0.790921 10 E E 1.000000 </code></pre> <p>data set:</p> <pre><code>In [100]: df Out[100]: A B C D E A 1.000000 0.413454 0.615351 0.479720 0.342612 B 0.413454 1.000000 0.568124 0.316543 0.361164 C 0.615351 0.568124 1.000000 0.633183 0.790921 D 0.479720 0.316543 0.633183 1.000000 0.450248 E 0.342612 0.361164 0.790921 0.450248 1.000000 </code></pre>
1
2016-07-24T12:51:34Z
[ "python", "pandas", "dataframe" ]
How to scan a panda dataframe for all values greater than something and returns row and column number corresponding to that value?
38,552,055
<p>I have a problem where I have huge data set like below (Correl Coeef matrix)</p> <pre><code> A B C D E A 1, 0.413454352,0.615350574,0.479720098,0.34261232 B 0.413454352,1, 0.568124328,0.316543449,0.361164436 C 0.615350574,0.568124328,1, 0.633182519,0.790921334 D 0.479720098,0.316543449,0.633182519,1, 0.450248008 E 0.34261232, 0.361164436,0.790921334,0.450248008,1 </code></pre> <p>I want to fetch all the values in this data frame where cell value is greater than 0.6 it should be along with row name and column name like below </p> <pre><code> row_name col_name value 1 A C 0.61 2 C A 0.61 3 C D 0.63 3 C E 0.79 4 D C 0.63 5 E C 0.79 </code></pre> <p>If we can also ignore either (A,C) or (C,A) ..it would be much better.</p> <p>I know I can do it using for loop but that method is not efficient for large data set.</p>
3
2016-07-24T12:31:18Z
38,552,281
<p>Here's a NumPy based approach -</p> <pre><code># Extract values and row, column names arr = df.values index_names = df.index col_names = df.columns # Get indices where such threshold is crossed; avoid diagonal elems R,C = np.where(np.triu(arr,1)&gt;0.6) # Arrange those in columns and put out as a dataframe out_arr = np.column_stack((index_names[R],col_names[C],arr[R,C])) df_out = pd.DataFrame(out_arr,columns=[['row_name','col_name','value']]) </code></pre> <p>Sample run -</p> <pre><code>In [139]: df Out[139]: A B C D E P 1.000000 0.031388 0.263606 0.121490 0.628969 Q 0.031388 1.000000 0.963510 0.497828 0.955238 R 0.263606 0.963510 1.000000 0.917935 0.520522 S 0.121490 0.497828 0.917935 1.000000 0.728386 T 0.628969 0.955238 0.520522 0.728386 1.000000 In [140]: df_out Out[140]: row_name col_name value 0 P E 0.628969 1 Q C 0.96351 2 Q E 0.955238 3 R D 0.917935 4 S E 0.728386 </code></pre>
3
2016-07-24T12:56:30Z
[ "python", "pandas", "dataframe" ]
How can I periodically change a tkinter image?
38,552,086
<p>I have an image that is saved in a file <code>test.bmp</code> and this file is overwritten 2 times per second<br> (I want to show 2 images per second).</p> <p>Here is what I have so far:</p> <pre><code>import tkinter as tk from PIL import Image, ImageTk root = tk.Tk() img_path = 'test.bmp' img = ImageTk.PhotoImage(Image.open(img_path), Image.ANTIALIAS)) canvas = tk.Canvas(root, height=400, width=400) canvas.create_image(200, 200, image=img) canvas.pack() root.mainloop() </code></pre> <p>But I don't know how can I refresh the image every ½ second?<br> I'm using Python3 and Tkinter.</p>
1
2016-07-24T12:35:33Z
38,555,487
<p>Gee, the code in your question looks very <a href="http://stackoverflow.com/a/38527334/355230">familiar</a>...</p> <p>Coming up with an answer comprised of tested code was complicated by the need to have the image file be updated by some mysterious unspecified process. This is done in the code below by creating a separate thread that periodically overwrites the image file independent of the main process. I tried to delineate this code from the rest with comments because I felt it was somewhat distracting and makes things seem more complex than they are really.</p> <p>The main takeaway is that you'll need to use the universal tkinter widget <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html" rel="nofollow"><code>after()</code></a> method to schedule the image to be refreshed at some future time. Care also needs to be taken to first create a place-holder canvas image object so it can be updated in-place later. This is needed because there may be other canvas objects present, and otherwise the updated image could cover them up depending on relative placement if a place-holder had not been created (so the image object id will be returned saved to be used later to change it).</p> <pre><code>from PIL import Image, ImageTk import tkinter as tk #------------------------------------------------------------------------------ # Code to simulate background process periodically updating the image file. # Note: # It's important that this code *not* interact directly with tkinter # stuff in the main process since it doesn't support multi-threading. import itertools import os import shutil import threading import time def update_image_file(dst): """ Overwrite (or create) destination file by copying successive image files to the destination path. Runs indefinitely. """ TEST_IMAGES = 'test_image1.png', 'test_image2.png', 'test_image3.png' for src in itertools.cycle(TEST_IMAGES): shutil.copy(src, dst) time.sleep(.5) # pause between updates #------------------------------------------------------------------------------ def refresh_image(canvas, img, image_path, image_id): try: pil_img = Image.open(image_path).resize((400,400), Image.ANTIALIAS) img = ImageTk.PhotoImage(pil_img) canvas.itemconfigure(image_id, image=img) except IOError: # missing or corrupt image file img = None # repeat every half sec canvas.after(500, refresh_image, canvas, img, image_path, image_id) root = tk.Tk() image_path = 'test.png' #------------------------------------------------------------------------------ # More code to simulate background process periodically updating the image file. th = threading.Thread(target=update_image_file, args=(image_path,)) th.daemon = True # terminates whenever main thread does th.start() while not os.path.exists(image_path): # let it run until image file exists time.sleep(.1) #------------------------------------------------------------------------------ canvas = tk.Canvas(root, height=400, width=400) img = None # initially only need a canvas image place-holder image_id = canvas.create_image(200, 200, image=img) canvas.pack() refresh_image(canvas, img, image_path, image_id) root.mainloop() </code></pre>
1
2016-07-24T18:39:35Z
[ "python", "image", "python-3.x", "tkinter" ]
how to know which environment running unit tests in django works on
38,552,131
<h1>Question</h1> <p>I want to separate my prod settings from my local settings. I found this library <a href="https://github.com/sobolevn/django-split-settings" rel="nofollow">django-split-settings</a>, which worked nicely. </p> <p>However somewhere in my code I have something like this:</p> <pre><code>if settings.DEBUG: # do debug stuff else: # do prod stuff </code></pre> <p>The problem is that when i run my unit test command:</p> <pre><code>./run ./manage.py test </code></pre> <p>the above if statements evaluates <code>settings.DEBUG</code> as false. Which makes me wonder, which settings file is the test command reading from and how to correct it</p> <h1>What I have tried</h1> <p>I tried running a command like this:</p> <pre><code>./run ./manage.py test --settings=bx/settings </code></pre> <p>gives me this crash:</p> <pre><code>Traceback (most recent call last): File "./manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/beneple/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/beneple/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: Import by filename is not supported. </code></pre> <p>any ideas?</p> <hr> <h3>update:</h3> <p>this is what my run command looks like</p> <pre><code>#!/usr/bin/env bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &amp;&amp; pwd )" docker run \ --env "PATH=/beneple/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \ -e "DJANGO_SETTINGS_MODULE=bx.settings.local" \ --link beneple_db:db \ -v $DIR:/beneple \ -t -i --rm \ beneple/beneple \ $@ </code></pre> <p>currently my manage.py looks like this</p> <pre><code>#!/usr/bin/env python import os import sys if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) </code></pre> <p>if I run this command:</p> <pre><code>./run ./manage.py shell </code></pre> <p>it works fine.. but for example when i try to run </p> <pre><code>./run ./flu.sh </code></pre> <p>which in turn runs test_data.py which starts like so:</p> <pre><code>#!/usr/bin/env python if __name__ == "__main__": import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import django django.setup() .. from django.conf import settings from settings import DOMAIN </code></pre> <p>it gives me the error:</p> <pre><code>Traceback (most recent call last): File "./bx/test_data.py", line 18, in &lt;module&gt; from settings import DOMAIN ImportError: cannot import name DOMAIN Done. </code></pre> <p>I'm not sure why that's happening, since my base.py definitely has DOMAIN set.</p>
1
2016-07-24T12:41:34Z
38,552,177
<p><code>--settings</code> is <code>The Python path to a settings module</code>. So <code>bx</code> is your root project folder and settings.py file is there then </p> <blockquote> <p>./run ./manage.py test --settings="bx"</p> </blockquote>
0
2016-07-24T12:46:25Z
[ "python", "django", "unit-testing" ]
how to know which environment running unit tests in django works on
38,552,131
<h1>Question</h1> <p>I want to separate my prod settings from my local settings. I found this library <a href="https://github.com/sobolevn/django-split-settings" rel="nofollow">django-split-settings</a>, which worked nicely. </p> <p>However somewhere in my code I have something like this:</p> <pre><code>if settings.DEBUG: # do debug stuff else: # do prod stuff </code></pre> <p>The problem is that when i run my unit test command:</p> <pre><code>./run ./manage.py test </code></pre> <p>the above if statements evaluates <code>settings.DEBUG</code> as false. Which makes me wonder, which settings file is the test command reading from and how to correct it</p> <h1>What I have tried</h1> <p>I tried running a command like this:</p> <pre><code>./run ./manage.py test --settings=bx/settings </code></pre> <p>gives me this crash:</p> <pre><code>Traceback (most recent call last): File "./manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/beneple/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/beneple/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: Import by filename is not supported. </code></pre> <p>any ideas?</p> <hr> <h3>update:</h3> <p>this is what my run command looks like</p> <pre><code>#!/usr/bin/env bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &amp;&amp; pwd )" docker run \ --env "PATH=/beneple/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \ -e "DJANGO_SETTINGS_MODULE=bx.settings.local" \ --link beneple_db:db \ -v $DIR:/beneple \ -t -i --rm \ beneple/beneple \ $@ </code></pre> <p>currently my manage.py looks like this</p> <pre><code>#!/usr/bin/env python import os import sys if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) </code></pre> <p>if I run this command:</p> <pre><code>./run ./manage.py shell </code></pre> <p>it works fine.. but for example when i try to run </p> <pre><code>./run ./flu.sh </code></pre> <p>which in turn runs test_data.py which starts like so:</p> <pre><code>#!/usr/bin/env python if __name__ == "__main__": import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import django django.setup() .. from django.conf import settings from settings import DOMAIN </code></pre> <p>it gives me the error:</p> <pre><code>Traceback (most recent call last): File "./bx/test_data.py", line 18, in &lt;module&gt; from settings import DOMAIN ImportError: cannot import name DOMAIN Done. </code></pre> <p>I'm not sure why that's happening, since my base.py definitely has DOMAIN set.</p>
1
2016-07-24T12:41:34Z
38,553,153
<p>Django test, by default, set DEBUG = False</p> <p><a href="https://docs.djangoproject.com/en/1.9/topics/testing/overview/#other-test-conditions" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/testing/overview/#other-test-conditions</a></p>
0
2016-07-24T14:31:01Z
[ "python", "django", "unit-testing" ]
Variable changing by itself inside loop
38,552,163
<p>I have a python <code>for</code> loop that seems to have a variable changing of its own accord inside the loop. My variables are defined as:</p> <pre><code>yhat = np.empty((1,len(prices))) yhat[:] = nan yhat = yhat.astype('float') e = Q = yhat P = R = np.matrix(np.zeros((2,2))) B = np.empty((2,len(prices))) B[:] = nan B = np.matrix(B) B[:,0] = 0 </code></pre> <p>The loop is: (<code>prices</code> is a dataframe)</p> <pre><code>for t in xrange(0,len(prices),1): if t &gt; 0: B[:,t] = B[:,t-1] R = P+Vw yhat[0,t] = x[t,:]*B[:,t] print yhat[0,t] Q[0,t] = x[t,:]*R*x[t,:].T + Ve print yhat[0,t] e[0,t] = y[t,0] - yhat[0,t] print yhat[0,t] K = (R*x[t,:].T)/Q[0,t] B[:,t] = B[:,t]+K*e[0,t] P = R - K*x[t,:]*R </code></pre> <p>I'm printing <code>yhat</code> because I've narrowed the anomaly in the code down to it. After set the value of <code>yhat</code> @ t, it seems to change. When I run the code, it prints out:</p> <pre><code>0.0 0.001 20.438747 </code></pre> <p>Additionally, I'm concerned about the subtraction for <code>e[0,t]</code> because for some reason the subtraction results in the value of <code>yhat</code> at that current moment?</p> <p>Maybe I'm missing something blatantly obvious. I'm relatively new to python, and I switched over from MATLAB.</p> <p>EDIT: x &amp; y are also matrix objects. So all of the multiplications are matrix dot products.</p>
0
2016-07-24T12:44:42Z
38,552,187
<p><code>e = Q = yhat</code> won't create copies. They are instead additional <em>references to the same object</em>. Altering that object through either the <code>e</code> or <code>Q</code> names will reflect in those changes being visible through the <code>yhat</code> reference too.</p> <p>So</p> <pre><code>yhat[0,t] = x[t,:]*B[:,t] </code></pre> <p>and</p> <pre><code>Q[0,t] = x[t,:]*R*x[t,:].T + Ve </code></pre> <p>and </p> <pre><code>e[0,t] = y[t,0] - yhat[0,t] </code></pre> <p>all operate on the same, single <code>numpy</code> array object, not on separate objects.</p> <p>Use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html" rel="nofollow"><code>numpy.copy()</code> function</a> to create independent new copies instead:</p> <pre><code>e, Q = np.copy(yhat), np.copy(yhat) </code></pre>
3
2016-07-24T12:47:03Z
[ "python", "loops", "variables", "matrix" ]
How to pass echo y to plink.exe for first connection
38,552,236
<p>I would like to pass <code>echo y</code> to plink.exe, so that plink execute a command. How it can be achieved?</p> <pre><code>os.system(' c:/netapp/python/plink.exe admin@192.168.1.1 -pw xxx uptime &gt; c:/netapp/python/12.txt') </code></pre> <blockquote> <p>The server's host key is not cached in the registry. You have no guarantee that the server is the computer you think it is. The server's rsa2 key fingerprint is: ssh-rsa 2048 9d:08:37:a8:d0:34:a3:d2:d8:e5:09:7e:63:08:a9:1b If you trust this host, enter "y" to add the key to</p> <p>Store key in cache? (y/n)</p> </blockquote>
0
2016-07-24T12:52:18Z
38,552,455
<p>Confirming a server's SSH key fingerprint is an important step. This is how you know you've connected to the correct machine, and should always be done with care.</p> <p>The Plink documentation <a href="http://the.earth.li/~sgtatham/putty/0.67/htmldoc/Chapter7.html#plink-usage-batch" rel="nofollow">makes the following suggestion</a>:</p> <blockquote> <p>To avoid being prompted for the server host key when using Plink for an automated connection, you should first make a <em>manual</em> connection (using either of PuTTY or Plink) to the same server, verify the host key (see <a href="http://the.earth.li/~sgtatham/putty/0.67/htmldoc/Chapter2.html#gs-hostkey" rel="nofollow">section 2.2</a> for more information), and select Yes to add the host key to the Registry. After that, Plink commands connecting to that server should not give a host key prompt unless the host key changes.</p> </blockquote>
0
2016-07-24T13:17:43Z
[ "python", "plink" ]
How to pass echo y to plink.exe for first connection
38,552,236
<p>I would like to pass <code>echo y</code> to plink.exe, so that plink execute a command. How it can be achieved?</p> <pre><code>os.system(' c:/netapp/python/plink.exe admin@192.168.1.1 -pw xxx uptime &gt; c:/netapp/python/12.txt') </code></pre> <blockquote> <p>The server's host key is not cached in the registry. You have no guarantee that the server is the computer you think it is. The server's rsa2 key fingerprint is: ssh-rsa 2048 9d:08:37:a8:d0:34:a3:d2:d8:e5:09:7e:63:08:a9:1b If you trust this host, enter "y" to add the key to</p> <p>Store key in cache? (y/n)</p> </blockquote>
0
2016-07-24T12:52:18Z
38,572,722
<p><strong>Do not!</strong></p> <p>Verifying host key fingerprint is an integral part of securing your connection. Blindly accepting any host key will make you vulnerable to the <a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack" rel="nofollow">man-in-the-middle attacks</a>.</p> <hr> <p>Instead, use the <a href="http://the.earth.li/~sgtatham/putty/0.67/htmldoc/Chapter3.html#using-cmdline-hostkey" rel="nofollow"><code>-hostkey</code> switch</a> to provide the fingerprint of the expected/known host key.</p> <pre><code>c:/netapp/python/plink.exe admin@192.168.1.1 -pw xxx -hostkey 9d:08:37:a8:d0:34:a3:d2:d8:e5:09:7e:63:08:a9:1b uptime </code></pre>
2
2016-07-25T16:12:58Z
[ "python", "plink" ]
change urlparse.path of a url
38,552,253
<p>Here is the python code:</p> <pre><code>url = http://www.phonebook.com.pk/dynamic/search.aspx path = urlparse(url) print (path) &gt;&gt;&gt;ParseResult(scheme='http', netloc='www.phonebook.com.pk', path='/dynamic/search.aspx', params='', query='searchtype=cat&amp;class_id=4520&amp;page=1', fragment='') print (path.path) &gt;&gt;&gt;/dynamic/search.aspx </code></pre> <p>Now I need to change the <code>path.path</code> to my requirement. Like if "/dynamic/search.aspx" is the path then I only need the parts between the first slash and last slash including slashes which is "/dynamic/".</p> <p>I have tried these two lines but end result is not what I expected that's why I am asking this question as my knowledge of "urllib.parse" is insufficient.</p> <pre><code>path = path.path[:path.path.index("/")] print (path) &gt;&gt;&gt;Returns nothing. path = path.path[path.path.index("/"):] &gt;&gt;&gt;/dynamic/search.aspx (as it was before, no change.) </code></pre> <p>In short whatever the path.path result is my need is directory names only. For example:" dynamic/search/search.aspx". now I need "dynamic/search/"</p>
1
2016-07-24T12:53:34Z
38,552,680
<p>I've tried to look into <code>urlparse</code> to find any method that could help in your situation, but didn't find, may be overlooked, but anyway, at this level, you probably would have to make your own method or hack:</p> <pre><code>&gt;&gt;&gt; path.path '/dynamic/search.aspx' &gt;&gt;&gt; import re &gt;&gt;&gt; d = re.search(r'/.*/', path.path) &gt;&gt;&gt; d.group(0) '/dynamic/' </code></pre> <p>This is just an example to you, you may also use built-in methods, like so:</p> <pre><code>&gt;&gt;&gt; i = path.path.index('/', 1) &gt;&gt;&gt; &gt;&gt;&gt; path.path[:i+1] '/dynamic/' </code></pre> <p>EDIT:</p> <p>I didn't notice your last example, so here is another way:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; path = os.path.dirname(path.path) + os.sep &gt;&gt;&gt; path '/dynamic/' &gt;&gt;&gt; path = os.path.dirname(s) + os.sep &gt;&gt;&gt; path 'dynamic/search/' </code></pre> <p>Or with <code>re</code>:</p> <pre><code>&gt;&gt;&gt; s 'dynamic/search/search.aspx' &gt;&gt;&gt; d = re.search(r'.*/', s) &gt;&gt;&gt; d &lt;_sre.SRE_Match object; span=(0, 15), match='dynamic/search/'&gt; &gt;&gt;&gt; d.group(0) 'dynamic/search/' &gt;&gt;&gt; &gt;&gt;&gt; s = '/dynamic/search.aspx' &gt;&gt;&gt; d = re.search(r'.*/', s) &gt;&gt;&gt; d.group(0) '/dynamic/' </code></pre>
1
2016-07-24T13:44:22Z
[ "python", "python-3.x", "urlparse" ]
instantiate object (codecademy)
38,552,285
<p>I typed the following code, printed the answers I was supposed to get (3 and True), but it keeps giving me an error, asking me if I "Created an instance in class Triangle called my_triangle". How can this be, if I in fact did intantiate my_triangle and even got the correct results with it?</p> <pre><code>class Triangle(object): def __init__(self, angle1, angle2, angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 number_of_sides = 3 def check_angles(self): if self.angle1 + self.angle2 + self.angle3 == 180: return True else: return False my_triangle = Triangle(90, 30, 60) print my_triangle.number_of_sides print my_triangle.check_angles() </code></pre>
-1
2016-07-24T12:56:50Z
38,552,309
<p>Your indentation is wrong. The last three lines need to be aligned all the way to the left.</p>
1
2016-07-24T12:59:05Z
[ "python" ]
Does numpy methods work correctly on numbers too big to fit numpy dtypes?
38,552,392
<p>I would like to know if numbers bigger than what int64 or float128 can be correctly processed by numpy functions EDIT: numpy functions applied to numbers/python objects outside of any numpy array. Like using a np function in a list comprehension that applies to the content of a list of int128?</p> <p>I can't find anything about that in their docs, but I really don't know what to think and expect. From tests, it should work but I want to be sure, and a few trivial test won't help for that. So I come here for knowledge:<br> If np framework is not handling such big numbers, are its functions able to deal with these anyway?</p> <p>EDIT: sorry, I wasn't clear. Please see the edit above Thanks by advance.</p>
0
2016-07-24T13:09:40Z
38,552,519
<p>You can have numpy arrays of python objects, which could be a python integer which is too big to fit in np.int64. Some of numpy's functionality will work, but many functions call underlying c code which will not work. Here is an example:</p> <pre><code>import numpy as np a = np.array([123456789012345678901234567890]) # a has dtype object now print((a*2)[0]) # Works and gives the right result print(np.exp(a)) # Does not work, because "'int' object has no attribute 'exp'" </code></pre> <p>Generally, most functionality will probably be lost for your extremely large numbers. Also, as it has been pointed out, when you have an array with a dtype of np.int64 or similar, you will have overflow problems, when you increase the size of your array elements over that types limit. With numpy, you have to be careful about what your array's dtype is! </p>
1
2016-07-24T13:25:35Z
[ "python", "numpy", "int", "precision" ]
Does numpy methods work correctly on numbers too big to fit numpy dtypes?
38,552,392
<p>I would like to know if numbers bigger than what int64 or float128 can be correctly processed by numpy functions EDIT: numpy functions applied to numbers/python objects outside of any numpy array. Like using a np function in a list comprehension that applies to the content of a list of int128?</p> <p>I can't find anything about that in their docs, but I really don't know what to think and expect. From tests, it should work but I want to be sure, and a few trivial test won't help for that. So I come here for knowledge:<br> If np framework is not handling such big numbers, are its functions able to deal with these anyway?</p> <p>EDIT: sorry, I wasn't clear. Please see the edit above Thanks by advance.</p>
0
2016-07-24T13:09:40Z
38,552,523
<p>When storing a number into a numpy array with a dtype not sufficient to store it, you will get truncation or an error</p> <pre><code>arr = np.empty(1, dtype=np.int64) arr[0] = 2**65 arr </code></pre> <p>Gives <code>OverflowError: Python int too large to convert to C long</code>.</p> <pre><code>arr = np.empty(1, dtype=float16) arr[0] = 2**64 arr </code></pre> <p>Gives <code>inf</code> (and no error)</p> <pre><code>arr[0] = 2**15 + 2 arr </code></pre> <p>Gives <code>[ 32768.]</code> (i.e., 2**15), so truncation occurred. It would be harder for this to happen with float128...</p>
1
2016-07-24T13:26:17Z
[ "python", "numpy", "int", "precision" ]
Does numpy methods work correctly on numbers too big to fit numpy dtypes?
38,552,392
<p>I would like to know if numbers bigger than what int64 or float128 can be correctly processed by numpy functions EDIT: numpy functions applied to numbers/python objects outside of any numpy array. Like using a np function in a list comprehension that applies to the content of a list of int128?</p> <p>I can't find anything about that in their docs, but I really don't know what to think and expect. From tests, it should work but I want to be sure, and a few trivial test won't help for that. So I come here for knowledge:<br> If np framework is not handling such big numbers, are its functions able to deal with these anyway?</p> <p>EDIT: sorry, I wasn't clear. Please see the edit above Thanks by advance.</p>
0
2016-07-24T13:09:40Z
38,552,699
<p>See the Extended Precision heading in the Numpy documentation <a href="http://docs.scipy.org/doc/numpy/user/basics.types.html" rel="nofollow">here</a>. For very large numbers, you can also create an array with <code>dtype</code> set to <code>'object'</code>, which will allow you essentially to use the Numpy framework on the large numbers but with lower performance than using native types. As has been pointed out, though, this will break when you try to call a function not supported by the particular object saved in the array.</p> <pre><code>import numpy as np arr = np.array([10**105, 10**106], dtype='object') </code></pre> <p>But the short answer is that you you can and will get unexpected behavior when using these large numbers unless you take special care to account for them.</p>
1
2016-07-24T13:46:04Z
[ "python", "numpy", "int", "precision" ]
How can I load a text file as array that can be loaded element by element?
38,552,418
<p>I have a text file with the following information:</p> <pre><code>SHRO BJRD ZNJK GRMI </code></pre> <p>I want to save them in a way that I can load them line by line. I mean, suppose its name is "name", and I want the 4th column like below:</p> <pre><code>name[3] = "GRMI" </code></pre> <p>How can I do this? </p>
0
2016-07-24T13:13:00Z
38,552,561
<p>You could do something like this:</p> <pre><code>with open('filename.txt') as f: name = f.read().split() </code></pre> <p>EDIT<br> According to that answer you've posted, I understand that you simply need to print the name in a line and so, the modified code will be this:</p> <pre><code>with open('filename.txt') as f: print f.read().split('\n')[12][:4] # Assuming that all of the those consist of 4 characters. # That number 12 was just an example. </code></pre> <p>Otherwise,</p> <pre><code>with open('filename.txt') as f: names = f.read().split('\n') print names[12].split()[0] # Again, that number is an example. </code></pre>
3
2016-07-24T13:30:49Z
[ "python" ]
How can I load a text file as array that can be loaded element by element?
38,552,418
<p>I have a text file with the following information:</p> <pre><code>SHRO BJRD ZNJK GRMI </code></pre> <p>I want to save them in a way that I can load them line by line. I mean, suppose its name is "name", and I want the 4th column like below:</p> <pre><code>name[3] = "GRMI" </code></pre> <p>How can I do this? </p>
0
2016-07-24T13:13:00Z
38,553,041
<p>You probably want something like</p> <pre><code>with open('stationlist', 'r') as f: station_names = [line.split()[0] for line in f] </code></pre> <p>If all of the station names are four characters, the list comprehension could be replaced by</p> <pre><code>[line[:4] for line in f] </code></pre>
0
2016-07-24T14:21:14Z
[ "python" ]
Scrapy - input processor
38,552,506
<p>items.py:</p> <pre><code>import scrapy from scrapy.loader.processors import MapCompose def filter_spaces(value): return value.strip(" ").strip("\n") class LotItem(scrapy.Item): num = scrapy.Field(input_processor=MapCompose(filter_spaces)) </code></pre> <p>spider.py:</p> <pre><code>def parse_item(self, response): item = LotItem() item['num'] = response.xpath('//div/span/text()').extract()[0] yield item </code></pre> <p><code>response.xpath('//div/span/text()').extract()[0]</code> returns a kind of </p> <pre><code>"\n1234 " </code></pre> <p>And I need to turn it into: <code>"1234"</code></p> <p>But I still get object in the form - <code>{'num': '\n1234 '}</code> </p> <p>Thanks a lot!!!</p>
1
2016-07-24T13:25:11Z
38,556,992
<p>You can use response.xpath with a regular expression instead of extract(). Something like this for the number:</p> <pre><code>response.xpath("//div/span/text()").re(r"(?:'num':\s'\\n)([0-9]*)(?:\s*')") </code></pre> <p>or something like this for the city:</p> <pre><code>.re(r'(?:\\"city\\":\s\"G\\\)(.*)(?:\\")') </code></pre> <p>(All regular expressions are untested and may need slight tweaking.)</p>
1
2016-07-24T21:29:15Z
[ "python", "scrapy" ]
Python SQLite update error
38,552,571
<p>I'm writing some scoring server using python and sqlite, and error occured when using update. </p> <pre><code>Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from server import * &gt;&gt;&gt; db = DB_control() &gt;&gt;&gt; db.update_user_score("ZSPEF1", "FXVCWI", 180) UPDATE score SET FXVCWI = 180 WHERE USER_ID = ZSPEF1 Error raised while updating ID ZSPEF1's score to 180. Rolling back DB... DB Successfully rolled back Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "server.py", line 102, in update_user_score musica_db.execute(update_score_str) sqlite3.OperationalError: no such column: ZSPEF1 &gt;&gt;&gt; </code></pre> <p>score table looks like this: <a href="http://i.stack.imgur.com/zvjMf.png" rel="nofollow"><img src="http://i.stack.imgur.com/zvjMf.png" alt="score table screenshot"></a></p> <p>As you see, there are FXVCWI column and ZSPEF1 row and want to change that value, but error says there are no ZSPEF1 column.<br> UPDATE command only occurs error on update_user_score function.</p> <p>Why this happens to me? Also, error sometimes occurs when first character in string is number. Is there any way to prevent this error?</p> <p>Here is my code</p> <pre><code>#!/usr/bin/env python import sqlite3 musica_db_file = sqlite3.connect("musica.db") musica_db = musica_db_file.cursor() class DB_control(object): def setupDB(self): #This function should execute only on first run. try: userDB_setupDB_str = "NUM INTEGER PRIMARY KEY AUTOINCREMENT, " userDB_setupDB_str += "CARD_ID TEXT NOT NULL UNIQUE, " userDB_setupDB_str += "NAME TEXT NOT NULL UNIQUE, " userDB_setupDB_str += "PASSWORD TEXT NOT NULL, " userDB_setupDB_str += "ADMIN INT NOT NULL DEFAULT 0" songDB_setupDB_str = "NUM INTEGER PRIMARY KEY AUTOINCREMENT, " songDB_setupDB_str += "SONG_ID INT NOT NULL UNIQUE, " songDB_setupDB_str += "NAME TEXT NOT NULL UNIQUE, " songDB_setupDB_str += "FINGERPRINT TEXT NOT NULL UNIQUE" scoreDB_setupDB_str = "USER_ID TEXT NOT NULL UNIQUE" musica_db.execute('CREATE TABLE user({0}) '.format(userDB_setupDB_str)) musica_db.execute('CREATE TABLE song({0}) '.format(songDB_setupDB_str)) musica_db.execute('CREATE TABLE score({0})'.format(scoreDB_setupDB_str)) musica_db_file.commit() self.add_user(randomID(), 'MU_Admin', 'yj809042', admin=True) #Create admin account. self.add_song(randomID(), 'Tutorial', randomID()) #Create tutorial(dummy) song print("DB setuped.") except: print("Error raised while setuping DB") raise def update_user_score(self, cardID, songID, score): try: update_score_str = "UPDATE score SET {0} = {1} WHERE USER_ID = {2}".format(songID, score, cardID) print update_score_str musica_db.execute(update_score_str) musica_db_file.commit() print("User ID {0}'s score is now {1}.".format(cardID, score)) except: print("Error raised while updating ID {0}'s score to {1}. Rolling back DB...".format(cardID, score)) self.rollback_DB() raise def rollback_DB(self): try: musica_db_file.rollback() musica_db_file.commit() print("DB Successfully rolled back") except: print("Error raised while rolling back DB. Critical.") raise </code></pre>
0
2016-07-24T13:32:16Z
38,552,769
<p>You are interpolating column values as <em>SQL object names</em>, with no quoting:</p> <pre><code>update_score_str = "UPDATE score SET {0} = {1} WHERE USER_ID = {2}".format(songID, score, cardID) musica_db.execute(update_score_str) </code></pre> <p>Don't use string interpolation for SQL <em>values</em>. Use bind parameters instead:</p> <pre><code>update_score_str = "UPDATE score SET {0} = ? WHERE USER_ID = ?".format(songID) musica_db.execute(update_score_str, (score, cardID)) </code></pre> <p>The <code>cursor.execute()</code> function will then take care of proper quoting, reducing your risk of SQL injection.</p> <p>Even interpolating SQL object names (<code>songID</code> here) is dodgy; do make sure you validate that string up front.</p> <p>It looks as if you are creating a column per song. You probably want to read up some more about proper relational table design and <em>not</em> store data in column names. Use a <code>user_song_scores</code> many-to-many table instead, where that table stores <code>(USER_ID, SONG_ID, SCORE)</code> tuples, letting you update scores for a given song with <code>UPDATE user_song_scores SET score=? WHERE USER_ID=? AND SONG_ID=?</code> instead, removing the need to generate column names.</p>
1
2016-07-24T13:53:47Z
[ "python", "python-2.7", "sqlite3" ]
How Django authnetication works with SQL Server?
38,552,624
<p>Just wanted to understand how exactly Python Django works with databases such as SQL Server or MySql.</p> <p>For example, in ASP.NET WebForms, you'll have a <code>UserID</code> field from your custom <code>User</code> table that you link with the default <code>aspnet_Users</code> table. That's what connects your database to ASP.NET. </p> <p>My question is how does it work in Django? How do I link registered users to my own database?</p> <p>I hope this question is clear.</p> <p>Thanks in advance.</p>
1
2016-07-24T13:38:12Z
38,553,102
<p>Django is consider a "batteries included" framework. Django has a robust ORM and build in system for user management. In specifics to users and authentication and authorization, Django has an out-of-the-box user model with fields for username, password, first name, last name, and email address; it also has facilities for groups and permissions. This can be extended using <code>AbstractUser</code>, or replaced entirely using <code>AbstractBaseUser</code>. More details can be found in the documentation:</p> <p><a href="https://docs.djangoproject.com/en/1.9/topics/auth/" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/auth/</a></p> <p>Good luck.</p>
0
2016-07-24T14:26:16Z
[ "python", "mysql", "asp.net", "sql-server", "django" ]
Pandas gives an error from str.extractall('#')
38,552,688
<p>I am trying to filter all the <code>#</code> keywords from the tweet text. I am using <code>str.extractall()</code> to extract all the keywords with <code>#</code> keywords. This is the first time I am working on filtering keywords from the tweetText using pandas. Inputs, code, expected output and error are given below.</p> <p>Input: </p> <pre><code>userID,tweetText 01, home #sweet home 01, #happy #life 02, #world peace 03, #all are one 04, world tour </code></pre> <p>and so on... the total datafile is in GB size scraped tweets with several other columns. But I am interested in only two columns. </p> <p>Code: </p> <pre><code>import re import pandas as pd data = pd.read_csv('Text.csv', index_col=0, header=None, names=['userID', 'tweetText']) fout = data['tweetText'].str.extractall('#') print fout </code></pre> <p>Expected Output: </p> <pre><code>userID,tweetText 01,#sweet 01,#happy 01,#life 02,#world 03,#all </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "keyword_split.py", line 7, in &lt;module&gt; fout = data['tweetText'].str.extractall('#') File "/usr/local/lib/python2.7/dist-packages/pandas/core/strings.py", line 1621, in extractall return str_extractall(self._orig, pat, flags=flags) File "/usr/local/lib/python2.7/dist-packages/pandas/core/strings.py", line 694, in str_extractall raise ValueError("pattern contains no capture groups") ValueError: pattern contains no capture groups </code></pre> <p>Thanks in advance for the help. What should be the simplest way to filter keywords with respect to userid?</p> <p>Output Update: </p> <p>When used only this the output is like above <code>s.name = "tweetText" data_1 = data[~data['tweetText'].isnull()]</code></p> <p>The output in this case has empty <code>[]</code> and the userID at still listed and for those which has keywords has an array of keywords and not in list form. </p> <p>When used only this the output us what needed but with <code>NAN</code></p> <pre><code>s.name = "tweetText" data_2 = data_1.drop('tweetText', axis=1).join(s) </code></pre> <p>The output here is correct format but those with no keywords has yet considered and has NAN </p> <p>If it is possible we got to neglect such userIDs and not shown in output at all.In next stages I am trying to calculate the frequency of keywords in which the <code>NAN</code> or empty <code>[]</code> will also be counted and that frequency may compromise the far future classification. </p> <p><a href="http://i.stack.imgur.com/VYHY4.png" rel="nofollow"><img src="http://i.stack.imgur.com/VYHY4.png" alt="enter image description here"></a></p>
2
2016-07-24T13:45:14Z
38,553,194
<p>The <code>extractall</code> function requires a regex pattern <strong>with capturing groups</strong> as the first argument, for which you have provided <code>#</code>.</p> <p>A possible argument could be <code>(#\S+)</code>. The braces indicate a capture group, in other words what the <code>extractall</code> function needs to extract from each string.</p> <p>Example:</p> <pre><code>data="""01, home #sweet home 01, #happy #life 02, #world peace 03, #all are one """ import pandas as pd from io import StringIO df = pd.read_csv(StringIO(data), header=None, names=['col1', 'col2'], index_col=0) df['col2'].str.extractall('(#\S+)') </code></pre> <p>The error <code>ValueError: pattern contains no capture groups</code> doesn't appear anymore with the above code (meaning the issue in the question is solved), but this hits a bug in the current version of pandas (I'm using <code>'0.18.1'</code>). </p> <p>The error returned is: </p> <pre><code>AssertionError: 1 columns passed, passed data had 6 columns </code></pre> <p>The issue is described <a href="https://github.com/pydata/pandas/issues/13382" rel="nofollow">here</a>.</p> <p>If you would try <code>df['col2'].str.extractall('#(\S)')</code>(which will give you the first letter of every hashtag, you'll see that the <code>extractall</code> function works as long as the captured group only contains a single character (which matches the issue description). As the issue is closed, it should be fixed in an upcoming pandas release.</p>
2
2016-07-24T14:35:02Z
[ "python", "pandas" ]
Pandas gives an error from str.extractall('#')
38,552,688
<p>I am trying to filter all the <code>#</code> keywords from the tweet text. I am using <code>str.extractall()</code> to extract all the keywords with <code>#</code> keywords. This is the first time I am working on filtering keywords from the tweetText using pandas. Inputs, code, expected output and error are given below.</p> <p>Input: </p> <pre><code>userID,tweetText 01, home #sweet home 01, #happy #life 02, #world peace 03, #all are one 04, world tour </code></pre> <p>and so on... the total datafile is in GB size scraped tweets with several other columns. But I am interested in only two columns. </p> <p>Code: </p> <pre><code>import re import pandas as pd data = pd.read_csv('Text.csv', index_col=0, header=None, names=['userID', 'tweetText']) fout = data['tweetText'].str.extractall('#') print fout </code></pre> <p>Expected Output: </p> <pre><code>userID,tweetText 01,#sweet 01,#happy 01,#life 02,#world 03,#all </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "keyword_split.py", line 7, in &lt;module&gt; fout = data['tweetText'].str.extractall('#') File "/usr/local/lib/python2.7/dist-packages/pandas/core/strings.py", line 1621, in extractall return str_extractall(self._orig, pat, flags=flags) File "/usr/local/lib/python2.7/dist-packages/pandas/core/strings.py", line 694, in str_extractall raise ValueError("pattern contains no capture groups") ValueError: pattern contains no capture groups </code></pre> <p>Thanks in advance for the help. What should be the simplest way to filter keywords with respect to userid?</p> <p>Output Update: </p> <p>When used only this the output is like above <code>s.name = "tweetText" data_1 = data[~data['tweetText'].isnull()]</code></p> <p>The output in this case has empty <code>[]</code> and the userID at still listed and for those which has keywords has an array of keywords and not in list form. </p> <p>When used only this the output us what needed but with <code>NAN</code></p> <pre><code>s.name = "tweetText" data_2 = data_1.drop('tweetText', axis=1).join(s) </code></pre> <p>The output here is correct format but those with no keywords has yet considered and has NAN </p> <p>If it is possible we got to neglect such userIDs and not shown in output at all.In next stages I am trying to calculate the frequency of keywords in which the <code>NAN</code> or empty <code>[]</code> will also be counted and that frequency may compromise the far future classification. </p> <p><a href="http://i.stack.imgur.com/VYHY4.png" rel="nofollow"><img src="http://i.stack.imgur.com/VYHY4.png" alt="enter image description here"></a></p>
2
2016-07-24T13:45:14Z
38,553,531
<p>If you are not too tied to using <code>extractall</code>, you can try the following to get your final output:</p> <pre><code>from io import StringIO import pandas as pd import re data_text = """userID,tweetText 01, home #sweet home 01, #happy #life 02, #world peace 03, #all are one """ data = pd.read_csv(StringIO(data_text),header=0) data['tweetText'] = data.tweetText.apply(lambda x: re.findall('#(?=\w+)\w+',x)) s = data.apply(lambda x: pd.Series(x['tweetText']),axis=1).stack().reset_index(level=1, drop=True) s.name = "tweetText" data = data.drop('tweetText', axis=1).join(s) userID tweetText 0 1 #sweet 1 1 #happy 1 1 #life 2 2 #world 3 3 #all 4 4 NaN </code></pre> <p>You drop the rows where the textTweet column returns <code>Nan</code>'s by doing the following:</p> <pre><code>data = data[~data['tweetText'].isnull()] </code></pre> <p>This should return:</p> <pre><code> userID tweetText 0 1 #sweet 1 1 #happy 1 1 #life 2 2 #world 3 3 #all </code></pre> <p>I hope this helps.</p>
2
2016-07-24T15:12:11Z
[ "python", "pandas" ]
Pandas gives an error from str.extractall('#')
38,552,688
<p>I am trying to filter all the <code>#</code> keywords from the tweet text. I am using <code>str.extractall()</code> to extract all the keywords with <code>#</code> keywords. This is the first time I am working on filtering keywords from the tweetText using pandas. Inputs, code, expected output and error are given below.</p> <p>Input: </p> <pre><code>userID,tweetText 01, home #sweet home 01, #happy #life 02, #world peace 03, #all are one 04, world tour </code></pre> <p>and so on... the total datafile is in GB size scraped tweets with several other columns. But I am interested in only two columns. </p> <p>Code: </p> <pre><code>import re import pandas as pd data = pd.read_csv('Text.csv', index_col=0, header=None, names=['userID', 'tweetText']) fout = data['tweetText'].str.extractall('#') print fout </code></pre> <p>Expected Output: </p> <pre><code>userID,tweetText 01,#sweet 01,#happy 01,#life 02,#world 03,#all </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "keyword_split.py", line 7, in &lt;module&gt; fout = data['tweetText'].str.extractall('#') File "/usr/local/lib/python2.7/dist-packages/pandas/core/strings.py", line 1621, in extractall return str_extractall(self._orig, pat, flags=flags) File "/usr/local/lib/python2.7/dist-packages/pandas/core/strings.py", line 694, in str_extractall raise ValueError("pattern contains no capture groups") ValueError: pattern contains no capture groups </code></pre> <p>Thanks in advance for the help. What should be the simplest way to filter keywords with respect to userid?</p> <p>Output Update: </p> <p>When used only this the output is like above <code>s.name = "tweetText" data_1 = data[~data['tweetText'].isnull()]</code></p> <p>The output in this case has empty <code>[]</code> and the userID at still listed and for those which has keywords has an array of keywords and not in list form. </p> <p>When used only this the output us what needed but with <code>NAN</code></p> <pre><code>s.name = "tweetText" data_2 = data_1.drop('tweetText', axis=1).join(s) </code></pre> <p>The output here is correct format but those with no keywords has yet considered and has NAN </p> <p>If it is possible we got to neglect such userIDs and not shown in output at all.In next stages I am trying to calculate the frequency of keywords in which the <code>NAN</code> or empty <code>[]</code> will also be counted and that frequency may compromise the far future classification. </p> <p><a href="http://i.stack.imgur.com/VYHY4.png" rel="nofollow"><img src="http://i.stack.imgur.com/VYHY4.png" alt="enter image description here"></a></p>
2
2016-07-24T13:45:14Z
38,554,554
<p>Try this: </p> <p>Since it filters for '#', your NAN should not exist. </p> <pre><code> data = pd.read_csv(StringIO(data_text),header=0, index_col=0 ) data = data["tweetText"].str.split(' ', expand=True).stack().reset_index().rename(columns = {0:"tweetText"}).drop('level_1', 1) data = data[data['tweetText'].str[0] == "#"].reset_index(drop=True) userID tweetText 0 1 #sweet 1 1 #happy 2 1 #life 3 2 #world 4 3 #all </code></pre> <p>@Abdou method: </p> <pre><code>def try1(): data = pd.read_csv(StringIO(data_text),header=0) data['tweetText'] = data.tweetText.apply(lambda x: re.findall('#(?=\w+)\w+',x)) s = data.apply(lambda x: pd.Series(x['tweetText']),axis=1).stack().reset_index(level=1, drop=True) s.name = "tweetText" data = data.drop('tweetText', axis=1).join(s) data = data[~data['tweetText'].isnull()] %timeit try1() 100 loops, best of 3: 7.71 ms per loop </code></pre> <p>@Merlin method</p> <pre><code>def try2(): data = pd.read_csv(StringIO(data_text),header=0, index_col=0 ) data = data["tweetText"].str.split(' ', expand=True).stack().reset_index().rename(columns = {'level_0':'userID',0:"tweetText"}).drop('level_1', 1) data = data[data['tweetText'].str[0] == "#"].reset_index(drop=True) %timeit try2() 100 loops, best of 3: 5.36 ms per loop </code></pre>
0
2016-07-24T17:04:28Z
[ "python", "pandas" ]
python BeautifulSoap table scraping
38,552,722
<p>my HTML has several tables, the first table is:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;div id="string"&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>and the rest are of the form:</p> <pre><code>&lt;table class="confluenceTable" data-csvtable="1"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th class="highlight-grey confluenceTh" data-highlight-colour="grey" rowspan="2" style="text-align: center;"&gt;Negev&lt;/th&gt; </code></pre> <p>I want to scrape data from the tables. when I use:</p> <pre><code>from bs4 import BeautifulSoup from urllib.request import urlopen url = 'XXX' soup = BeautifulSoup(urlopen(url).read(), "lxml") for table in soup.findAll('table'): print(table) </code></pre> <p>it only finds the first table. when I change the search to :</p> <pre><code>soup.findAll("table", { "class" : "confluenceTable" }) </code></pre> <p>it doesn't find anything. What am I missing?</p> <p>using python 3.4 on windows with BeautifulSoap 4.5</p>
1
2016-07-24T13:49:31Z
38,552,982
<p>I suspect you are trying to scrape an <em>Atlassian Confluence</em> page which is usually quite dynamic and makes use of JavaScript intensively to load the page. If you look into the HTML source you download with <code>urllib</code> you would not find <code>table</code> elements with <code>confluenceTable</code> class.</p> <p>Instead, you should either look into using <a href="https://developer.atlassian.com/confdev/confluence-server-rest-api" rel="nofollow">Confluence API</a>, or use a browser automation tool like <a href="http://selenium-python.readthedocs.io/" rel="nofollow"><code>selenium</code></a>.</p>
2
2016-07-24T14:16:02Z
[ "python", "beautifulsoup" ]
How to improve the performance of this Python code?
38,552,736
<p>Is there any way I can improve the Python code I attached below? It seems too slow for me now.</p> <pre><code>C_abs = abs(C) _, n = C_abs.shape G = np.zeros((n, n)) for i in xrange(n): for j in xrange(n): G[i,j] = C_abs[i,j]+C_abs[j,i] </code></pre>
4
2016-07-24T13:51:02Z
38,552,762
<p>Just add <code>C_abs</code> with its <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow"><code>transposed version</code></a> -</p> <pre><code>G = C_abs + C_abs.T </code></pre> <p>To understand, look at the computation part of the code :</p> <pre><code>G[i,j] = C_abs[i,j]+C_abs[j,i] </code></pre> <p>The first input on the right side is <code>C_abs[i,j]</code>, which has the same iterators involved as on the left side of the assignment - <code>G[i,j]</code>. So, for a vectorized solution, we will use it without change as the first input. The second input on the right side is <code>C_abs[j,i]</code> and its iterators are flipped version of the iterators on the left side - <code>G[i,j]</code>. This flipping in the entire array context would be the transpose of <code>C_abs</code>. Therefore, put together, we will add <code>C_abs</code> with its own transposed version to get the desired output in a vectorized manner.</p>
6
2016-07-24T13:53:21Z
[ "python", "performance", "numpy", "scipy" ]
Django: item extendable discount calculation
38,552,851
<p>I'm thinhking about e-shop django skeleton.</p> <pre><code># models.py class Category(models.Model): name = models.CharField() discount = models.DecimalField() class Product(models.Model): name = models.CharField() price = models.DecimalField() category = models.ForeignKey(Category) discount = models.DecimalField() </code></pre> <p>Now I need to calculate product final discount. It's the biggest one of the product and category discount:</p> <pre><code>class Product(models.Model): ... def get_final_discount(self): return max([self.discount, self.category.discount]) </code></pre> <p>But now I need to extend my models with Brand model. Brand model has own discount, so I need to modify Product.get_final_discount() method to consider Brand's discount in final product price calculation.</p> <p>Question: what is the best way to implement final product discount method that doesn't violate open-closed principle?</p>
0
2016-07-24T14:02:11Z
38,554,249
<p>You could make a method that checks all of your model's fields for 2 conditions: 1.) that the field is a <code>ForeignKey</code> and 2.) that the model it references has a <code>discount</code> attribute. If both are true, the method adds the value of the <code>reference_model.discount</code> to an array of discounts. This method could then be used in your <code>max()</code> function.</p> <p>Here's a working example:</p> <pre><code>from django.db import models class Category(models.Model): name = models.CharField(max_length=255) discount = models.DecimalField(decimal_places=2, max_digits=10) class Brand(models.Model): name = models.CharField(max_length=255) discount = models.DecimalField(decimal_places=2, max_digits=10) class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(decimal_places=2, max_digits=10) category = models.ForeignKey(Category) brand = models.ForeignKey(Brand) discount = models.DecimalField(decimal_places=2, max_digits=10) def get_all_discounts(self): all_fields = self._meta.get_fields() discounts = [] for field in all_fields: if field.get_internal_type() == 'ForeignKey': field_ref = getattr(self, field.name) if hasattr(field_ref, 'discount'): discounts.append(field_ref.discount) return discounts def get_final_discount(self): return max(self.get_all_discounts()) </code></pre>
0
2016-07-24T16:30:33Z
[ "python", "django", "oop", "e-commerce" ]
Getting Attribute error while Checking model
38,553,132
<p>I am creating my first model in django, I have been following The django book which was predated when compare to the django version I been using,I have created an app Book and written the below model </p> <pre><code>from django.db import models #Create your models here. class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() </code></pre> <p>when I am checking it using, py manage.py check it gives</p> <pre><code>AttributeError: module 'first' has no attribute 'books' </code></pre> <p>my website structure is <code>1)first\books(models) 2)first\first 3)first\manage.py</code></p> <p>my changes to the settings file</p> <pre><code>INSTALLED_APPS = [ #'django.contrib.admin', #'django.contrib.auth', #'django.contrib.contenttypes', #'django.contrib.sessions', #'django.contrib.messages', #'django.contrib.staticfiles', 'first.books' -- I commented the defaults as described in the book ] MIDDLEWARE_CLASSES = [ #'django.middleware.security.SecurityMiddleware', #'django.contrib.sessions.middleware.SessionMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', #'django.contrib.auth.middleware.AuthenticationMiddleware', #'django.contrib.auth.middleware.SessionAuthenticationMiddleware', #'django.contrib.messages.middleware.MessageMiddleware', #'django.middleware.clickjacking.XFrameOptionsMiddleware' ] </code></pre> <p>Can anyone shed some light I was stuck.</p> <blockquote> <p>My directory stucture</p> </blockquote> <pre><code>C:\Program Files\Python35\mywebapp\first&gt;tree /f Folder PATH listing Volume serial number is CE58-0759 C:. │ db.sqlite3 │ manage.py │ ├───books │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ └───migrations │ __init__.py │ └───first │ settings.py │ urls.py │ views.py │ wsgi.py │ __init__.py │ ├───template │ basic.html │ └───__pycache__ settings.cpython-35.pyc urls.cpython-35.pyc views.cpython-35.pyc wsgi.cpython-35.pyc __init__.cpython-35.pyc </code></pre> <blockquote> <p>my settings.py</p> </blockquote> <pre><code>import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*********' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ ''''django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',''' 'first.books', ] MIDDLEWARE_CLASSES = [ ''' 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',''' ] ROOT_URLCONF = 'first.urls' import os.path TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(__file__) ,'template').replace('\\','/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'first.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' </code></pre>
0
2016-07-24T14:28:42Z
38,553,395
<p>Your app is named <code>books</code>, so <code>books</code> (and not <code>first.books</code>) should be included as the <code>app_name</code> in your <code>INSTALLED_APPS</code> setting.</p>
1
2016-07-24T14:57:55Z
[ "python", "django", "django-models" ]
scrapy CSV writing
38,553,178
<p>Being new user I managed to make a spider can romper e- commerce site and extract Title and variations of each product and the output CSV file and a product line but what I will wish This is a variation by line, please can someone help me move forward in my project.</p> <p>I'm looking forward to come to the question but unfortunately I can not find an answer.</p> <p>my spider:</p> <pre><code>import scrapy from w3lib.html import remove_tags from products_crawler.items import ProductItem class DemostoreSpider(scrapy.Spider): name = "demostore" allowed_domains = ["adns-grossiste.fr"] start_urls = [ 'http://adns-grossiste.fr/17-produits-recommandes', ] download_delay = 0.5 def parse(self, response): for category_url in response.css('#categories_block_left &gt; div &gt; ul &gt; li ::attr(href)').extract(): yield scrapy.Request(category_url, callback=self.parse_category, meta={'page_number': '1'}) def parse_category(self, response): for product_url in response.css('#center_column &gt; ul &gt; li &gt; div &gt; div.right-block &gt; h5 &gt; a ::attr(href)').extract(): yield scrapy.Request(product_url, callback=self.parse_product) def parse_product(self, response): item = ProductItem() item['url'] = response.url item['title'] = response.css('#center_column &gt; div &gt; div.primary_block.clearfix &gt; div.pb-center-column.col-xs-12.col-sm-7.col- md-7.col-lg-7 &gt; h1 ::text').extract_first() item['Déclinaisons'] = remove_tags(response.css('#d_c_1852 &gt; tbody &gt;tr.combi_1852.\31 852_155.\31 852_26.odd &gt; td.tl.sorting_1 &gt; a &gt; span ::text').extract_first() or '') yield item </code></pre> <p>sample CSV wish to: <a href="http://i.stack.imgur.com/yCkDf.png" rel="nofollow">image CSV</a></p>
1
2016-07-24T14:33:31Z
38,555,015
<p>Check out <a href="http://doc.scrapy.org/en/latest/faq.html?highlight=csv#simplest-way-to-dump-all-my-scraped-items-into-a-json-csv-xml-file" rel="nofollow">official docummentation here</a> </p> <p>In short there are two approaches, the simpliest one would be just to use crawl command argument <code>--output</code> or <code>-o</code> in short. For example:</p> <pre><code>scrapy crawl myspider -o myspider.csv </code></pre> <p>Scrapy will automatically convert yielded items into a csv file. For more detailed approach check out the documentation page posted at the beginning.</p>
0
2016-07-24T17:52:59Z
[ "python", "csv", "scrapy", "scrapy-spider" ]
TypeError: not all arguments converted during string formatting postgres
38,553,237
<p>I try to add data to the database (use psycopg2.connect): </p> <pre><code>cand = Candidate('test', datetime.now(), 'test@test.t', '123123', "21", 'test', 'test', 'test', datetime.now(), "1", "1", 'test', 'M', "18", "2", "2") db.addCandidate(cand) </code></pre> <p>my function add:</p> <pre><code>def addCandidate(self, candidate): with self.connection.cursor() as cursor: cursor.execute("""INSERT INTO candidate ( name, pub_date, email, tel, age, proff, href, city, last_update, called_count, status, comment, sex, recrut_id, vacancy_id, level) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", (candidate.name, candidate.pub_date, candidate.email, candidate.tel, candidate.age, candidate.proff, candidate.href, candidate.city, candidate.last_update, candidate.called_count, candidate.status, candidate.comment, candidate.sex, candidate.recrut_id, candidate.vacancy_id, candidate.level)) self.connection.commit() </code></pre> <p>tried wrapping data in str, but nothing has changed. in pymysql.connect work fine</p>
0
2016-07-24T14:40:01Z
38,553,406
<p>I can't tell for sure because I don't know the types of your columns but it's plausible that your datetime object is not of the right format. You're sending in the datetime object not a string in the right date format. Try:</p> <pre><code>candidate.pub_date.isoformat() </code></pre> <p>or</p> <pre><code>candidate.pub_date.strftime("&lt;proper_format"&gt;) </code></pre> <p>See <a href="http://strftime.org/" rel="nofollow">http://strftime.org/</a> for format options. That may work for you.</p>
0
2016-07-24T15:00:02Z
[ "python", "postgresql", "psycopg2" ]
TypeError: not all arguments converted during string formatting postgres
38,553,237
<p>I try to add data to the database (use psycopg2.connect): </p> <pre><code>cand = Candidate('test', datetime.now(), 'test@test.t', '123123', "21", 'test', 'test', 'test', datetime.now(), "1", "1", 'test', 'M', "18", "2", "2") db.addCandidate(cand) </code></pre> <p>my function add:</p> <pre><code>def addCandidate(self, candidate): with self.connection.cursor() as cursor: cursor.execute("""INSERT INTO candidate ( name, pub_date, email, tel, age, proff, href, city, last_update, called_count, status, comment, sex, recrut_id, vacancy_id, level) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", (candidate.name, candidate.pub_date, candidate.email, candidate.tel, candidate.age, candidate.proff, candidate.href, candidate.city, candidate.last_update, candidate.called_count, candidate.status, candidate.comment, candidate.sex, candidate.recrut_id, candidate.vacancy_id, candidate.level)) self.connection.commit() </code></pre> <p>tried wrapping data in str, but nothing has changed. in pymysql.connect work fine</p>
0
2016-07-24T14:40:01Z
38,554,176
<p>In instead of <code>execute</code> do <code>mogrify</code> to check what exactly is being sent to the server: </p> <pre><code>print cursor.mogrify (""" INSERT INTO candidate ( name, pub_date, email, tel, age, proff, href, city, last_update, called_count, status, comment, sex, recrut_id, vacancy_id, level ) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )""", ( candidate.name, candidate.pub_date, candidate.email, candidate.tel, candidate.age, candidate.proff, candidate.href, candidate.city, candidate.last_update, candidate.called_count, candidate.status, candidate.comment, candidate.sex, candidate.recrut_id, candidate.vacancy_id, candidate.level ) ) </code></pre>
0
2016-07-24T16:22:46Z
[ "python", "postgresql", "psycopg2" ]